/[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 1416 by schoenebeck, Sun Oct 14 12:06:32 2007 UTC revision 3053 by schoenebeck, Wed Dec 14 18:55:08 2016 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file access library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2007 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2016 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 25  Line 25 
25    
26  #include "helper.h"  #include "helper.h"
27    
28    #include <algorithm>
29  #include <math.h>  #include <math.h>
30  #include <iostream>  #include <iostream>
31    #include <assert.h>
32    
33    /// libgig's current file format version (for extending the original Giga file
34    /// format with libgig's own custom data / custom features).
35    #define GIG_FILE_EXT_VERSION    2
36    
37  /// Initial size of the sample buffer which is used for decompression of  /// Initial size of the sample buffer which is used for decompression of
38  /// compressed sample wave streams - this value should always be bigger than  /// compressed sample wave streams - this value should always be bigger than
# Line 51  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 121  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 158  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 301  namespace { Line 275  namespace {
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 344  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 364  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 375  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 453  namespace { Line 440  namespace {
440      }      }
441    
442      /**      /**
443         * Make a (semi) deep copy of the Sample object given by @a orig (without
444         * the actual waveform data) and assign it to this object.
445         *
446         * Discussion: copying .gig samples is a bit tricky. It requires three
447         * steps:
448         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
449         *    its new sample waveform data size.
450         * 2. Saving the file (done by File::Save()) so that it gains correct size
451         *    and layout for writing the actual wave form data directly to disc
452         *    in next step.
453         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
454         *
455         * @param orig - original Sample object to be copied from
456         */
457        void Sample::CopyAssignMeta(const Sample* orig) {
458            // handle base classes
459            DLS::Sample::CopyAssignCore(orig);
460            
461            // handle actual own attributes of this class
462            Manufacturer = orig->Manufacturer;
463            Product = orig->Product;
464            SamplePeriod = orig->SamplePeriod;
465            MIDIUnityNote = orig->MIDIUnityNote;
466            FineTune = orig->FineTune;
467            SMPTEFormat = orig->SMPTEFormat;
468            SMPTEOffset = orig->SMPTEOffset;
469            Loops = orig->Loops;
470            LoopID = orig->LoopID;
471            LoopType = orig->LoopType;
472            LoopStart = orig->LoopStart;
473            LoopEnd = orig->LoopEnd;
474            LoopSize = orig->LoopSize;
475            LoopFraction = orig->LoopFraction;
476            LoopPlayCount = orig->LoopPlayCount;
477            
478            // schedule resizing this sample to the given sample's size
479            Resize(orig->GetSize());
480        }
481    
482        /**
483         * Should be called after CopyAssignMeta() and File::Save() sequence.
484         * Read more about it in the discussion of CopyAssignMeta(). This method
485         * copies the actual waveform data by disk streaming.
486         *
487         * @e CAUTION: this method is currently not thread safe! During this
488         * operation the sample must not be used for other purposes by other
489         * threads!
490         *
491         * @param orig - original Sample object to be copied from
492         */
493        void Sample::CopyAssignWave(const Sample* orig) {
494            const int iReadAtOnce = 32*1024;
495            char* buf = new char[iReadAtOnce * orig->FrameSize];
496            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
497            file_offset_t restorePos = pOrig->GetPos();
498            pOrig->SetPos(0);
499            SetPos(0);
500            for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
501                               n = pOrig->Read(buf, iReadAtOnce))
502            {
503                Write(buf, n);
504            }
505            pOrig->SetPos(restorePos);
506            delete [] buf;
507        }
508    
509        /**
510       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
511       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
512       *       *
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 513  namespace { Line 568  namespace {
568          // update '3gix' chunk          // update '3gix' chunk
569          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
570          store16(&pData[0], iSampleGroup);          store16(&pData[0], iSampleGroup);
571    
572            // if the library user toggled the "Compressed" attribute from true to
573            // false, then the EWAV chunk associated with compressed samples needs
574            // to be deleted
575            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
576            if (ewav && !Compressed) {
577                pWaveList->DeleteSubChunk(ewav);
578            }
579      }      }
580    
581      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
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 535  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 554  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 570  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 613  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 672  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
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;
745          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 713  namespace { Line 777  namespace {
777          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
778          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
779          RAMCache.Size   = 0;          RAMCache.Size   = 0;
780            RAMCache.NullExtensionSize = 0;
781      }      }
782    
783      /** @brief Resize sample.      /** @brief Resize sample.
# Line 737  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 771  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 789  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 805  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() {      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 844  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 884  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 907  namespace { Line 972  namespace {
972                                  }                                  }
973    
974                                  // reverse the sample frames for backward playback                                  // reverse the sample frames for backward playback
975                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                                  if (totalreadsamples > swapareastart) //FIXME: this if() is just a crash workaround for now (#102), but totalreadsamples <= swapareastart should never be the case, so there's probably still a bug above!
976                                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
977                              }                              }
978                          } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
979                          break;                          break;
# Line 934  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 1018  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 1033  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 1056  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 1207  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 1216  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 1250  namespace { Line 1316  namespace {
1316       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1317       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1318       */       */
1319      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1320          buffer_t result;          buffer_t result;
1321          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1322                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1323          result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);          result.Size              = (file_offset_t) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1324          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1325          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1326          return result;          return result;
# Line 1288  namespace { Line 1354  namespace {
1354          return pGroup;          return pGroup;
1355      }      }
1356    
1357        /**
1358         * Returns the CRC-32 checksum of the sample's raw wave form data at the
1359         * time when this sample's wave form data was modified for the last time
1360         * by calling Write(). This checksum only covers the raw wave form data,
1361         * not any meta informations like i.e. bit depth or loop points. Since
1362         * this method just returns the checksum stored for this sample i.e. when
1363         * the gig file was loaded, this method returns immediately. So it does no
1364         * recalcuation of the checksum with the currently available sample wave
1365         * form data.
1366         *
1367         * @see VerifyWaveData()
1368         */
1369        uint32_t Sample::GetWaveDataCRC32Checksum() {
1370            return crc;
1371        }
1372    
1373        /**
1374         * Checks the integrity of this sample's raw audio wave data. Whenever a
1375         * Sample's raw wave data is intentionally modified (i.e. by calling
1376         * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1377         * is calculated and stored/updated for this sample, along to the sample's
1378         * meta informations.
1379         *
1380         * Now by calling this method the current raw audio wave data is checked
1381         * against the already stored CRC32 check sum in order to check whether the
1382         * sample data had been damaged unintentionally for some reason. Since by
1383         * calling this method always the entire raw audio wave data has to be
1384         * read, verifying all samples this way may take a long time accordingly.
1385         * And that's also the reason why the sample integrity is not checked by
1386         * default whenever a gig file is loaded. So this method must be called
1387         * explicitly to fulfill this task.
1388         *
1389         * @param pActually - (optional) if provided, will be set to the actually
1390         *                    calculated checksum of the current raw wave form data,
1391         *                    you can get the expected checksum instead by calling
1392         *                    GetWaveDataCRC32Checksum()
1393         * @returns true if sample is OK or false if the sample is damaged
1394         * @throws Exception if no checksum had been stored to disk for this
1395         *         sample yet, or on I/O issues
1396         * @see GetWaveDataCRC32Checksum()
1397         */
1398        bool Sample::VerifyWaveData(uint32_t* pActually) {
1399            //File* pFile = static_cast<File*>(GetParent());
1400            uint32_t crc = CalculateWaveDataChecksum();
1401            if (pActually) *pActually = crc;
1402            return crc == this->crc;
1403        }
1404    
1405        uint32_t Sample::CalculateWaveDataChecksum() {
1406            const size_t sz = 20*1024; // 20kB buffer size
1407            std::vector<uint8_t> buffer(sz);
1408            buffer.resize(sz);
1409    
1410            const size_t n = sz / FrameSize;
1411            SetPos(0);
1412            uint32_t crc = 0;
1413            __resetCRC(crc);
1414            while (true) {
1415                file_offset_t nRead = Read(&buffer[0], n);
1416                if (nRead <= 0) break;
1417                __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1418            }
1419            __encodeCRC(crc);
1420            return crc;
1421        }
1422    
1423      Sample::~Sample() {      Sample::~Sample() {
1424          Instances--;          Instances--;
1425          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1304  namespace { Line 1436  namespace {
1436  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1437  // *  // *
1438    
1439      uint                               DimensionRegion::Instances       = 0;      size_t                             DimensionRegion::Instances       = 0;
1440      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1441    
1442      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
# Line 1429  namespace { Line 1561  namespace {
1561                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1562              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1563              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1564                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1565              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1566              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1567              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1498  namespace { Line 1630  namespace {
1630              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1631              EG2Decay1                       = 0.005;              EG2Decay1                       = 0.005;
1632              EG2Sustain                      = 1000;              EG2Sustain                      = 1000;
1633              EG2Release                      = 0.3;              EG2Release                      = 60;
1634              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1635              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1636              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
# Line 1577  namespace { Line 1709  namespace {
1709       */       */
1710      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1711          Instances++;          Instances++;
1712            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1713          *this = src; // default memberwise shallow copy of all parameters          *this = src; // default memberwise shallow copy of all parameters
1714          pParentList = _3ewl; // restore the chunk pointer          pParentList = _3ewl; // restore the chunk pointer
1715    
# Line 1592  namespace { Line 1725  namespace {
1725                  pSampleLoops[k] = src.pSampleLoops[k];                  pSampleLoops[k] = src.pSampleLoops[k];
1726          }          }
1727      }      }
1728        
1729        /**
1730         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1731         * and assign it to this object.
1732         *
1733         * Note that all sample pointers referenced by @a orig are simply copied as
1734         * memory address. Thus the respective samples are shared, not duplicated!
1735         *
1736         * @param orig - original DimensionRegion object to be copied from
1737         */
1738        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1739            CopyAssign(orig, NULL);
1740        }
1741    
1742        /**
1743         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1744         * and assign it to this object.
1745         *
1746         * @param orig - original DimensionRegion object to be copied from
1747         * @param mSamples - crosslink map between the foreign file's samples and
1748         *                   this file's samples
1749         */
1750        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1751            // delete all allocated data first
1752            if (VelocityTable) delete [] VelocityTable;
1753            if (pSampleLoops) delete [] pSampleLoops;
1754            
1755            // backup parent list pointer
1756            RIFF::List* p = pParentList;
1757            
1758            gig::Sample* pOriginalSample = pSample;
1759            gig::Region* pOriginalRegion = pRegion;
1760            
1761            //NOTE: copy code copied from assignment constructor above, see comment there as well
1762            
1763            *this = *orig; // default memberwise shallow copy of all parameters
1764            
1765            // restore members that shall not be altered
1766            pParentList = p; // restore the chunk pointer
1767            pRegion = pOriginalRegion;
1768            
1769            // only take the raw sample reference reference if the
1770            // two DimensionRegion objects are part of the same file
1771            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1772                pSample = pOriginalSample;
1773            }
1774            
1775            if (mSamples && mSamples->count(orig->pSample)) {
1776                pSample = mSamples->find(orig->pSample)->second;
1777            }
1778    
1779            // deep copy of owned structures
1780            if (orig->VelocityTable) {
1781                VelocityTable = new uint8_t[128];
1782                for (int k = 0 ; k < 128 ; k++)
1783                    VelocityTable[k] = orig->VelocityTable[k];
1784            }
1785            if (orig->pSampleLoops) {
1786                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1787                for (int k = 0 ; k < orig->SampleLoops ; k++)
1788                    pSampleLoops[k] = orig->pSampleLoops[k];
1789            }
1790        }
1791    
1792      /**      /**
1793       * Updates the respective member variable and updates @c SampleAttenuation       * Updates the respective member variable and updates @c SampleAttenuation
# Line 1608  namespace { Line 1804  namespace {
1804       *       *
1805       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
1806       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
1807         *
1808         * @param pProgress - callback function for progress notification
1809       */       */
1810      void DimensionRegion::UpdateChunks() {      void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1811          // first update base class's chunk          // first update base class's chunk
1812          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks(pProgress);
1813    
1814          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1815          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
# Line 1631  namespace { Line 1829  namespace {
1829    
1830          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1831    
1832          const uint32_t chunksize = _3ewa->GetNewSize();          const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1833          store32(&pData[0], chunksize); // unknown, always chunk size?          store32(&pData[0], chunksize); // unknown, always chunk size?
1834    
1835          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
# Line 1833  namespace { Line 2031  namespace {
2031          }          }
2032    
2033          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
2034                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
2035          pData[116] = eg3depth;          store16(&pData[116], eg3depth);
2036    
2037          // next 2 bytes unknown          // next 2 bytes unknown
2038    
# Line 1881  namespace { Line 2079  namespace {
2079                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2080          pData[137] = vcfbreakpoint;          pData[137] = vcfbreakpoint;
2081    
2082          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2083                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2084          pData[138] = vcfvelocity;          pData[138] = vcfvelocity;
2085    
# Line 1946  namespace { Line 2144  namespace {
2144          return pRegion;          return pRegion;
2145      }      }
2146    
2147    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2148    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2149    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2150    //#pragma GCC diagnostic push
2151    //#pragma GCC diagnostic error "-Wswitch"
2152    
2153      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2154          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2155          switch (EncodedController) {          switch (EncodedController) {
# Line 2057  namespace { Line 2261  namespace {
2261                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2262                  break;                  break;
2263    
2264                // format extension (these controllers are so far only supported by
2265                // LinuxSampler & gigedit) they will *NOT* work with
2266                // Gigasampler/GigaStudio !
2267                case _lev_ctrl_CC3_EXT:
2268                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2269                    decodedcontroller.controller_number = 3;
2270                    break;
2271                case _lev_ctrl_CC6_EXT:
2272                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2273                    decodedcontroller.controller_number = 6;
2274                    break;
2275                case _lev_ctrl_CC7_EXT:
2276                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2277                    decodedcontroller.controller_number = 7;
2278                    break;
2279                case _lev_ctrl_CC8_EXT:
2280                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2281                    decodedcontroller.controller_number = 8;
2282                    break;
2283                case _lev_ctrl_CC9_EXT:
2284                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2285                    decodedcontroller.controller_number = 9;
2286                    break;
2287                case _lev_ctrl_CC10_EXT:
2288                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2289                    decodedcontroller.controller_number = 10;
2290                    break;
2291                case _lev_ctrl_CC11_EXT:
2292                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2293                    decodedcontroller.controller_number = 11;
2294                    break;
2295                case _lev_ctrl_CC14_EXT:
2296                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2297                    decodedcontroller.controller_number = 14;
2298                    break;
2299                case _lev_ctrl_CC15_EXT:
2300                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2301                    decodedcontroller.controller_number = 15;
2302                    break;
2303                case _lev_ctrl_CC20_EXT:
2304                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2305                    decodedcontroller.controller_number = 20;
2306                    break;
2307                case _lev_ctrl_CC21_EXT:
2308                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2309                    decodedcontroller.controller_number = 21;
2310                    break;
2311                case _lev_ctrl_CC22_EXT:
2312                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2313                    decodedcontroller.controller_number = 22;
2314                    break;
2315                case _lev_ctrl_CC23_EXT:
2316                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2317                    decodedcontroller.controller_number = 23;
2318                    break;
2319                case _lev_ctrl_CC24_EXT:
2320                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2321                    decodedcontroller.controller_number = 24;
2322                    break;
2323                case _lev_ctrl_CC25_EXT:
2324                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2325                    decodedcontroller.controller_number = 25;
2326                    break;
2327                case _lev_ctrl_CC26_EXT:
2328                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2329                    decodedcontroller.controller_number = 26;
2330                    break;
2331                case _lev_ctrl_CC27_EXT:
2332                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2333                    decodedcontroller.controller_number = 27;
2334                    break;
2335                case _lev_ctrl_CC28_EXT:
2336                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2337                    decodedcontroller.controller_number = 28;
2338                    break;
2339                case _lev_ctrl_CC29_EXT:
2340                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2341                    decodedcontroller.controller_number = 29;
2342                    break;
2343                case _lev_ctrl_CC30_EXT:
2344                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2345                    decodedcontroller.controller_number = 30;
2346                    break;
2347                case _lev_ctrl_CC31_EXT:
2348                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2349                    decodedcontroller.controller_number = 31;
2350                    break;
2351                case _lev_ctrl_CC68_EXT:
2352                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2353                    decodedcontroller.controller_number = 68;
2354                    break;
2355                case _lev_ctrl_CC69_EXT:
2356                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2357                    decodedcontroller.controller_number = 69;
2358                    break;
2359                case _lev_ctrl_CC70_EXT:
2360                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2361                    decodedcontroller.controller_number = 70;
2362                    break;
2363                case _lev_ctrl_CC71_EXT:
2364                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2365                    decodedcontroller.controller_number = 71;
2366                    break;
2367                case _lev_ctrl_CC72_EXT:
2368                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2369                    decodedcontroller.controller_number = 72;
2370                    break;
2371                case _lev_ctrl_CC73_EXT:
2372                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2373                    decodedcontroller.controller_number = 73;
2374                    break;
2375                case _lev_ctrl_CC74_EXT:
2376                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2377                    decodedcontroller.controller_number = 74;
2378                    break;
2379                case _lev_ctrl_CC75_EXT:
2380                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2381                    decodedcontroller.controller_number = 75;
2382                    break;
2383                case _lev_ctrl_CC76_EXT:
2384                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2385                    decodedcontroller.controller_number = 76;
2386                    break;
2387                case _lev_ctrl_CC77_EXT:
2388                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2389                    decodedcontroller.controller_number = 77;
2390                    break;
2391                case _lev_ctrl_CC78_EXT:
2392                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2393                    decodedcontroller.controller_number = 78;
2394                    break;
2395                case _lev_ctrl_CC79_EXT:
2396                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2397                    decodedcontroller.controller_number = 79;
2398                    break;
2399                case _lev_ctrl_CC84_EXT:
2400                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2401                    decodedcontroller.controller_number = 84;
2402                    break;
2403                case _lev_ctrl_CC85_EXT:
2404                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2405                    decodedcontroller.controller_number = 85;
2406                    break;
2407                case _lev_ctrl_CC86_EXT:
2408                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2409                    decodedcontroller.controller_number = 86;
2410                    break;
2411                case _lev_ctrl_CC87_EXT:
2412                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2413                    decodedcontroller.controller_number = 87;
2414                    break;
2415                case _lev_ctrl_CC89_EXT:
2416                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2417                    decodedcontroller.controller_number = 89;
2418                    break;
2419                case _lev_ctrl_CC90_EXT:
2420                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2421                    decodedcontroller.controller_number = 90;
2422                    break;
2423                case _lev_ctrl_CC96_EXT:
2424                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2425                    decodedcontroller.controller_number = 96;
2426                    break;
2427                case _lev_ctrl_CC97_EXT:
2428                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2429                    decodedcontroller.controller_number = 97;
2430                    break;
2431                case _lev_ctrl_CC102_EXT:
2432                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2433                    decodedcontroller.controller_number = 102;
2434                    break;
2435                case _lev_ctrl_CC103_EXT:
2436                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2437                    decodedcontroller.controller_number = 103;
2438                    break;
2439                case _lev_ctrl_CC104_EXT:
2440                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2441                    decodedcontroller.controller_number = 104;
2442                    break;
2443                case _lev_ctrl_CC105_EXT:
2444                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2445                    decodedcontroller.controller_number = 105;
2446                    break;
2447                case _lev_ctrl_CC106_EXT:
2448                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2449                    decodedcontroller.controller_number = 106;
2450                    break;
2451                case _lev_ctrl_CC107_EXT:
2452                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2453                    decodedcontroller.controller_number = 107;
2454                    break;
2455                case _lev_ctrl_CC108_EXT:
2456                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2457                    decodedcontroller.controller_number = 108;
2458                    break;
2459                case _lev_ctrl_CC109_EXT:
2460                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2461                    decodedcontroller.controller_number = 109;
2462                    break;
2463                case _lev_ctrl_CC110_EXT:
2464                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2465                    decodedcontroller.controller_number = 110;
2466                    break;
2467                case _lev_ctrl_CC111_EXT:
2468                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2469                    decodedcontroller.controller_number = 111;
2470                    break;
2471                case _lev_ctrl_CC112_EXT:
2472                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2473                    decodedcontroller.controller_number = 112;
2474                    break;
2475                case _lev_ctrl_CC113_EXT:
2476                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2477                    decodedcontroller.controller_number = 113;
2478                    break;
2479                case _lev_ctrl_CC114_EXT:
2480                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2481                    decodedcontroller.controller_number = 114;
2482                    break;
2483                case _lev_ctrl_CC115_EXT:
2484                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2485                    decodedcontroller.controller_number = 115;
2486                    break;
2487                case _lev_ctrl_CC116_EXT:
2488                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2489                    decodedcontroller.controller_number = 116;
2490                    break;
2491                case _lev_ctrl_CC117_EXT:
2492                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2493                    decodedcontroller.controller_number = 117;
2494                    break;
2495                case _lev_ctrl_CC118_EXT:
2496                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2497                    decodedcontroller.controller_number = 118;
2498                    break;
2499                case _lev_ctrl_CC119_EXT:
2500                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2501                    decodedcontroller.controller_number = 119;
2502                    break;
2503    
2504              // unknown controller type              // unknown controller type
2505              default:              default:
2506                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2507          }          }
2508          return decodedcontroller;          return decodedcontroller;
2509      }      }
2510        
2511    // see above (diagnostic push not supported prior GCC 4.6)
2512    //#pragma GCC diagnostic pop
2513    
2514      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2515          _lev_ctrl_t encodedcontroller;          _lev_ctrl_t encodedcontroller;
# Line 2150  namespace { Line 2597  namespace {
2597                      case 95:                      case 95:
2598                          encodedcontroller = _lev_ctrl_effect5depth;                          encodedcontroller = _lev_ctrl_effect5depth;
2599                          break;                          break;
2600    
2601                        // format extension (these controllers are so far only
2602                        // supported by LinuxSampler & gigedit) they will *NOT*
2603                        // work with Gigasampler/GigaStudio !
2604                        case 3:
2605                            encodedcontroller = _lev_ctrl_CC3_EXT;
2606                            break;
2607                        case 6:
2608                            encodedcontroller = _lev_ctrl_CC6_EXT;
2609                            break;
2610                        case 7:
2611                            encodedcontroller = _lev_ctrl_CC7_EXT;
2612                            break;
2613                        case 8:
2614                            encodedcontroller = _lev_ctrl_CC8_EXT;
2615                            break;
2616                        case 9:
2617                            encodedcontroller = _lev_ctrl_CC9_EXT;
2618                            break;
2619                        case 10:
2620                            encodedcontroller = _lev_ctrl_CC10_EXT;
2621                            break;
2622                        case 11:
2623                            encodedcontroller = _lev_ctrl_CC11_EXT;
2624                            break;
2625                        case 14:
2626                            encodedcontroller = _lev_ctrl_CC14_EXT;
2627                            break;
2628                        case 15:
2629                            encodedcontroller = _lev_ctrl_CC15_EXT;
2630                            break;
2631                        case 20:
2632                            encodedcontroller = _lev_ctrl_CC20_EXT;
2633                            break;
2634                        case 21:
2635                            encodedcontroller = _lev_ctrl_CC21_EXT;
2636                            break;
2637                        case 22:
2638                            encodedcontroller = _lev_ctrl_CC22_EXT;
2639                            break;
2640                        case 23:
2641                            encodedcontroller = _lev_ctrl_CC23_EXT;
2642                            break;
2643                        case 24:
2644                            encodedcontroller = _lev_ctrl_CC24_EXT;
2645                            break;
2646                        case 25:
2647                            encodedcontroller = _lev_ctrl_CC25_EXT;
2648                            break;
2649                        case 26:
2650                            encodedcontroller = _lev_ctrl_CC26_EXT;
2651                            break;
2652                        case 27:
2653                            encodedcontroller = _lev_ctrl_CC27_EXT;
2654                            break;
2655                        case 28:
2656                            encodedcontroller = _lev_ctrl_CC28_EXT;
2657                            break;
2658                        case 29:
2659                            encodedcontroller = _lev_ctrl_CC29_EXT;
2660                            break;
2661                        case 30:
2662                            encodedcontroller = _lev_ctrl_CC30_EXT;
2663                            break;
2664                        case 31:
2665                            encodedcontroller = _lev_ctrl_CC31_EXT;
2666                            break;
2667                        case 68:
2668                            encodedcontroller = _lev_ctrl_CC68_EXT;
2669                            break;
2670                        case 69:
2671                            encodedcontroller = _lev_ctrl_CC69_EXT;
2672                            break;
2673                        case 70:
2674                            encodedcontroller = _lev_ctrl_CC70_EXT;
2675                            break;
2676                        case 71:
2677                            encodedcontroller = _lev_ctrl_CC71_EXT;
2678                            break;
2679                        case 72:
2680                            encodedcontroller = _lev_ctrl_CC72_EXT;
2681                            break;
2682                        case 73:
2683                            encodedcontroller = _lev_ctrl_CC73_EXT;
2684                            break;
2685                        case 74:
2686                            encodedcontroller = _lev_ctrl_CC74_EXT;
2687                            break;
2688                        case 75:
2689                            encodedcontroller = _lev_ctrl_CC75_EXT;
2690                            break;
2691                        case 76:
2692                            encodedcontroller = _lev_ctrl_CC76_EXT;
2693                            break;
2694                        case 77:
2695                            encodedcontroller = _lev_ctrl_CC77_EXT;
2696                            break;
2697                        case 78:
2698                            encodedcontroller = _lev_ctrl_CC78_EXT;
2699                            break;
2700                        case 79:
2701                            encodedcontroller = _lev_ctrl_CC79_EXT;
2702                            break;
2703                        case 84:
2704                            encodedcontroller = _lev_ctrl_CC84_EXT;
2705                            break;
2706                        case 85:
2707                            encodedcontroller = _lev_ctrl_CC85_EXT;
2708                            break;
2709                        case 86:
2710                            encodedcontroller = _lev_ctrl_CC86_EXT;
2711                            break;
2712                        case 87:
2713                            encodedcontroller = _lev_ctrl_CC87_EXT;
2714                            break;
2715                        case 89:
2716                            encodedcontroller = _lev_ctrl_CC89_EXT;
2717                            break;
2718                        case 90:
2719                            encodedcontroller = _lev_ctrl_CC90_EXT;
2720                            break;
2721                        case 96:
2722                            encodedcontroller = _lev_ctrl_CC96_EXT;
2723                            break;
2724                        case 97:
2725                            encodedcontroller = _lev_ctrl_CC97_EXT;
2726                            break;
2727                        case 102:
2728                            encodedcontroller = _lev_ctrl_CC102_EXT;
2729                            break;
2730                        case 103:
2731                            encodedcontroller = _lev_ctrl_CC103_EXT;
2732                            break;
2733                        case 104:
2734                            encodedcontroller = _lev_ctrl_CC104_EXT;
2735                            break;
2736                        case 105:
2737                            encodedcontroller = _lev_ctrl_CC105_EXT;
2738                            break;
2739                        case 106:
2740                            encodedcontroller = _lev_ctrl_CC106_EXT;
2741                            break;
2742                        case 107:
2743                            encodedcontroller = _lev_ctrl_CC107_EXT;
2744                            break;
2745                        case 108:
2746                            encodedcontroller = _lev_ctrl_CC108_EXT;
2747                            break;
2748                        case 109:
2749                            encodedcontroller = _lev_ctrl_CC109_EXT;
2750                            break;
2751                        case 110:
2752                            encodedcontroller = _lev_ctrl_CC110_EXT;
2753                            break;
2754                        case 111:
2755                            encodedcontroller = _lev_ctrl_CC111_EXT;
2756                            break;
2757                        case 112:
2758                            encodedcontroller = _lev_ctrl_CC112_EXT;
2759                            break;
2760                        case 113:
2761                            encodedcontroller = _lev_ctrl_CC113_EXT;
2762                            break;
2763                        case 114:
2764                            encodedcontroller = _lev_ctrl_CC114_EXT;
2765                            break;
2766                        case 115:
2767                            encodedcontroller = _lev_ctrl_CC115_EXT;
2768                            break;
2769                        case 116:
2770                            encodedcontroller = _lev_ctrl_CC116_EXT;
2771                            break;
2772                        case 117:
2773                            encodedcontroller = _lev_ctrl_CC117_EXT;
2774                            break;
2775                        case 118:
2776                            encodedcontroller = _lev_ctrl_CC118_EXT;
2777                            break;
2778                        case 119:
2779                            encodedcontroller = _lev_ctrl_CC119_EXT;
2780                            break;
2781    
2782                      default:                      default:
2783                          throw gig::Exception("leverage controller number is not supported by the gig format");                          throw gig::Exception("leverage controller number is not supported by the gig format");
2784                  }                  }
# Line 2372  namespace { Line 3001  namespace {
3001    
3002          // Actual Loading          // Actual Loading
3003    
3004            if (!file->GetAutoLoad()) return;
3005    
3006          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
3007    
3008          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2415  namespace { Line 3046  namespace {
3046              else              else
3047                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
3048    
3049              // load sample references              // load sample references (if auto loading is enabled)
3050              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
3051                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
3052                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
3053                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
3054                    }
3055                    GetSample(); // load global region sample reference
3056              }              }
             GetSample(); // load global region sample reference  
3057          } else {          } else {
3058              DimensionRegions = 0;              DimensionRegions = 0;
3059              for (int i = 0 ; i < 8 ; i++) {              for (int i = 0 ; i < 8 ; i++) {
# Line 2447  namespace { Line 3080  namespace {
3080       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
3081       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
3082       *       *
3083         * @param pProgress - callback function for progress notification
3084       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3085       */       */
3086      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
3087          // in the gig format we don't care about the Region's sample reference          // in the gig format we don't care about the Region's sample reference
3088          // but we still have to provide some existing one to not corrupt the          // but we still have to provide some existing one to not corrupt the
3089          // file, so to avoid the latter we simply always assign the sample of          // file, so to avoid the latter we simply always assign the sample of
# Line 2457  namespace { Line 3091  namespace {
3091          pSample = pDimensionRegions[0]->pSample;          pSample = pDimensionRegions[0]->pSample;
3092    
3093          // first update base class's chunks          // first update base class's chunks
3094          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks(pProgress);
3095    
3096          // update dimension region's chunks          // update dimension region's chunks
3097          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
3098              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks(pProgress);
3099          }          }
3100    
3101          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
# Line 2477  namespace { Line 3111  namespace {
3111              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3112    
3113              // move 3prg to last position              // move 3prg to last position
3114              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3115          }          }
3116    
3117          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
# Line 2551  namespace { Line 3185  namespace {
3185          int step = 1;          int step = 1;
3186          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3187          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3188    
3189          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3190          int dim[8] = { 0 };          int dim[8] = { 0 };
3191          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3192                const int end = i + step * pDimensionDefinitions[veldim].zones;
3193    
3194                // create a velocity table for all cases where the velocity zone is zero
3195              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3196                  pDimensionRegions[i]->VelocityUpperLimit) {                  pDimensionRegions[i]->VelocityUpperLimit) {
3197                  // create the velocity table                  // create the velocity table
# Line 2587  namespace { Line 3222  namespace {
3222                  }                  }
3223              }              }
3224    
3225                // jump to the next case where the velocity zone is zero
3226              int j;              int j;
3227              int shift = 0;              int shift = 0;
3228              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 2623  namespace { Line 3259  namespace {
3259       *                        dimension bits limit is violated       *                        dimension bits limit is violated
3260       */       */
3261      void Region::AddDimension(dimension_def_t* pDimDef) {      void Region::AddDimension(dimension_def_t* pDimDef) {
3262            // some initial sanity checks of the given dimension definition
3263            if (pDimDef->zones < 2)
3264                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3265            if (pDimDef->bits < 1)
3266                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3267            if (pDimDef->dimension == dimension_samplechannel) {
3268                if (pDimDef->zones != 2)
3269                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3270                if (pDimDef->bits != 1)
3271                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3272            }
3273    
3274          // check if max. amount of dimensions reached          // check if max. amount of dimensions reached
3275          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3276          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
# Line 2798  namespace { Line 3446  namespace {
3446          if (pDimDef->dimension == dimension_layer) Layers = 1;          if (pDimDef->dimension == dimension_layer) Layers = 1;
3447      }      }
3448    
3449        /** @brief Delete one split zone of a dimension (decrement zone amount).
3450         *
3451         * Instead of deleting an entire dimensions, this method will only delete
3452         * one particular split zone given by @a zone of the Region's dimension
3453         * given by @a type. So this method will simply decrement the amount of
3454         * zones by one of the dimension in question. To be able to do that, the
3455         * respective dimension must exist on this Region and it must have at least
3456         * 3 zones. All DimensionRegion objects associated with the zone will be
3457         * deleted.
3458         *
3459         * @param type - identifies the dimension where a zone shall be deleted
3460         * @param zone - index of the dimension split zone that shall be deleted
3461         * @throws gig::Exception if requested zone could not be deleted
3462         */
3463        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3464            dimension_def_t* oldDef = GetDimensionDefinition(type);
3465            if (!oldDef)
3466                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3467            if (oldDef->zones <= 2)
3468                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3469            if (zone < 0 || zone >= oldDef->zones)
3470                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3471    
3472            const int newZoneSize = oldDef->zones - 1;
3473    
3474            // create a temporary Region which just acts as a temporary copy
3475            // container and will be deleted at the end of this function and will
3476            // also not be visible through the API during this process
3477            gig::Region* tempRgn = NULL;
3478            {
3479                // adding these temporary chunks is probably not even necessary
3480                Instrument* instr = static_cast<Instrument*>(GetParent());
3481                RIFF::List* pCkInstrument = instr->pCkInstrument;
3482                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3483                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3484                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3485                tempRgn = new Region(instr, rgn);
3486            }
3487    
3488            // copy this region's dimensions (with already the dimension split size
3489            // requested by the arguments of this method call) to the temporary
3490            // region, and don't use Region::CopyAssign() here for this task, since
3491            // it would also alter fast lookup helper variables here and there
3492            dimension_def_t newDef;
3493            for (int i = 0; i < Dimensions; ++i) {
3494                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3495                // is this the dimension requested by the method arguments? ...
3496                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3497                    def.zones = newZoneSize;
3498                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3499                    newDef = def;
3500                }
3501                tempRgn->AddDimension(&def);
3502            }
3503    
3504            // find the dimension index in the tempRegion which is the dimension
3505            // type passed to this method (paranoidly expecting different order)
3506            int tempReducedDimensionIndex = -1;
3507            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3508                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3509                    tempReducedDimensionIndex = d;
3510                    break;
3511                }
3512            }
3513    
3514            // copy dimension regions from this region to the temporary region
3515            for (int iDst = 0; iDst < 256; ++iDst) {
3516                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3517                if (!dstDimRgn) continue;
3518                std::map<dimension_t,int> dimCase;
3519                bool isValidZone = true;
3520                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3521                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3522                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3523                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3524                    baseBits += dstBits;
3525                    // there are also DimensionRegion objects of unused zones, skip them
3526                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3527                        isValidZone = false;
3528                        break;
3529                    }
3530                }
3531                if (!isValidZone) continue;
3532                // a bit paranoid: cope with the chance that the dimensions would
3533                // have different order in source and destination regions
3534                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3535                if (dimCase[type] >= zone) dimCase[type]++;
3536                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3537                dstDimRgn->CopyAssign(srcDimRgn);
3538                // if this is the upper most zone of the dimension passed to this
3539                // method, then correct (raise) its upper limit to 127
3540                if (newDef.split_type == split_type_normal && isLastZone)
3541                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3542            }
3543    
3544            // now tempRegion's dimensions and DimensionRegions basically reflect
3545            // what we wanted to get for this actual Region here, so we now just
3546            // delete and recreate the dimension in question with the new amount
3547            // zones and then copy back from tempRegion      
3548            DeleteDimension(oldDef);
3549            AddDimension(&newDef);
3550            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3551                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3552                if (!srcDimRgn) continue;
3553                std::map<dimension_t,int> dimCase;
3554                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3555                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3556                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3557                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3558                    baseBits += srcBits;
3559                }
3560                // a bit paranoid: cope with the chance that the dimensions would
3561                // have different order in source and destination regions
3562                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3563                if (!dstDimRgn) continue;
3564                dstDimRgn->CopyAssign(srcDimRgn);
3565            }
3566    
3567            // delete temporary region
3568            delete tempRgn;
3569    
3570            UpdateVelocityTable();
3571        }
3572    
3573        /** @brief Divide split zone of a dimension in two (increment zone amount).
3574         *
3575         * This will increment the amount of zones for the dimension (given by
3576         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3577         * in the middle of its zone range in two. So the two zones resulting from
3578         * the zone being splitted, will be an equivalent copy regarding all their
3579         * articulation informations and sample reference. The two zones will only
3580         * differ in their zone's upper limit
3581         * (DimensionRegion::DimensionUpperLimits).
3582         *
3583         * @param type - identifies the dimension where a zone shall be splitted
3584         * @param zone - index of the dimension split zone that shall be splitted
3585         * @throws gig::Exception if requested zone could not be splitted
3586         */
3587        void Region::SplitDimensionZone(dimension_t type, int zone) {
3588            dimension_def_t* oldDef = GetDimensionDefinition(type);
3589            if (!oldDef)
3590                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3591            if (zone < 0 || zone >= oldDef->zones)
3592                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3593    
3594            const int newZoneSize = oldDef->zones + 1;
3595    
3596            // create a temporary Region which just acts as a temporary copy
3597            // container and will be deleted at the end of this function and will
3598            // also not be visible through the API during this process
3599            gig::Region* tempRgn = NULL;
3600            {
3601                // adding these temporary chunks is probably not even necessary
3602                Instrument* instr = static_cast<Instrument*>(GetParent());
3603                RIFF::List* pCkInstrument = instr->pCkInstrument;
3604                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3605                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3606                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3607                tempRgn = new Region(instr, rgn);
3608            }
3609    
3610            // copy this region's dimensions (with already the dimension split size
3611            // requested by the arguments of this method call) to the temporary
3612            // region, and don't use Region::CopyAssign() here for this task, since
3613            // it would also alter fast lookup helper variables here and there
3614            dimension_def_t newDef;
3615            for (int i = 0; i < Dimensions; ++i) {
3616                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3617                // is this the dimension requested by the method arguments? ...
3618                if (def.dimension == type) { // ... if yes, increment zone amount by one
3619                    def.zones = newZoneSize;
3620                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3621                    newDef = def;
3622                }
3623                tempRgn->AddDimension(&def);
3624            }
3625    
3626            // find the dimension index in the tempRegion which is the dimension
3627            // type passed to this method (paranoidly expecting different order)
3628            int tempIncreasedDimensionIndex = -1;
3629            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3630                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3631                    tempIncreasedDimensionIndex = d;
3632                    break;
3633                }
3634            }
3635    
3636            // copy dimension regions from this region to the temporary region
3637            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3638                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3639                if (!srcDimRgn) continue;
3640                std::map<dimension_t,int> dimCase;
3641                bool isValidZone = true;
3642                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3643                    const int srcBits = pDimensionDefinitions[d].bits;
3644                    dimCase[pDimensionDefinitions[d].dimension] =
3645                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3646                    // there are also DimensionRegion objects for unused zones, skip them
3647                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3648                        isValidZone = false;
3649                        break;
3650                    }
3651                    baseBits += srcBits;
3652                }
3653                if (!isValidZone) continue;
3654                // a bit paranoid: cope with the chance that the dimensions would
3655                // have different order in source and destination regions            
3656                if (dimCase[type] > zone) dimCase[type]++;
3657                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3658                dstDimRgn->CopyAssign(srcDimRgn);
3659                // if this is the requested zone to be splitted, then also copy
3660                // the source DimensionRegion to the newly created target zone
3661                // and set the old zones upper limit lower
3662                if (dimCase[type] == zone) {
3663                    // lower old zones upper limit
3664                    if (newDef.split_type == split_type_normal) {
3665                        const int high =
3666                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3667                        int low = 0;
3668                        if (zone > 0) {
3669                            std::map<dimension_t,int> lowerCase = dimCase;
3670                            lowerCase[type]--;
3671                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3672                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3673                        }
3674                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3675                    }
3676                    // fill the newly created zone of the divided zone as well
3677                    dimCase[type]++;
3678                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3679                    dstDimRgn->CopyAssign(srcDimRgn);
3680                }
3681            }
3682    
3683            // now tempRegion's dimensions and DimensionRegions basically reflect
3684            // what we wanted to get for this actual Region here, so we now just
3685            // delete and recreate the dimension in question with the new amount
3686            // zones and then copy back from tempRegion      
3687            DeleteDimension(oldDef);
3688            AddDimension(&newDef);
3689            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3690                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3691                if (!srcDimRgn) continue;
3692                std::map<dimension_t,int> dimCase;
3693                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3694                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3695                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3696                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3697                    baseBits += srcBits;
3698                }
3699                // a bit paranoid: cope with the chance that the dimensions would
3700                // have different order in source and destination regions
3701                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3702                if (!dstDimRgn) continue;
3703                dstDimRgn->CopyAssign(srcDimRgn);
3704            }
3705    
3706            // delete temporary region
3707            delete tempRgn;
3708    
3709            UpdateVelocityTable();
3710        }
3711    
3712        /** @brief Change type of an existing dimension.
3713         *
3714         * Alters the dimension type of a dimension already existing on this
3715         * region. If there is currently no dimension on this Region with type
3716         * @a oldType, then this call with throw an Exception. Likewise there are
3717         * cases where the requested dimension type cannot be performed. For example
3718         * if the new dimension type shall be gig::dimension_samplechannel, and the
3719         * current dimension has more than 2 zones. In such cases an Exception is
3720         * thrown as well.
3721         *
3722         * @param oldType - identifies the existing dimension to be changed
3723         * @param newType - to which dimension type it should be changed to
3724         * @throws gig::Exception if requested change cannot be performed
3725         */
3726        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3727            if (oldType == newType) return;
3728            dimension_def_t* def = GetDimensionDefinition(oldType);
3729            if (!def)
3730                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3731            if (newType == dimension_samplechannel && def->zones != 2)
3732                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3733            if (GetDimensionDefinition(newType))
3734                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3735            def->dimension  = newType;
3736            def->split_type = __resolveSplitType(newType);
3737        }
3738    
3739        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3740            uint8_t bits[8] = {};
3741            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3742                 it != DimCase.end(); ++it)
3743            {
3744                for (int d = 0; d < Dimensions; ++d) {
3745                    if (pDimensionDefinitions[d].dimension == it->first) {
3746                        bits[d] = it->second;
3747                        goto nextDimCaseSlice;
3748                    }
3749                }
3750                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3751                nextDimCaseSlice:
3752                ; // noop
3753            }
3754            return GetDimensionRegionByBit(bits);
3755        }
3756    
3757        /**
3758         * Searches in the current Region for a dimension of the given dimension
3759         * type and returns the precise configuration of that dimension in this
3760         * Region.
3761         *
3762         * @param type - dimension type of the sought dimension
3763         * @returns dimension definition or NULL if there is no dimension with
3764         *          sought type in this Region.
3765         */
3766        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3767            for (int i = 0; i < Dimensions; ++i)
3768                if (pDimensionDefinitions[i].dimension == type)
3769                    return &pDimensionDefinitions[i];
3770            return NULL;
3771        }
3772    
3773      Region::~Region() {      Region::~Region() {
3774          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
3775              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
# Line 2825  namespace { Line 3797  namespace {
3797      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3798          uint8_t bits;          uint8_t bits;
3799          int veldim = -1;          int veldim = -1;
3800          int velbitpos;          int velbitpos = 0;
3801          int bitpos = 0;          int bitpos = 0;
3802          int dimregidx = 0;          int dimregidx = 0;
3803          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 2855  namespace { Line 3827  namespace {
3827              }              }
3828              bitpos += pDimensionDefinitions[i].bits;              bitpos += pDimensionDefinitions[i].bits;
3829          }          }
3830          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3831            if (!dimreg) return NULL;
3832          if (veldim != -1) {          if (veldim != -1) {
3833              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3834              if (dimreg->VelocityTable) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3835                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3836              else // normal split type              else // normal split type
3837                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3838    
3839              dimregidx |= bits << velbitpos;              const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3840              dimreg = pDimensionRegions[dimregidx];              dimregidx |= (bits & limiter_mask) << velbitpos;
3841                dimreg = pDimensionRegions[dimregidx & 255];
3842          }          }
3843          return dimreg;          return dimreg;
3844      }      }
3845    
3846        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3847            uint8_t bits;
3848            int veldim = -1;
3849            int velbitpos = 0;
3850            int bitpos = 0;
3851            int dimregidx = 0;
3852            for (uint i = 0; i < Dimensions; i++) {
3853                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3854                    // the velocity dimension must be handled after the other dimensions
3855                    veldim = i;
3856                    velbitpos = bitpos;
3857                } else {
3858                    switch (pDimensionDefinitions[i].split_type) {
3859                        case split_type_normal:
3860                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3861                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3862                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3863                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3864                                }
3865                            } else {
3866                                // gig2: evenly sized zones
3867                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3868                            }
3869                            break;
3870                        case split_type_bit: // the value is already the sought dimension bit number
3871                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3872                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3873                            break;
3874                    }
3875                    dimregidx |= bits << bitpos;
3876                }
3877                bitpos += pDimensionDefinitions[i].bits;
3878            }
3879            dimregidx &= 255;
3880            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3881            if (!dimreg) return -1;
3882            if (veldim != -1) {
3883                // (dimreg is now the dimension region for the lowest velocity)
3884                if (dimreg->VelocityTable) // custom defined zone ranges
3885                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3886                else // normal split type
3887                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3888    
3889                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3890                dimregidx |= (bits & limiter_mask) << velbitpos;
3891                dimregidx &= 255;
3892            }
3893            return dimregidx;
3894        }
3895    
3896      /**      /**
3897       * Returns the appropriate DimensionRegion for the given dimension bit       * Returns the appropriate DimensionRegion for the given dimension bit
3898       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
# Line 2907  namespace { Line 3931  namespace {
3931          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
3932          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3933          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
3934          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
3935          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
3936          Sample* sample = file->GetFirstSample(pProgress);              // use 64 bit wave pool offsets (treating this as large file)
3937          while (sample) {              uint64_t soughtoffset =
3938              if (sample->ulWavePoolOffset == soughtoffset &&                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
3939                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
3940              sample = file->GetNextSample();              Sample* sample = file->GetFirstSample(pProgress);
3941                while (sample) {
3942                    if (sample->ullWavePoolOffset == soughtoffset)
3943                        return static_cast<gig::Sample*>(sample);
3944                    sample = file->GetNextSample();
3945                }
3946            } else {
3947                // use extension files and 32 bit wave pool offsets
3948                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3949                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3950                Sample* sample = file->GetFirstSample(pProgress);
3951                while (sample) {
3952                    if (sample->ullWavePoolOffset == soughtoffset &&
3953                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3954                    sample = file->GetNextSample();
3955                }
3956            }
3957            return NULL;
3958        }
3959        
3960        /**
3961         * Make a (semi) deep copy of the Region object given by @a orig
3962         * and assign it to this object.
3963         *
3964         * Note that all sample pointers referenced by @a orig are simply copied as
3965         * memory address. Thus the respective samples are shared, not duplicated!
3966         *
3967         * @param orig - original Region object to be copied from
3968         */
3969        void Region::CopyAssign(const Region* orig) {
3970            CopyAssign(orig, NULL);
3971        }
3972        
3973        /**
3974         * Make a (semi) deep copy of the Region object given by @a orig and
3975         * assign it to this object
3976         *
3977         * @param mSamples - crosslink map between the foreign file's samples and
3978         *                   this file's samples
3979         */
3980        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3981            // handle base classes
3982            DLS::Region::CopyAssign(orig);
3983            
3984            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3985                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3986            }
3987            
3988            // handle own member variables
3989            for (int i = Dimensions - 1; i >= 0; --i) {
3990                DeleteDimension(&pDimensionDefinitions[i]);
3991            }
3992            Layers = 0; // just to be sure
3993            for (int i = 0; i < orig->Dimensions; i++) {
3994                // we need to copy the dim definition here, to avoid the compiler
3995                // complaining about const-ness issue
3996                dimension_def_t def = orig->pDimensionDefinitions[i];
3997                AddDimension(&def);
3998            }
3999            for (int i = 0; i < 256; i++) {
4000                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
4001                    pDimensionRegions[i]->CopyAssign(
4002                        orig->pDimensionRegions[i],
4003                        mSamples
4004                    );
4005                }
4006            }
4007            Layers = orig->Layers;
4008        }
4009    
4010    
4011    // *************** MidiRule ***************
4012    // *
4013    
4014        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
4015            _3ewg->SetPos(36);
4016            Triggers = _3ewg->ReadUint8();
4017            _3ewg->SetPos(40);
4018            ControllerNumber = _3ewg->ReadUint8();
4019            _3ewg->SetPos(46);
4020            for (int i = 0 ; i < Triggers ; i++) {
4021                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
4022                pTriggers[i].Descending = _3ewg->ReadUint8();
4023                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
4024                pTriggers[i].Key = _3ewg->ReadUint8();
4025                pTriggers[i].NoteOff = _3ewg->ReadUint8();
4026                pTriggers[i].Velocity = _3ewg->ReadUint8();
4027                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
4028                _3ewg->ReadUint8();
4029            }
4030        }
4031    
4032        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
4033            ControllerNumber(0),
4034            Triggers(0) {
4035        }
4036    
4037        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
4038            pData[32] = 4;
4039            pData[33] = 16;
4040            pData[36] = Triggers;
4041            pData[40] = ControllerNumber;
4042            for (int i = 0 ; i < Triggers ; i++) {
4043                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
4044                pData[47 + i * 8] = pTriggers[i].Descending;
4045                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
4046                pData[49 + i * 8] = pTriggers[i].Key;
4047                pData[50 + i * 8] = pTriggers[i].NoteOff;
4048                pData[51 + i * 8] = pTriggers[i].Velocity;
4049                pData[52 + i * 8] = pTriggers[i].OverridePedal;
4050            }
4051        }
4052    
4053        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
4054            _3ewg->SetPos(36);
4055            LegatoSamples = _3ewg->ReadUint8(); // always 12
4056            _3ewg->SetPos(40);
4057            BypassUseController = _3ewg->ReadUint8();
4058            BypassKey = _3ewg->ReadUint8();
4059            BypassController = _3ewg->ReadUint8();
4060            ThresholdTime = _3ewg->ReadUint16();
4061            _3ewg->ReadInt16();
4062            ReleaseTime = _3ewg->ReadUint16();
4063            _3ewg->ReadInt16();
4064            KeyRange.low = _3ewg->ReadUint8();
4065            KeyRange.high = _3ewg->ReadUint8();
4066            _3ewg->SetPos(64);
4067            ReleaseTriggerKey = _3ewg->ReadUint8();
4068            AltSustain1Key = _3ewg->ReadUint8();
4069            AltSustain2Key = _3ewg->ReadUint8();
4070        }
4071    
4072        MidiRuleLegato::MidiRuleLegato() :
4073            LegatoSamples(12),
4074            BypassUseController(false),
4075            BypassKey(0),
4076            BypassController(1),
4077            ThresholdTime(20),
4078            ReleaseTime(20),
4079            ReleaseTriggerKey(0),
4080            AltSustain1Key(0),
4081            AltSustain2Key(0)
4082        {
4083            KeyRange.low = KeyRange.high = 0;
4084        }
4085    
4086        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
4087            pData[32] = 0;
4088            pData[33] = 16;
4089            pData[36] = LegatoSamples;
4090            pData[40] = BypassUseController;
4091            pData[41] = BypassKey;
4092            pData[42] = BypassController;
4093            store16(&pData[43], ThresholdTime);
4094            store16(&pData[47], ReleaseTime);
4095            pData[51] = KeyRange.low;
4096            pData[52] = KeyRange.high;
4097            pData[64] = ReleaseTriggerKey;
4098            pData[65] = AltSustain1Key;
4099            pData[66] = AltSustain2Key;
4100        }
4101    
4102        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4103            _3ewg->SetPos(36);
4104            Articulations = _3ewg->ReadUint8();
4105            int flags = _3ewg->ReadUint8();
4106            Polyphonic = flags & 8;
4107            Chained = flags & 4;
4108            Selector = (flags & 2) ? selector_controller :
4109                (flags & 1) ? selector_key_switch : selector_none;
4110            Patterns = _3ewg->ReadUint8();
4111            _3ewg->ReadUint8(); // chosen row
4112            _3ewg->ReadUint8(); // unknown
4113            _3ewg->ReadUint8(); // unknown
4114            _3ewg->ReadUint8(); // unknown
4115            KeySwitchRange.low = _3ewg->ReadUint8();
4116            KeySwitchRange.high = _3ewg->ReadUint8();
4117            Controller = _3ewg->ReadUint8();
4118            PlayRange.low = _3ewg->ReadUint8();
4119            PlayRange.high = _3ewg->ReadUint8();
4120    
4121            int n = std::min(int(Articulations), 32);
4122            for (int i = 0 ; i < n ; i++) {
4123                _3ewg->ReadString(pArticulations[i], 32);
4124            }
4125            _3ewg->SetPos(1072);
4126            n = std::min(int(Patterns), 32);
4127            for (int i = 0 ; i < n ; i++) {
4128                _3ewg->ReadString(pPatterns[i].Name, 16);
4129                pPatterns[i].Size = _3ewg->ReadUint8();
4130                _3ewg->Read(&pPatterns[i][0], 1, 32);
4131            }
4132        }
4133    
4134        MidiRuleAlternator::MidiRuleAlternator() :
4135            Articulations(0),
4136            Patterns(0),
4137            Selector(selector_none),
4138            Controller(0),
4139            Polyphonic(false),
4140            Chained(false)
4141        {
4142            PlayRange.low = PlayRange.high = 0;
4143            KeySwitchRange.low = KeySwitchRange.high = 0;
4144        }
4145    
4146        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4147            pData[32] = 3;
4148            pData[33] = 16;
4149            pData[36] = Articulations;
4150            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4151                (Selector == selector_controller ? 2 :
4152                 (Selector == selector_key_switch ? 1 : 0));
4153            pData[38] = Patterns;
4154    
4155            pData[43] = KeySwitchRange.low;
4156            pData[44] = KeySwitchRange.high;
4157            pData[45] = Controller;
4158            pData[46] = PlayRange.low;
4159            pData[47] = PlayRange.high;
4160    
4161            char* str = reinterpret_cast<char*>(pData);
4162            int pos = 48;
4163            int n = std::min(int(Articulations), 32);
4164            for (int i = 0 ; i < n ; i++, pos += 32) {
4165                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4166            }
4167    
4168            pos = 1072;
4169            n = std::min(int(Patterns), 32);
4170            for (int i = 0 ; i < n ; i++, pos += 49) {
4171                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4172                pData[pos + 16] = pPatterns[i].Size;
4173                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4174            }
4175        }
4176    
4177    // *************** Script ***************
4178    // *
4179    
4180        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4181            pGroup = group;
4182            pChunk = ckScri;
4183            if (ckScri) { // object is loaded from file ...
4184                // read header
4185                uint32_t headerSize = ckScri->ReadUint32();
4186                Compression = (Compression_t) ckScri->ReadUint32();
4187                Encoding    = (Encoding_t) ckScri->ReadUint32();
4188                Language    = (Language_t) ckScri->ReadUint32();
4189                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4190                crc         = ckScri->ReadUint32();
4191                uint32_t nameSize = ckScri->ReadUint32();
4192                Name.resize(nameSize, ' ');
4193                for (int i = 0; i < nameSize; ++i)
4194                    Name[i] = ckScri->ReadUint8();
4195                // to handle potential future extensions of the header
4196                ckScri->SetPos(sizeof(int32_t) + headerSize);
4197                // read actual script data
4198                uint32_t scriptSize = uint32_t(ckScri->GetSize() - ckScri->GetPos());
4199                data.resize(scriptSize);
4200                for (int i = 0; i < scriptSize; ++i)
4201                    data[i] = ckScri->ReadUint8();
4202            } else { // this is a new script object, so just initialize it as such ...
4203                Compression = COMPRESSION_NONE;
4204                Encoding = ENCODING_ASCII;
4205                Language = LANGUAGE_NKSP;
4206                Bypass   = false;
4207                crc      = 0;
4208                Name     = "Unnamed Script";
4209            }
4210        }
4211    
4212        Script::~Script() {
4213        }
4214    
4215        /**
4216         * Returns the current script (i.e. as source code) in text format.
4217         */
4218        String Script::GetScriptAsText() {
4219            String s;
4220            s.resize(data.size(), ' ');
4221            memcpy(&s[0], &data[0], data.size());
4222            return s;
4223        }
4224    
4225        /**
4226         * Replaces the current script with the new script source code text given
4227         * by @a text.
4228         *
4229         * @param text - new script source code
4230         */
4231        void Script::SetScriptAsText(const String& text) {
4232            data.resize(text.size());
4233            memcpy(&data[0], &text[0], text.size());
4234        }
4235    
4236        /**
4237         * Apply this script to the respective RIFF chunks. You have to call
4238         * File::Save() to make changes persistent.
4239         *
4240         * Usually there is absolutely no need to call this method explicitly.
4241         * It will be called automatically when File::Save() was called.
4242         *
4243         * @param pProgress - callback function for progress notification
4244         */
4245        void Script::UpdateChunks(progress_t* pProgress) {
4246            // recalculate CRC32 check sum
4247            __resetCRC(crc);
4248            __calculateCRC(&data[0], data.size(), crc);
4249            __encodeCRC(crc);
4250            // make sure chunk exists and has the required size
4251            const file_offset_t chunkSize = (file_offset_t) 7*sizeof(int32_t) + Name.size() + data.size();
4252            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4253            else pChunk->Resize(chunkSize);
4254            // fill the chunk data to be written to disk
4255            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4256            int pos = 0;
4257            store32(&pData[pos], uint32_t(6*sizeof(int32_t) + Name.size())); // total header size
4258            pos += sizeof(int32_t);
4259            store32(&pData[pos], Compression);
4260            pos += sizeof(int32_t);
4261            store32(&pData[pos], Encoding);
4262            pos += sizeof(int32_t);
4263            store32(&pData[pos], Language);
4264            pos += sizeof(int32_t);
4265            store32(&pData[pos], Bypass ? 1 : 0);
4266            pos += sizeof(int32_t);
4267            store32(&pData[pos], crc);
4268            pos += sizeof(int32_t);
4269            store32(&pData[pos], (uint32_t) Name.size());
4270            pos += sizeof(int32_t);
4271            for (int i = 0; i < Name.size(); ++i, ++pos)
4272                pData[pos] = Name[i];
4273            for (int i = 0; i < data.size(); ++i, ++pos)
4274                pData[pos] = data[i];
4275        }
4276    
4277        /**
4278         * Move this script from its current ScriptGroup to another ScriptGroup
4279         * given by @a pGroup.
4280         *
4281         * @param pGroup - script's new group
4282         */
4283        void Script::SetGroup(ScriptGroup* pGroup) {
4284            if (this->pGroup == pGroup) return;
4285            if (pChunk)
4286                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4287            this->pGroup = pGroup;
4288        }
4289    
4290        /**
4291         * Returns the script group this script currently belongs to. Each script
4292         * is a member of exactly one ScriptGroup.
4293         *
4294         * @returns current script group
4295         */
4296        ScriptGroup* Script::GetGroup() const {
4297            return pGroup;
4298        }
4299    
4300        void Script::RemoveAllScriptReferences() {
4301            File* pFile = pGroup->pFile;
4302            for (int i = 0; pFile->GetInstrument(i); ++i) {
4303                Instrument* instr = pFile->GetInstrument(i);
4304                instr->RemoveScript(this);
4305            }
4306        }
4307    
4308    // *************** ScriptGroup ***************
4309    // *
4310    
4311        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4312            pFile = file;
4313            pList = lstRTIS;
4314            pScripts = NULL;
4315            if (lstRTIS) {
4316                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4317                ::LoadString(ckName, Name);
4318            } else {
4319                Name = "Default Group";
4320            }
4321        }
4322    
4323        ScriptGroup::~ScriptGroup() {
4324            if (pScripts) {
4325                std::list<Script*>::iterator iter = pScripts->begin();
4326                std::list<Script*>::iterator end  = pScripts->end();
4327                while (iter != end) {
4328                    delete *iter;
4329                    ++iter;
4330                }
4331                delete pScripts;
4332            }
4333        }
4334    
4335        /**
4336         * Apply this script group to the respective RIFF chunks. You have to call
4337         * File::Save() to make changes persistent.
4338         *
4339         * Usually there is absolutely no need to call this method explicitly.
4340         * It will be called automatically when File::Save() was called.
4341         *
4342         * @param pProgress - callback function for progress notification
4343         */
4344        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4345            if (pScripts) {
4346                if (!pList)
4347                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4348    
4349                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4350                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4351    
4352                for (std::list<Script*>::iterator it = pScripts->begin();
4353                     it != pScripts->end(); ++it)
4354                {
4355                    (*it)->UpdateChunks(pProgress);
4356                }
4357          }          }
4358        }
4359    
4360        /** @brief Get instrument script.
4361         *
4362         * Returns the real-time instrument script with the given index.
4363         *
4364         * @param index - number of the sought script (0..n)
4365         * @returns sought script or NULL if there's no such script
4366         */
4367        Script* ScriptGroup::GetScript(uint index) {
4368            if (!pScripts) LoadScripts();
4369            std::list<Script*>::iterator it = pScripts->begin();
4370            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4371                if (i == index) return *it;
4372          return NULL;          return NULL;
4373      }      }
4374    
4375        /** @brief Add new instrument script.
4376         *
4377         * Adds a new real-time instrument script to the file. The script is not
4378         * actually used / executed unless it is referenced by an instrument to be
4379         * used. This is similar to samples, which you can add to a file, without
4380         * an instrument necessarily actually using it.
4381         *
4382         * You have to call Save() to make this persistent to the file.
4383         *
4384         * @return new empty script object
4385         */
4386        Script* ScriptGroup::AddScript() {
4387            if (!pScripts) LoadScripts();
4388            Script* pScript = new Script(this, NULL);
4389            pScripts->push_back(pScript);
4390            return pScript;
4391        }
4392    
4393        /** @brief Delete an instrument script.
4394         *
4395         * This will delete the given real-time instrument script. References of
4396         * instruments that are using that script will be removed accordingly.
4397         *
4398         * You have to call Save() to make this persistent to the file.
4399         *
4400         * @param pScript - script to delete
4401         * @throws gig::Exception if given script could not be found
4402         */
4403        void ScriptGroup::DeleteScript(Script* pScript) {
4404            if (!pScripts) LoadScripts();
4405            std::list<Script*>::iterator iter =
4406                find(pScripts->begin(), pScripts->end(), pScript);
4407            if (iter == pScripts->end())
4408                throw gig::Exception("Could not delete script, could not find given script");
4409            pScripts->erase(iter);
4410            pScript->RemoveAllScriptReferences();
4411            if (pScript->pChunk)
4412                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4413            delete pScript;
4414        }
4415    
4416        void ScriptGroup::LoadScripts() {
4417            if (pScripts) return;
4418            pScripts = new std::list<Script*>;
4419            if (!pList) return;
4420    
4421            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4422                 ck = pList->GetNextSubChunk())
4423            {
4424                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4425                    pScripts->push_back(new Script(this, ck));
4426                }
4427            }
4428        }
4429    
4430  // *************** Instrument ***************  // *************** Instrument ***************
4431  // *  // *
# Line 2940  namespace { Line 4447  namespace {
4447          PianoReleaseMode = false;          PianoReleaseMode = false;
4448          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
4449          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
4450            pMidiRules = new MidiRule*[3];
4451            pMidiRules[0] = NULL;
4452            pScriptRefs = NULL;
4453    
4454          // Loading          // Loading
4455          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2954  namespace { Line 4464  namespace {
4464                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
4465                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
4466                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
4467    
4468                    if (_3ewg->GetSize() > 32) {
4469                        // read MIDI rules
4470                        int i = 0;
4471                        _3ewg->SetPos(32);
4472                        uint8_t id1 = _3ewg->ReadUint8();
4473                        uint8_t id2 = _3ewg->ReadUint8();
4474    
4475                        if (id2 == 16) {
4476                            if (id1 == 4) {
4477                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4478                            } else if (id1 == 0) {
4479                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4480                            } else if (id1 == 3) {
4481                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4482                            } else {
4483                                pMidiRules[i++] = new MidiRuleUnknown;
4484                            }
4485                        }
4486                        else if (id1 != 0 || id2 != 0) {
4487                            pMidiRules[i++] = new MidiRuleUnknown;
4488                        }
4489                        //TODO: all the other types of rules
4490    
4491                        pMidiRules[i] = NULL;
4492                    }
4493                }
4494            }
4495    
4496            if (pFile->GetAutoLoad()) {
4497                if (!pRegions) pRegions = new RegionList;
4498                RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4499                if (lrgn) {
4500                    RIFF::List* rgn = lrgn->GetFirstSubList();
4501                    while (rgn) {
4502                        if (rgn->GetListType() == LIST_TYPE_RGN) {
4503                            __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4504                            pRegions->push_back(new Region(this, rgn));
4505                        }
4506                        rgn = lrgn->GetNextSubList();
4507                    }
4508                    // Creating Region Key Table for fast lookup
4509                    UpdateRegionKeyTable();
4510              }              }
4511          }          }
4512    
4513          if (!pRegions) pRegions = new RegionList;          // own gig format extensions
4514          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4515          if (lrgn) {          if (lst3LS) {
4516              RIFF::List* rgn = lrgn->GetFirstSubList();              RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4517              while (rgn) {              if (ckSCSL) {
4518                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  int headerSize = ckSCSL->ReadUint32();
4519                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                  int slotCount  = ckSCSL->ReadUint32();
4520                      pRegions->push_back(new Region(this, rgn));                  if (slotCount) {
4521                        int slotSize  = ckSCSL->ReadUint32();
4522                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4523                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4524                        for (int i = 0; i < slotCount; ++i) {
4525                            _ScriptPooolEntry e;
4526                            e.fileOffset = ckSCSL->ReadUint32();
4527                            e.bypass     = ckSCSL->ReadUint32() & 1;
4528                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4529                            scriptPoolFileOffsets.push_back(e);
4530                        }
4531                  }                  }
                 rgn = lrgn->GetNextSubList();  
4532              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
4533          }          }
4534    
4535          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
# Line 2988  namespace { Line 4548  namespace {
4548      }      }
4549    
4550      Instrument::~Instrument() {      Instrument::~Instrument() {
4551            for (int i = 0 ; pMidiRules[i] ; i++) {
4552                delete pMidiRules[i];
4553            }
4554            delete[] pMidiRules;
4555            if (pScriptRefs) delete pScriptRefs;
4556      }      }
4557    
4558      /**      /**
# Line 2997  namespace { Line 4562  namespace {
4562       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
4563       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
4564       *       *
4565         * @param pProgress - callback function for progress notification
4566       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
4567       */       */
4568      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
4569          // first update base classes' chunks          // first update base classes' chunks
4570          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks(pProgress);
4571    
4572          // update Regions' chunks          // update Regions' chunks
4573          {          {
4574              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
4575              RegionList::iterator end  = pRegions->end();              RegionList::iterator end  = pRegions->end();
4576              for (; iter != end; ++iter)              for (; iter != end; ++iter)
4577                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
4578          }          }
4579    
4580          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
# Line 3034  namespace { Line 4600  namespace {
4600                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
4601          pData[10] = dimkeystart;          pData[10] = dimkeystart;
4602          pData[11] = DimensionKeyRange.high;          pData[11] = DimensionKeyRange.high;
4603    
4604            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4605                pData[32] = 0;
4606                pData[33] = 0;
4607            } else {
4608                for (int i = 0 ; pMidiRules[i] ; i++) {
4609                    pMidiRules[i]->UpdateChunks(pData);
4610                }
4611            }
4612    
4613            // own gig format extensions
4614           if (ScriptSlotCount()) {
4615               // make sure we have converted the original loaded script file
4616               // offsets into valid Script object pointers
4617               LoadScripts();
4618    
4619               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4620               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4621               const int slotCount = (int) pScriptRefs->size();
4622               const int headerSize = 3 * sizeof(uint32_t);
4623               const int slotSize  = 2 * sizeof(uint32_t);
4624               const int totalChunkSize = headerSize + slotCount * slotSize;
4625               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4626               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4627               else ckSCSL->Resize(totalChunkSize);
4628               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4629               int pos = 0;
4630               store32(&pData[pos], headerSize);
4631               pos += sizeof(uint32_t);
4632               store32(&pData[pos], slotCount);
4633               pos += sizeof(uint32_t);
4634               store32(&pData[pos], slotSize);
4635               pos += sizeof(uint32_t);
4636               for (int i = 0; i < slotCount; ++i) {
4637                   // arbitrary value, the actual file offset will be updated in
4638                   // UpdateScriptFileOffsets() after the file has been resized
4639                   int bogusFileOffset = 0;
4640                   store32(&pData[pos], bogusFileOffset);
4641                   pos += sizeof(uint32_t);
4642                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4643                   pos += sizeof(uint32_t);
4644               }
4645           } else {
4646               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4647               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4648               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4649           }
4650        }
4651    
4652        void Instrument::UpdateScriptFileOffsets() {
4653           // own gig format extensions
4654           if (pScriptRefs && pScriptRefs->size() > 0) {
4655               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4656               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4657               const int slotCount = (int) pScriptRefs->size();
4658               const int headerSize = 3 * sizeof(uint32_t);
4659               ckSCSL->SetPos(headerSize);
4660               for (int i = 0; i < slotCount; ++i) {
4661                   uint32_t fileOffset = uint32_t(
4662                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4663                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4664                        CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize())
4665                   );
4666                   ckSCSL->WriteUint32(&fileOffset);
4667                   // jump over flags entry (containing the bypass flag)
4668                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4669               }
4670           }        
4671      }      }
4672    
4673      /**      /**
# Line 3088  namespace { Line 4722  namespace {
4722          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4723          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
4724          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
4725          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
4726          // update Region key table for fast lookup          // update Region key table for fast lookup
4727          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4728          // done          // done
# Line 3102  namespace { Line 4736  namespace {
4736          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4737      }      }
4738    
4739        /**
4740         * Move this instrument at the position before @arg dst.
4741         *
4742         * This method can be used to reorder the sequence of instruments in a
4743         * .gig file. This might be helpful especially on large .gig files which
4744         * contain a large number of instruments within the same .gig file. So
4745         * grouping such instruments to similar ones, can help to keep track of them
4746         * when working with such complex .gig files.
4747         *
4748         * When calling this method, this instrument will be removed from in its
4749         * current position in the instruments list and moved to the requested
4750         * target position provided by @param dst. You may also pass NULL as
4751         * argument to this method, in that case this intrument will be moved to the
4752         * very end of the .gig file's instrument list.
4753         *
4754         * You have to call Save() to make the order change persistent to the .gig
4755         * file.
4756         *
4757         * Currently this method is limited to moving the instrument within the same
4758         * .gig file. Trying to move it to another .gig file by calling this method
4759         * will throw an exception.
4760         *
4761         * @param dst - destination instrument at which this instrument will be
4762         *              moved to, or pass NULL for moving to end of list
4763         * @throw gig::Exception if this instrument and target instrument are not
4764         *                       part of the same file
4765         */
4766        void Instrument::MoveTo(Instrument* dst) {
4767            if (dst && GetParent() != dst->GetParent())
4768                throw Exception(
4769                    "gig::Instrument::MoveTo() can only be used for moving within "
4770                    "the same gig file."
4771                );
4772    
4773            File* pFile = (File*) GetParent();
4774    
4775            // move this instrument within the instrument list
4776            {
4777                File::InstrumentList& list = *pFile->pInstruments;
4778    
4779                File::InstrumentList::iterator itFrom =
4780                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4781    
4782                File::InstrumentList::iterator itTo =
4783                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4784    
4785                list.splice(itTo, list, itFrom);
4786            }
4787    
4788            // move the instrument's actual list RIFF chunk appropriately
4789            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4790            lstCkInstruments->MoveSubChunk(
4791                this->pCkInstrument,
4792                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4793            );
4794        }
4795    
4796        /**
4797         * Returns a MIDI rule of the instrument.
4798         *
4799         * The list of MIDI rules, at least in gig v3, always contains at
4800         * most two rules. The second rule can only be the DEF filter
4801         * (which currently isn't supported by libgig).
4802         *
4803         * @param i - MIDI rule number
4804         * @returns   pointer address to MIDI rule number i or NULL if there is none
4805         */
4806        MidiRule* Instrument::GetMidiRule(int i) {
4807            return pMidiRules[i];
4808        }
4809    
4810        /**
4811         * Adds the "controller trigger" MIDI rule to the instrument.
4812         *
4813         * @returns the new MIDI rule
4814         */
4815        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4816            delete pMidiRules[0];
4817            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4818            pMidiRules[0] = r;
4819            pMidiRules[1] = 0;
4820            return r;
4821        }
4822    
4823        /**
4824         * Adds the legato MIDI rule to the instrument.
4825         *
4826         * @returns the new MIDI rule
4827         */
4828        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4829            delete pMidiRules[0];
4830            MidiRuleLegato* r = new MidiRuleLegato;
4831            pMidiRules[0] = r;
4832            pMidiRules[1] = 0;
4833            return r;
4834        }
4835    
4836        /**
4837         * Adds the alternator MIDI rule to the instrument.
4838         *
4839         * @returns the new MIDI rule
4840         */
4841        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4842            delete pMidiRules[0];
4843            MidiRuleAlternator* r = new MidiRuleAlternator;
4844            pMidiRules[0] = r;
4845            pMidiRules[1] = 0;
4846            return r;
4847        }
4848    
4849        /**
4850         * Deletes a MIDI rule from the instrument.
4851         *
4852         * @param i - MIDI rule number
4853         */
4854        void Instrument::DeleteMidiRule(int i) {
4855            delete pMidiRules[i];
4856            pMidiRules[i] = 0;
4857        }
4858    
4859        void Instrument::LoadScripts() {
4860            if (pScriptRefs) return;
4861            pScriptRefs = new std::vector<_ScriptPooolRef>;
4862            if (scriptPoolFileOffsets.empty()) return;
4863            File* pFile = (File*) GetParent();
4864            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4865                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4866                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4867                    ScriptGroup* group = pFile->GetScriptGroup(i);
4868                    for (uint s = 0; group->GetScript(s); ++s) {
4869                        Script* script = group->GetScript(s);
4870                        if (script->pChunk) {
4871                            uint32_t offset = uint32_t(
4872                                script->pChunk->GetFilePos() -
4873                                script->pChunk->GetPos() -
4874                                CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize())
4875                            );
4876                            if (offset == soughtOffset)
4877                            {
4878                                _ScriptPooolRef ref;
4879                                ref.script = script;
4880                                ref.bypass = scriptPoolFileOffsets[k].bypass;
4881                                pScriptRefs->push_back(ref);
4882                                break;
4883                            }
4884                        }
4885                    }
4886                }
4887            }
4888            // we don't need that anymore
4889            scriptPoolFileOffsets.clear();
4890        }
4891    
4892        /** @brief Get instrument script (gig format extension).
4893         *
4894         * Returns the real-time instrument script of instrument script slot
4895         * @a index.
4896         *
4897         * @note This is an own format extension which did not exist i.e. in the
4898         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4899         * gigedit.
4900         *
4901         * @param index - instrument script slot index
4902         * @returns script or NULL if index is out of bounds
4903         */
4904        Script* Instrument::GetScriptOfSlot(uint index) {
4905            LoadScripts();
4906            if (index >= pScriptRefs->size()) return NULL;
4907            return pScriptRefs->at(index).script;
4908        }
4909    
4910        /** @brief Add new instrument script slot (gig format extension).
4911         *
4912         * Add the given real-time instrument script reference to this instrument,
4913         * which shall be executed by the sampler for for this instrument. The
4914         * script will be added to the end of the script list of this instrument.
4915         * The positions of the scripts in the Instrument's Script list are
4916         * relevant, because they define in which order they shall be executed by
4917         * the sampler. For this reason it is also legal to add the same script
4918         * twice to an instrument, for example you might have a script called
4919         * "MyFilter" which performs an event filter task, and you might have
4920         * another script called "MyNoteTrigger" which triggers new notes, then you
4921         * might for example have the following list of scripts on the instrument:
4922         *
4923         * 1. Script "MyFilter"
4924         * 2. Script "MyNoteTrigger"
4925         * 3. Script "MyFilter"
4926         *
4927         * Which would make sense, because the 2nd script launched new events, which
4928         * you might need to filter as well.
4929         *
4930         * There are two ways to disable / "bypass" scripts. You can either disable
4931         * a script locally for the respective script slot on an instrument (i.e. by
4932         * passing @c false to the 2nd argument of this method, or by calling
4933         * SetScriptBypassed()). Or you can disable a script globally for all slots
4934         * and all instruments by setting Script::Bypass.
4935         *
4936         * @note This is an own format extension which did not exist i.e. in the
4937         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4938         * gigedit.
4939         *
4940         * @param pScript - script that shall be executed for this instrument
4941         * @param bypass  - if enabled, the sampler shall skip executing this
4942         *                  script (in the respective list position)
4943         * @see SetScriptBypassed()
4944         */
4945        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4946            LoadScripts();
4947            _ScriptPooolRef ref = { pScript, bypass };
4948            pScriptRefs->push_back(ref);
4949        }
4950    
4951        /** @brief Flip two script slots with each other (gig format extension).
4952         *
4953         * Swaps the position of the two given scripts in the Instrument's Script
4954         * list. The positions of the scripts in the Instrument's Script list are
4955         * relevant, because they define in which order they shall be executed by
4956         * the sampler.
4957         *
4958         * @note This is an own format extension which did not exist i.e. in the
4959         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4960         * gigedit.
4961         *
4962         * @param index1 - index of the first script slot to swap
4963         * @param index2 - index of the second script slot to swap
4964         */
4965        void Instrument::SwapScriptSlots(uint index1, uint index2) {
4966            LoadScripts();
4967            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4968                return;
4969            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4970            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4971            (*pScriptRefs)[index2] = tmp;
4972        }
4973    
4974        /** @brief Remove script slot.
4975         *
4976         * Removes the script slot with the given slot index.
4977         *
4978         * @param index - index of script slot to remove
4979         */
4980        void Instrument::RemoveScriptSlot(uint index) {
4981            LoadScripts();
4982            if (index >= pScriptRefs->size()) return;
4983            pScriptRefs->erase( pScriptRefs->begin() + index );
4984        }
4985    
4986        /** @brief Remove reference to given Script (gig format extension).
4987         *
4988         * This will remove all script slots on the instrument which are referencing
4989         * the given script.
4990         *
4991         * @note This is an own format extension which did not exist i.e. in the
4992         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4993         * gigedit.
4994         *
4995         * @param pScript - script reference to remove from this instrument
4996         * @see RemoveScriptSlot()
4997         */
4998        void Instrument::RemoveScript(Script* pScript) {
4999            LoadScripts();
5000            for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5001                if ((*pScriptRefs)[i].script == pScript) {
5002                    pScriptRefs->erase( pScriptRefs->begin() + i );
5003                }
5004            }
5005        }
5006    
5007        /** @brief Instrument's amount of script slots.
5008         *
5009         * This method returns the amount of script slots this instrument currently
5010         * uses.
5011         *
5012         * A script slot is a reference of a real-time instrument script to be
5013         * executed by the sampler. The scripts will be executed by the sampler in
5014         * sequence of the slots. One (same) script may be referenced multiple
5015         * times in different slots.
5016         *
5017         * @note This is an own format extension which did not exist i.e. in the
5018         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5019         * gigedit.
5020         */
5021        uint Instrument::ScriptSlotCount() const {
5022            return uint(pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size());
5023        }
5024    
5025        /** @brief Whether script execution shall be skipped.
5026         *
5027         * Defines locally for the Script reference slot in the Instrument's Script
5028         * list, whether the script shall be skipped by the sampler regarding
5029         * execution.
5030         *
5031         * It is also possible to ignore exeuction of the script globally, for all
5032         * slots and for all instruments by setting Script::Bypass.
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         * @param index - index of the script slot on this instrument
5039         * @see Script::Bypass
5040         */
5041        bool Instrument::IsScriptSlotBypassed(uint index) {
5042            if (index >= ScriptSlotCount()) return false;
5043            return pScriptRefs ? pScriptRefs->at(index).bypass
5044                               : scriptPoolFileOffsets.at(index).bypass;
5045            
5046        }
5047    
5048        /** @brief Defines whether execution shall be skipped.
5049         *
5050         * You can call this method to define locally whether or whether not the
5051         * given script slot shall be executed by the sampler.
5052         *
5053         * @note This is an own format extension which did not exist i.e. in the
5054         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5055         * gigedit.
5056         *
5057         * @param index - script slot index on this instrument
5058         * @param bBypass - if true, the script slot will be skipped by the sampler
5059         * @see Script::Bypass
5060         */
5061        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
5062            if (index >= ScriptSlotCount()) return;
5063            if (pScriptRefs)
5064                pScriptRefs->at(index).bypass = bBypass;
5065            else
5066                scriptPoolFileOffsets.at(index).bypass = bBypass;
5067        }
5068    
5069        /**
5070         * Make a (semi) deep copy of the Instrument object given by @a orig
5071         * and assign it to this object.
5072         *
5073         * Note that all sample pointers referenced by @a orig are simply copied as
5074         * memory address. Thus the respective samples are shared, not duplicated!
5075         *
5076         * @param orig - original Instrument object to be copied from
5077         */
5078        void Instrument::CopyAssign(const Instrument* orig) {
5079            CopyAssign(orig, NULL);
5080        }
5081            
5082        /**
5083         * Make a (semi) deep copy of the Instrument object given by @a orig
5084         * and assign it to this object.
5085         *
5086         * @param orig - original Instrument object to be copied from
5087         * @param mSamples - crosslink map between the foreign file's samples and
5088         *                   this file's samples
5089         */
5090        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
5091            // handle base class
5092            // (without copying DLS region stuff)
5093            DLS::Instrument::CopyAssignCore(orig);
5094            
5095            // handle own member variables
5096            Attenuation = orig->Attenuation;
5097            EffectSend = orig->EffectSend;
5098            FineTune = orig->FineTune;
5099            PitchbendRange = orig->PitchbendRange;
5100            PianoReleaseMode = orig->PianoReleaseMode;
5101            DimensionKeyRange = orig->DimensionKeyRange;
5102            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5103            pScriptRefs = orig->pScriptRefs;
5104            
5105            // free old midi rules
5106            for (int i = 0 ; pMidiRules[i] ; i++) {
5107                delete pMidiRules[i];
5108            }
5109            //TODO: MIDI rule copying
5110            pMidiRules[0] = NULL;
5111            
5112            // delete all old regions
5113            while (Regions) DeleteRegion(GetFirstRegion());
5114            // create new regions and copy them from original
5115            {
5116                RegionList::const_iterator it = orig->pRegions->begin();
5117                for (int i = 0; i < orig->Regions; ++i, ++it) {
5118                    Region* dstRgn = AddRegion();
5119                    //NOTE: Region does semi-deep copy !
5120                    dstRgn->CopyAssign(
5121                        static_cast<gig::Region*>(*it),
5122                        mSamples
5123                    );
5124                }
5125            }
5126    
5127            UpdateRegionKeyTable();
5128        }
5129    
5130    
5131  // *************** Group ***************  // *************** Group ***************
# Line 3131  namespace { Line 5155  namespace {
5155       *       *
5156       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
5157       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
5158         *
5159         * @param pProgress - callback function for progress notification
5160       */       */
5161      void Group::UpdateChunks() {      void Group::UpdateChunks(progress_t* pProgress) {
5162          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
5163          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5164          if (!_3gri) {          if (!_3gri) {
# Line 3259  namespace { Line 5285  namespace {
5285      };      };
5286    
5287      File::File() : DLS::File() {      File::File() : DLS::File() {
5288            bAutoLoad = true;
5289          *pVersion = VERSION_3;          *pVersion = VERSION_3;
5290          pGroups = NULL;          pGroups = NULL;
5291            pScriptGroups = NULL;
5292          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5293          pInfo->ArchivalLocation = String(256, ' ');          pInfo->ArchivalLocation = String(256, ' ');
5294    
# Line 3274  namespace { Line 5302  namespace {
5302      }      }
5303    
5304      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5305            bAutoLoad = true;
5306          pGroups = NULL;          pGroups = NULL;
5307            pScriptGroups = NULL;
5308          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5309      }      }
5310    
# Line 3288  namespace { Line 5318  namespace {
5318              }              }
5319              delete pGroups;              delete pGroups;
5320          }          }
5321            if (pScriptGroups) {
5322                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5323                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5324                while (iter != end) {
5325                    delete *iter;
5326                    ++iter;
5327                }
5328                delete pScriptGroups;
5329            }
5330      }      }
5331    
5332      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 3302  namespace { Line 5341  namespace {
5341          SamplesIterator++;          SamplesIterator++;
5342          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5343      }      }
5344        
5345        /**
5346         * Returns Sample object of @a index.
5347         *
5348         * @returns sample object or NULL if index is out of bounds
5349         */
5350        Sample* File::GetSample(uint index) {
5351            if (!pSamples) LoadSamples();
5352            if (!pSamples) return NULL;
5353            DLS::File::SampleList::iterator it = pSamples->begin();
5354            for (int i = 0; i < index; ++i) {
5355                ++it;
5356                if (it == pSamples->end()) return NULL;
5357            }
5358            if (it == pSamples->end()) return NULL;
5359            return static_cast<gig::Sample*>( *it );
5360        }
5361    
5362      /** @brief Add a new sample.      /** @brief Add a new sample.
5363       *       *
# Line 3343  namespace { Line 5399  namespace {
5399          pSamples->erase(iter);          pSamples->erase(iter);
5400          delete pSample;          delete pSample;
5401    
5402            SampleList::iterator tmp = SamplesIterator;
5403          // remove all references to the sample          // remove all references to the sample
5404          for (Instrument* instrument = GetFirstInstrument() ; instrument ;          for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5405               instrument = GetNextInstrument()) {               instrument = GetNextInstrument()) {
# Line 3357  namespace { Line 5414  namespace {
5414                  }                  }
5415              }              }
5416          }          }
5417            SamplesIterator = tmp; // restore iterator
5418      }      }
5419    
5420      void File::LoadSamples() {      void File::LoadSamples() {
# Line 3377  namespace { Line 5435  namespace {
5435          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5436    
5437          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5438            // (only for old gig files < 2 GB)
5439          int lastFileNo = 0;          int lastFileNo = 0;
5440          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5441              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5442                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5443                }
5444          }          }
5445          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5446          int nameLen = name.length();          int nameLen = (int) name.length();
5447          char suffix[6];          char suffix[6];
5448          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5449    
5450          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5451              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5452              if (wvpl) {              if (wvpl) {
5453                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5454                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5455                  while (wave) {                  while (wave) {
5456                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 3397  namespace { Line 5458  namespace {
5458                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5459                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5460    
5461                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5462                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5463    
5464                          iSampleIndex++;                          iSampleIndex++;
5465                      }                      }
# Line 3447  namespace { Line 5508  namespace {
5508              progress_t subprogress;              progress_t subprogress;
5509              __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask              __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
5510              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
5511              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
5512                    GetFirstSample(&subprogress); // now force all samples to be loaded
5513              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
5514    
5515              // instrument loading subtask              // instrument loading subtask
# Line 3496  namespace { Line 5558  namespace {
5558         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
5559         return pInstrument;         return pInstrument;
5560      }      }
5561        
5562        /** @brief Add a duplicate of an existing instrument.
5563         *
5564         * Duplicates the instrument definition given by @a orig and adds it
5565         * to this file. This allows in an instrument editor application to
5566         * easily create variations of an instrument, which will be stored in
5567         * the same .gig file, sharing i.e. the same samples.
5568         *
5569         * Note that all sample pointers referenced by @a orig are simply copied as
5570         * memory address. Thus the respective samples are shared, not duplicated!
5571         *
5572         * You have to call Save() to make this persistent to the file.
5573         *
5574         * @param orig - original instrument to be copied
5575         * @returns duplicated copy of the given instrument
5576         */
5577        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
5578            Instrument* instr = AddInstrument();
5579            instr->CopyAssign(orig);
5580            return instr;
5581        }
5582        
5583        /** @brief Add content of another existing file.
5584         *
5585         * Duplicates the samples, groups and instruments of the original file
5586         * given by @a pFile and adds them to @c this File. In case @c this File is
5587         * a new one that you haven't saved before, then you have to call
5588         * SetFileName() before calling AddContentOf(), because this method will
5589         * automatically save this file during operation, which is required for
5590         * writing the sample waveform data by disk streaming.
5591         *
5592         * @param pFile - original file whose's content shall be copied from
5593         */
5594        void File::AddContentOf(File* pFile) {
5595            static int iCallCount = -1;
5596            iCallCount++;
5597            std::map<Group*,Group*> mGroups;
5598            std::map<Sample*,Sample*> mSamples;
5599            
5600            // clone sample groups
5601            for (int i = 0; pFile->GetGroup(i); ++i) {
5602                Group* g = AddGroup();
5603                g->Name =
5604                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5605                mGroups[pFile->GetGroup(i)] = g;
5606            }
5607            
5608            // clone samples (not waveform data here yet)
5609            for (int i = 0; pFile->GetSample(i); ++i) {
5610                Sample* s = AddSample();
5611                s->CopyAssignMeta(pFile->GetSample(i));
5612                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5613                mSamples[pFile->GetSample(i)] = s;
5614            }
5615            
5616            //BUG: For some reason this method only works with this additional
5617            //     Save() call in between here.
5618            //
5619            // Important: The correct one of the 2 Save() methods has to be called
5620            // here, depending on whether the file is completely new or has been
5621            // saved to disk already, otherwise it will result in data corruption.
5622            if (pRIFF->IsNew())
5623                Save(GetFileName());
5624            else
5625                Save();
5626            
5627            // clone instruments
5628            // (passing the crosslink table here for the cloned samples)
5629            for (int i = 0; pFile->GetInstrument(i); ++i) {
5630                Instrument* instr = AddInstrument();
5631                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5632            }
5633            
5634            // Mandatory: file needs to be saved to disk at this point, so this
5635            // file has the correct size and data layout for writing the samples'
5636            // waveform data to disk.
5637            Save();
5638            
5639            // clone samples' waveform data
5640            // (using direct read & write disk streaming)
5641            for (int i = 0; pFile->GetSample(i); ++i) {
5642                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5643            }
5644        }
5645    
5646      /** @brief Delete an instrument.      /** @brief Delete an instrument.
5647       *       *
# Line 3551  namespace { Line 5697  namespace {
5697          if (!_3crc) return;          if (!_3crc) return;
5698    
5699          // get the index of the sample          // get the index of the sample
5700          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;  
             }  
         }  
5701          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");
5702    
5703          // write the CRC-32 checksum to disk          // write the CRC-32 checksum to disk
5704          _3crc->SetPos(iWaveIndex * 8);          _3crc->SetPos(iWaveIndex * 8);
5705          uint32_t tmp = 1;          uint32_t one = 1;
5706          _3crc->WriteUint32(&tmp); // unknown, always 1?          _3crc->WriteUint32(&one); // always 1
5707          _3crc->WriteUint32(&crc);          _3crc->WriteUint32(&crc);
5708      }      }
5709    
5710        uint32_t File::GetSampleChecksum(Sample* pSample) {
5711            // get the index of the sample
5712            int iWaveIndex = GetWaveTableIndexOf(pSample);
5713            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5714    
5715            return GetSampleChecksumByIndex(iWaveIndex);
5716        }
5717    
5718        uint32_t File::GetSampleChecksumByIndex(int index) {
5719            if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5720    
5721            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5722            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5723            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5724            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5725    
5726            // read the CRC-32 checksum directly from disk
5727            size_t pos = index * 8;
5728            if (pos + 8 > _3crc->GetNewSize())
5729                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5730    
5731            uint32_t one = load32(&pData[pos]); // always 1
5732            if (one != 1)
5733                throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5734    
5735            return load32(&pData[pos+4]);
5736        }
5737    
5738        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5739            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5740            File::SampleList::iterator iter = pSamples->begin();
5741            File::SampleList::iterator end  = pSamples->end();
5742            for (int index = 0; iter != end; ++iter, ++index)
5743                if (*iter == pSample)
5744                    return index;
5745            return -1;
5746        }
5747    
5748        /**
5749         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5750         * the CRC32 check sums of all samples' raw wave data.
5751         *
5752         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5753         */
5754        bool File::VerifySampleChecksumTable() {
5755            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5756            if (!_3crc) return false;
5757            if (_3crc->GetNewSize() <= 0) return false;
5758            if (_3crc->GetNewSize() % 8) return false;
5759            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5760            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5761    
5762            const file_offset_t n = _3crc->GetNewSize() / 8;
5763    
5764            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5765            if (!pData) return false;
5766    
5767            for (file_offset_t i = 0; i < n; ++i) {
5768                uint32_t one = pData[i*2];
5769                if (one != 1) return false;
5770            }
5771    
5772            return true;
5773        }
5774    
5775        /**
5776         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5777         * file's checksum table with those new checksums. This might usually
5778         * just be necessary if the checksum table was damaged.
5779         *
5780         * @e IMPORTANT: The current implementation of this method only works
5781         * with files that have not been modified since it was loaded, because
5782         * it expects that no externally caused file structure changes are
5783         * required!
5784         *
5785         * Due to the expectation above, this method is currently protected
5786         * and actually only used by the command line tool "gigdump" yet.
5787         *
5788         * @returns true if Save() is required to be called after this call,
5789         *          false if no further action is required
5790         */
5791        bool File::RebuildSampleChecksumTable() {
5792            // make sure sample chunks were scanned
5793            if (!pSamples) GetFirstSample();
5794    
5795            bool bRequiresSave = false;
5796    
5797            // make sure "3CRC" chunk exists with required size
5798            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5799            if (!_3crc) {
5800                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5801                // the order of einf and 3crc is not the same in v2 and v3
5802                RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5803                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5804                bRequiresSave = true;
5805            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5806                _3crc->Resize(pSamples->size() * 8);
5807                bRequiresSave = true;
5808            }
5809    
5810            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5811                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5812                {
5813                    File::SampleList::iterator iter = pSamples->begin();
5814                    File::SampleList::iterator end  = pSamples->end();
5815                    for (; iter != end; ++iter) {
5816                        gig::Sample* pSample = (gig::Sample*) *iter;
5817                        int index = GetWaveTableIndexOf(pSample);
5818                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5819                        pData[index*2]   = 1; // always 1
5820                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5821                    }
5822                }
5823            } else { // no file structure changes necessary, so directly write to disk and we are done ...
5824                // make sure file is in write mode
5825                pRIFF->SetMode(RIFF::stream_mode_read_write);
5826                {
5827                    File::SampleList::iterator iter = pSamples->begin();
5828                    File::SampleList::iterator end  = pSamples->end();
5829                    for (; iter != end; ++iter) {
5830                        gig::Sample* pSample = (gig::Sample*) *iter;
5831                        int index = GetWaveTableIndexOf(pSample);
5832                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5833                        pSample->crc  = pSample->CalculateWaveDataChecksum();
5834                        SetSampleChecksum(pSample, pSample->crc);
5835                    }
5836                }
5837            }
5838    
5839            return bRequiresSave;
5840        }
5841    
5842      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
5843          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5844          // there must always be at least one group          // there must always be at least one group
# Line 3598  namespace { Line 5868  namespace {
5868          return NULL;          return NULL;
5869      }      }
5870    
5871        /**
5872         * Returns the group with the given group name.
5873         *
5874         * Note: group names don't have to be unique in the gig format! So there
5875         * can be multiple groups with the same name. This method will simply
5876         * return the first group found with the given name.
5877         *
5878         * @param name - name of the sought group
5879         * @returns sought group or NULL if there's no group with that name
5880         */
5881        Group* File::GetGroup(String name) {
5882            if (!pGroups) LoadGroups();
5883            GroupsIterator = pGroups->begin();
5884            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
5885                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
5886            return NULL;
5887        }
5888    
5889      Group* File::AddGroup() {      Group* File::AddGroup() {
5890          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5891          // there must always be at least one group          // there must always be at least one group
# Line 3678  namespace { Line 5966  namespace {
5966          }          }
5967      }      }
5968    
5969        /** @brief Get instrument script group (by index).
5970         *
5971         * Returns the real-time instrument script group with the given index.
5972         *
5973         * @param index - number of the sought group (0..n)
5974         * @returns sought script group or NULL if there's no such group
5975         */
5976        ScriptGroup* File::GetScriptGroup(uint index) {
5977            if (!pScriptGroups) LoadScriptGroups();
5978            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5979            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5980                if (i == index) return *it;
5981            return NULL;
5982        }
5983    
5984        /** @brief Get instrument script group (by name).
5985         *
5986         * Returns the first real-time instrument script group found with the given
5987         * group name. Note that group names may not necessarily be unique.
5988         *
5989         * @param name - name of the sought script group
5990         * @returns sought script group or NULL if there's no such group
5991         */
5992        ScriptGroup* File::GetScriptGroup(const String& name) {
5993            if (!pScriptGroups) LoadScriptGroups();
5994            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5995            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5996                if ((*it)->Name == name) return *it;
5997            return NULL;
5998        }
5999    
6000        /** @brief Add new instrument script group.
6001         *
6002         * Adds a new, empty real-time instrument script group to the file.
6003         *
6004         * You have to call Save() to make this persistent to the file.
6005         *
6006         * @return new empty script group
6007         */
6008        ScriptGroup* File::AddScriptGroup() {
6009            if (!pScriptGroups) LoadScriptGroups();
6010            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
6011            pScriptGroups->push_back(pScriptGroup);
6012            return pScriptGroup;
6013        }
6014    
6015        /** @brief Delete an instrument script group.
6016         *
6017         * This will delete the given real-time instrument script group and all its
6018         * instrument scripts it contains. References inside instruments that are
6019         * using the deleted scripts will be removed from the respective instruments
6020         * accordingly.
6021         *
6022         * You have to call Save() to make this persistent to the file.
6023         *
6024         * @param pScriptGroup - script group to delete
6025         * @throws gig::Exception if given script group could not be found
6026         */
6027        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
6028            if (!pScriptGroups) LoadScriptGroups();
6029            std::list<ScriptGroup*>::iterator iter =
6030                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
6031            if (iter == pScriptGroups->end())
6032                throw gig::Exception("Could not delete script group, could not find given script group");
6033            pScriptGroups->erase(iter);
6034            for (int i = 0; pScriptGroup->GetScript(i); ++i)
6035                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
6036            if (pScriptGroup->pList)
6037                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
6038            delete pScriptGroup;
6039        }
6040    
6041        void File::LoadScriptGroups() {
6042            if (pScriptGroups) return;
6043            pScriptGroups = new std::list<ScriptGroup*>;
6044            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
6045            if (lstLS) {
6046                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
6047                     lst = lstLS->GetNextSubList())
6048                {
6049                    if (lst->GetListType() == LIST_TYPE_RTIS) {
6050                        pScriptGroups->push_back(new ScriptGroup(this, lst));
6051                    }
6052                }
6053            }
6054        }
6055    
6056      /**      /**
6057       * Apply all the gig file's current instruments, samples, groups and settings       * Apply all the gig file's current instruments, samples, groups and settings
6058       * 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 3686  namespace { Line 6061  namespace {
6061       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
6062       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
6063       *       *
6064         * @param pProgress - callback function for progress notification
6065       * @throws Exception - on errors       * @throws Exception - on errors
6066       */       */
6067      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
6068          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6069    
6070          b64BitWavePoolOffsets = pVersion && pVersion->major == 3;          // update own gig format extension chunks
6071            // (not part of the GigaStudio 4 format)
6072            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6073            if (!lst3LS) {
6074                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6075            }
6076            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6077            // location of <3LS > is irrelevant, however it should be located
6078            // before  the actual wave data
6079            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6080            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6081    
6082            // This must be performed before writing the chunks for instruments,
6083            // because the instruments' script slots will write the file offsets
6084            // of the respective instrument script chunk as reference.
6085            if (pScriptGroups) {
6086                // Update instrument script (group) chunks.
6087                for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6088                     it != pScriptGroups->end(); ++it)
6089                {
6090                    (*it)->UpdateChunks(pProgress);
6091                }
6092            }
6093    
6094            // in case no libgig custom format data was added, then remove the
6095            // custom "3LS " chunk again
6096            if (!lst3LS->CountSubChunks()) {
6097                pRIFF->DeleteSubChunk(lst3LS);
6098                lst3LS = NULL;
6099            }
6100    
6101          // first update base class's chunks          // first update base class's chunks
6102          DLS::File::UpdateChunks();          DLS::File::UpdateChunks(pProgress);
6103    
6104          if (newFile) {          if (newFile) {
6105              // INFO was added by Resource::UpdateChunks - make sure it              // INFO was added by Resource::UpdateChunks - make sure it
# Line 3708  namespace { Line 6113  namespace {
6113    
6114          // update group's chunks          // update group's chunks
6115          if (pGroups) {          if (pGroups) {
6116              std::list<Group*>::iterator iter = pGroups->begin();              // make sure '3gri' and '3gnl' list chunks exist
6117              std::list<Group*>::iterator end  = pGroups->end();              // (before updating the Group chunks)
6118              for (; iter != end; ++iter) {              RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
6119                  (*iter)->UpdateChunks();              if (!_3gri) {
6120                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
6121                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
6122              }              }
6123                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
6124                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
6125    
6126              // v3: make sure the file has 128 3gnm chunks              // v3: make sure the file has 128 3gnm chunks
6127                // (before updating the Group chunks)
6128              if (pVersion && pVersion->major == 3) {              if (pVersion && pVersion->major == 3) {
                 RIFF::List* _3gnl = pRIFF->GetSubList(LIST_TYPE_3GRI)->GetSubList(LIST_TYPE_3GNL);  
6129                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
6130                  for (int i = 0 ; i < 128 ; i++) {                  for (int i = 0 ; i < 128 ; i++) {
6131                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
6132                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
6133                  }                  }
6134              }              }
6135    
6136                std::list<Group*>::iterator iter = pGroups->begin();
6137                std::list<Group*>::iterator end  = pGroups->end();
6138                for (; iter != end; ++iter) {
6139                    (*iter)->UpdateChunks(pProgress);
6140                }
6141          }          }
6142    
6143          // update einf chunk          // update einf chunk
# Line 3741  namespace { Line 6156  namespace {
6156          // Note that there are several fields with unknown use. These          // Note that there are several fields with unknown use. These
6157          // are set to zero.          // are set to zero.
6158    
6159          int sublen = pSamples->size() / 8 + 49;          int sublen = int(pSamples->size() / 8 + 49);
6160          int einfSize = (Instruments + 1) * sublen;          int einfSize = (Instruments + 1) * sublen;
6161    
6162          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
# Line 3814  namespace { Line 6229  namespace {
6229                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6230                  // next 8 bytes unknown                  // next 8 bytes unknown
6231                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6232                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());                  store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
6233                  // next 4 bytes unknown                  // next 4 bytes unknown
6234    
6235                  totnbregions += instrument->Regions;                  totnbregions += instrument->Regions;
# Line 3832  namespace { Line 6247  namespace {
6247              store32(&pData[24], totnbloops);              store32(&pData[24], totnbloops);
6248              // next 8 bytes unknown              // next 8 bytes unknown
6249              // next 4 bytes unknown, not always 0              // next 4 bytes unknown, not always 0
6250              store32(&pData[40], pSamples->size());              store32(&pData[40], (uint32_t) pSamples->size());
6251              // next 4 bytes unknown              // next 4 bytes unknown
6252          }          }
6253    
6254          // update 3crc chunk          // update 3crc chunk
6255    
6256          // The 3crc chunk contains CRC-32 checksums for the          // The 3crc chunk contains CRC-32 checksums for the
6257          // samples. The actual checksum values will be filled in          // samples. When saving a gig file to disk, we first update the 3CRC
6258          // later, by Sample::Write.          // chunk here (in RAM) with the old crc values which we read from the
6259            // 3CRC chunk when we opened the file (available with gig::Sample::crc
6260            // member variable). This step is required, because samples might have
6261            // been deleted by the user since the file was opened, which in turn
6262            // changes the order of the (i.e. old) checksums within the 3crc chunk.
6263            // If a sample was conciously modified by the user (that is if
6264            // Sample::Write() was called later on) then Sample::Write() will just
6265            // update the respective individual checksum(s) directly on disk and
6266            // leaves all other sample checksums untouched.
6267    
6268          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6269          if (_3crc) {          if (_3crc) {
6270              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
6271          } else if (newFile) {          } else /*if (newFile)*/ {
6272              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
             _3crc->LoadChunkData();  
   
6273              // 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
6274              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6275          }          }
6276            { // must be performed in RAM here ...
6277                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6278                if (pData) {
6279                    File::SampleList::iterator iter = pSamples->begin();
6280                    File::SampleList::iterator end  = pSamples->end();
6281                    for (int index = 0; iter != end; ++iter, ++index) {
6282                        gig::Sample* pSample = (gig::Sample*) *iter;
6283                        pData[index*2]   = 1; // always 1
6284                        pData[index*2+1] = pSample->crc;
6285                    }
6286                }
6287            }
6288        }
6289        
6290        void File::UpdateFileOffsets() {
6291            DLS::File::UpdateFileOffsets();
6292    
6293            for (Instrument* instrument = GetFirstInstrument(); instrument;
6294                 instrument = GetNextInstrument())
6295            {
6296                instrument->UpdateScriptFileOffsets();
6297            }
6298        }
6299    
6300        /**
6301         * Enable / disable automatic loading. By default this properyt is
6302         * enabled and all informations are loaded automatically. However
6303         * loading all Regions, DimensionRegions and especially samples might
6304         * take a long time for large .gig files, and sometimes one might only
6305         * be interested in retrieving very superficial informations like the
6306         * amount of instruments and their names. In this case one might disable
6307         * automatic loading to avoid very slow response times.
6308         *
6309         * @e CAUTION: by disabling this property many pointers (i.e. sample
6310         * references) and informations will have invalid or even undefined
6311         * data! This feature is currently only intended for retrieving very
6312         * superficial informations in a very fast way. Don't use it to retrieve
6313         * details like synthesis informations or even to modify .gig files!
6314         */
6315        void File::SetAutoLoad(bool b) {
6316            bAutoLoad = b;
6317        }
6318    
6319        /**
6320         * Returns whether automatic loading is enabled.
6321         * @see SetAutoLoad()
6322         */
6323        bool File::GetAutoLoad() {
6324            return bAutoLoad;
6325      }      }
6326    
6327    

Legend:
Removed from v.1416  
changed lines
  Added in v.3053

  ViewVC Help
Powered by ViewVC