/[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 1875 by schoenebeck, Thu Mar 26 13:32:59 2009 UTC revision 2912 by schoenebeck, Tue May 17 14:30:10 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-2009 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2016 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 28  Line 28 
28  #include <algorithm>  #include <algorithm>
29  #include <math.h>  #include <math.h>
30  #include <iostream>  #include <iostream>
31    #include <assert.h>
32    
33    /// libgig's current file format version (for extending the original Giga file
34    /// format with libgig's own custom data / custom features).
35    #define GIG_FILE_EXT_VERSION    2
36    
37  /// Initial size of the sample buffer which is used for decompression of  /// Initial size of the sample buffer which is used for decompression of
38  /// compressed sample wave streams - this value should always be bigger than  /// compressed sample wave streams - this value should always be bigger than
# Line 52  Line 57 
57    
58  namespace gig {  namespace gig {
59    
 // *************** progress_t ***************  
 // *  
   
     progress_t::progress_t() {  
         callback    = NULL;  
         custom      = NULL;  
         __range_min = 0.0f;  
         __range_max = 1.0f;  
     }  
   
     // private helper function to convert progress of a subprocess into the global progress  
     static void __notify_progress(progress_t* pProgress, float subprogress) {  
         if (pProgress && pProgress->callback) {  
             const float totalrange    = pProgress->__range_max - pProgress->__range_min;  
             const float totalprogress = pProgress->__range_min + subprogress * totalrange;  
             pProgress->factor         = totalprogress;  
             pProgress->callback(pProgress); // now actually notify about the progress  
         }  
     }  
   
     // private helper function to divide a progress into subprogresses  
     static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {  
         if (pParentProgress && pParentProgress->callback) {  
             const float totalrange    = pParentProgress->__range_max - pParentProgress->__range_min;  
             pSubProgress->callback    = pParentProgress->callback;  
             pSubProgress->custom      = pParentProgress->custom;  
             pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;  
             pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;  
         }  
     }  
   
   
60  // *************** Internal functions for sample decompression ***************  // *************** Internal functions for sample decompression ***************
61  // *  // *
62    
# Line 122  namespace { Line 95  namespace {
95      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
96                        int srcStep, int dstStep,                        int srcStep, int dstStep,
97                        const unsigned char* pSrc, int16_t* pDst,                        const unsigned char* pSrc, int16_t* pDst,
98                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
99                        unsigned long copysamples)                        file_offset_t copysamples)
100      {      {
101          switch (compressionmode) {          switch (compressionmode) {
102              case 0: // 16 bit uncompressed              case 0: // 16 bit uncompressed
# Line 159  namespace { Line 132  namespace {
132    
133      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
134                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,
135                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
136                        unsigned long copysamples, int truncatedBits)                        file_offset_t copysamples, int truncatedBits)
137      {      {
138          int y, dy, ddy, dddy;          int y, dy, ddy, dddy;
139    
# Line 366  namespace { Line 339  namespace {
339       * @param fileNo         - number of an extension file where this sample       * @param fileNo         - number of an extension file where this sample
340       *                         is located, 0 otherwise       *                         is located, 0 otherwise
341       */       */
342      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
343          static const DLS::Info::string_length_t fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
344              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
345              { 0, 0 }              { 0, 0 }
# Line 454  namespace { Line 427  namespace {
427      }      }
428    
429      /**      /**
430         * Make a (semi) deep copy of the Sample object given by @a orig (without
431         * the actual waveform data) and assign it to this object.
432         *
433         * Discussion: copying .gig samples is a bit tricky. It requires three
434         * steps:
435         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
436         *    its new sample waveform data size.
437         * 2. Saving the file (done by File::Save()) so that it gains correct size
438         *    and layout for writing the actual wave form data directly to disc
439         *    in next step.
440         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
441         *
442         * @param orig - original Sample object to be copied from
443         */
444        void Sample::CopyAssignMeta(const Sample* orig) {
445            // handle base classes
446            DLS::Sample::CopyAssignCore(orig);
447            
448            // handle actual own attributes of this class
449            Manufacturer = orig->Manufacturer;
450            Product = orig->Product;
451            SamplePeriod = orig->SamplePeriod;
452            MIDIUnityNote = orig->MIDIUnityNote;
453            FineTune = orig->FineTune;
454            SMPTEFormat = orig->SMPTEFormat;
455            SMPTEOffset = orig->SMPTEOffset;
456            Loops = orig->Loops;
457            LoopID = orig->LoopID;
458            LoopType = orig->LoopType;
459            LoopStart = orig->LoopStart;
460            LoopEnd = orig->LoopEnd;
461            LoopSize = orig->LoopSize;
462            LoopFraction = orig->LoopFraction;
463            LoopPlayCount = orig->LoopPlayCount;
464            
465            // schedule resizing this sample to the given sample's size
466            Resize(orig->GetSize());
467        }
468    
469        /**
470         * Should be called after CopyAssignMeta() and File::Save() sequence.
471         * Read more about it in the discussion of CopyAssignMeta(). This method
472         * copies the actual waveform data by disk streaming.
473         *
474         * @e CAUTION: this method is currently not thread safe! During this
475         * operation the sample must not be used for other purposes by other
476         * threads!
477         *
478         * @param orig - original Sample object to be copied from
479         */
480        void Sample::CopyAssignWave(const Sample* orig) {
481            const int iReadAtOnce = 32*1024;
482            char* buf = new char[iReadAtOnce * orig->FrameSize];
483            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
484            file_offset_t restorePos = pOrig->GetPos();
485            pOrig->SetPos(0);
486            SetPos(0);
487            for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
488                               n = pOrig->Read(buf, iReadAtOnce))
489            {
490                Write(buf, n);
491            }
492            pOrig->SetPos(restorePos);
493            delete [] buf;
494        }
495    
496        /**
497       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
498       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
499       *       *
500       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
501       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
502       *       *
503         * @param pProgress - callback function for progress notification
504       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
505       *                        was provided yet       *                        was provided yet
506       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
507       */       */
508      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
509          // first update base class's chunks          // first update base class's chunks
510          DLS::Sample::UpdateChunks();          DLS::Sample::UpdateChunks(pProgress);
511    
512          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
513          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 514  namespace { Line 555  namespace {
555          // update '3gix' chunk          // update '3gix' chunk
556          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
557          store16(&pData[0], iSampleGroup);          store16(&pData[0], iSampleGroup);
558    
559            // if the library user toggled the "Compressed" attribute from true to
560            // false, then the EWAV chunk associated with compressed samples needs
561            // to be deleted
562            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
563            if (ewav && !Compressed) {
564                pWaveList->DeleteSubChunk(ewav);
565            }
566      }      }
567    
568      /// 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).
569      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
570          //TODO: we have to add some more scans here (e.g. determine compression rate)          //TODO: we have to add some more scans here (e.g. determine compression rate)
571          this->SamplesTotal = 0;          this->SamplesTotal = 0;
572          std::list<unsigned long> frameOffsets;          std::list<file_offset_t> frameOffsets;
573    
574          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
575          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
# Line 536  namespace { Line 585  namespace {
585                  const int mode_l = pCkData->ReadUint8();                  const int mode_l = pCkData->ReadUint8();
586                  const int mode_r = pCkData->ReadUint8();                  const int mode_r = pCkData->ReadUint8();
587                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
588                  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];                  const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
589    
590                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
591                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 555  namespace { Line 604  namespace {
604    
605                  const int mode = pCkData->ReadUint8();                  const int mode = pCkData->ReadUint8();
606                  if (mode > 5) throw gig::Exception("Unknown compression mode");                  if (mode > 5) throw gig::Exception("Unknown compression mode");
607                  const unsigned long frameSize = bytesPerFrame[mode];                  const file_offset_t frameSize = bytesPerFrame[mode];
608    
609                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
610                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 571  namespace { Line 620  namespace {
620    
621          // Build the frames table (which is used for fast resolving of a frame's chunk offset)          // Build the frames table (which is used for fast resolving of a frame's chunk offset)
622          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
623          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new file_offset_t[frameOffsets.size()];
624          std::list<unsigned long>::iterator end  = frameOffsets.end();          std::list<file_offset_t>::iterator end  = frameOffsets.end();
625          std::list<unsigned long>::iterator iter = frameOffsets.begin();          std::list<file_offset_t>::iterator iter = frameOffsets.begin();
626          for (int i = 0; iter != end; i++, iter++) {          for (int i = 0; iter != end; i++, iter++) {
627              FrameTable[i] = *iter;              FrameTable[i] = *iter;
628          }          }
# Line 614  namespace { Line 663  namespace {
663       *                      the cached sample data in bytes       *                      the cached sample data in bytes
664       * @see                 ReleaseSampleData(), Read(), SetPos()       * @see                 ReleaseSampleData(), Read(), SetPos()
665       */       */
666      buffer_t Sample::LoadSampleData(unsigned long SampleCount) {      buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
667          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
668      }      }
669    
# Line 673  namespace { Line 722  namespace {
722       *                           size of the cached sample data in bytes       *                           size of the cached sample data in bytes
723       * @see                      ReleaseSampleData(), Read(), SetPos()       * @see                      ReleaseSampleData(), Read(), SetPos()
724       */       */
725      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
726          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
727          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
728          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
729          SetPos(0); // reset read position to begin of sample          SetPos(0); // reset read position to begin of sample
730          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
731          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
# Line 774  namespace { Line 823  namespace {
823       * @returns            the new sample position       * @returns            the new sample position
824       * @see                Read()       * @see                Read()
825       */       */
826      unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {      file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) {
827          if (Compressed) {          if (Compressed) {
828              switch (Whence) {              switch (Whence) {
829                  case RIFF::stream_curpos:                  case RIFF::stream_curpos:
# Line 792  namespace { Line 841  namespace {
841              }              }
842              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
843    
844              unsigned long frame = this->SamplePos / 2048; // to which frame to jump              file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
845              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame
846              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame
847              return this->SamplePos;              return this->SamplePos;
848          }          }
849          else { // not compressed          else { // not compressed
850              unsigned long orderedBytes = SampleCount * this->FrameSize;              file_offset_t orderedBytes = SampleCount * this->FrameSize;
851              unsigned long result = pCkData->SetPos(orderedBytes, Whence);              file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
852              return (result == orderedBytes) ? SampleCount              return (result == orderedBytes) ? SampleCount
853                                              : result / this->FrameSize;                                              : result / this->FrameSize;
854          }          }
# Line 808  namespace { Line 857  namespace {
857      /**      /**
858       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
859       */       */
860      unsigned long Sample::GetPos() {      file_offset_t Sample::GetPos() const {
861          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
862          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
863      }      }
# Line 847  namespace { Line 896  namespace {
896       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
897       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
898       */       */
899      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,      file_offset_t Sample::ReadAndLoop(void* pBuffer, file_offset_t SampleCount, playback_state_t* pPlaybackState,
900                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
901          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
902          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
903    
904          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
# Line 887  namespace { Line 936  namespace {
936                                  // reading, swap all sample frames so it reflects                                  // reading, swap all sample frames so it reflects
937                                  // backward playback                                  // backward playback
938    
939                                  unsigned long swapareastart       = totalreadsamples;                                  file_offset_t swapareastart       = totalreadsamples;
940                                  unsigned long loopoffset          = GetPos() - loop.LoopStart;                                  file_offset_t loopoffset          = GetPos() - loop.LoopStart;
941                                  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                  file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
942                                  unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                  file_offset_t reverseplaybackend  = GetPos() - samplestoreadinloop;
943    
944                                  SetPos(reverseplaybackend);                                  SetPos(reverseplaybackend);
945    
# Line 938  namespace { Line 987  namespace {
987                          // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
988                          // backward playback                          // backward playback
989    
990                          unsigned long swapareastart       = totalreadsamples;                          file_offset_t swapareastart       = totalreadsamples;
991                          unsigned long loopoffset          = GetPos() - loop.LoopStart;                          file_offset_t loopoffset          = GetPos() - loop.LoopStart;
992                          unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)                          file_offset_t samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
993                                                                                    : samplestoread;                                                                                    : samplestoread;
994                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);                          file_offset_t reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
995    
996                          SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
997    
# Line 1022  namespace { Line 1071  namespace {
1071       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1072       * @see                SetPos(), CreateDecompressionBuffer()       * @see                SetPos(), CreateDecompressionBuffer()
1073       */       */
1074      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {      file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount, buffer_t* pExternalDecompressionBuffer) {
1075          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1076          if (!Compressed) {          if (!Compressed) {
1077              if (BitDepth == 24) {              if (BitDepth == 24) {
# Line 1037  namespace { Line 1086  namespace {
1086          else {          else {
1087              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1088              //TODO: efficiency: maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1089              unsigned long assumedsize      = GuessSize(SampleCount),              file_offset_t assumedsize      = GuessSize(SampleCount),
1090                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1091                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1092                            copysamples, skipsamples,                            copysamples, skipsamples,
# Line 1060  namespace { Line 1109  namespace {
1109              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1110    
1111              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
1112                  unsigned long framesamples = SamplesPerFrame;                  file_offset_t framesamples = SamplesPerFrame;
1113                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;                  file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1114    
1115                  int mode_l = *pSrc++, mode_r = 0;                  int mode_l = *pSrc++, mode_r = 0;
1116    
# Line 1211  namespace { Line 1260  namespace {
1260       * @throws gig::Exception if sample is compressed       * @throws gig::Exception if sample is compressed
1261       * @see DLS::LoadSampleData()       * @see DLS::LoadSampleData()
1262       */       */
1263      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1264          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1265    
1266          // if this is the first write in this sample, reset the          // if this is the first write in this sample, reset the
# Line 1220  namespace { Line 1269  namespace {
1269              __resetCRC(crc);              __resetCRC(crc);
1270          }          }
1271          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1272          unsigned long res;          file_offset_t res;
1273          if (BitDepth == 24) {          if (BitDepth == 24) {
1274              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1275          } else { // 16 bit          } else { // 16 bit
# Line 1254  namespace { Line 1303  namespace {
1303       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1304       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1305       */       */
1306      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1307          buffer_t result;          buffer_t result;
1308          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1309                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1310          result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);          result.Size              = (file_offset_t) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1311          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1312          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1313          return result;          return result;
# Line 1433  namespace { Line 1482  namespace {
1482                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1483              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1484              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1485                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1486              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1487              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1488              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1581  namespace { Line 1630  namespace {
1630       */       */
1631      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1632          Instances++;          Instances++;
1633            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1634          *this = src; // default memberwise shallow copy of all parameters          *this = src; // default memberwise shallow copy of all parameters
1635          pParentList = _3ewl; // restore the chunk pointer          pParentList = _3ewl; // restore the chunk pointer
1636    
# Line 1596  namespace { Line 1646  namespace {
1646                  pSampleLoops[k] = src.pSampleLoops[k];                  pSampleLoops[k] = src.pSampleLoops[k];
1647          }          }
1648      }      }
1649        
1650        /**
1651         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1652         * and assign it to this object.
1653         *
1654         * Note that all sample pointers referenced by @a orig are simply copied as
1655         * memory address. Thus the respective samples are shared, not duplicated!
1656         *
1657         * @param orig - original DimensionRegion object to be copied from
1658         */
1659        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1660            CopyAssign(orig, NULL);
1661        }
1662    
1663        /**
1664         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1665         * and assign it to this object.
1666         *
1667         * @param orig - original DimensionRegion object to be copied from
1668         * @param mSamples - crosslink map between the foreign file's samples and
1669         *                   this file's samples
1670         */
1671        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1672            // delete all allocated data first
1673            if (VelocityTable) delete [] VelocityTable;
1674            if (pSampleLoops) delete [] pSampleLoops;
1675            
1676            // backup parent list pointer
1677            RIFF::List* p = pParentList;
1678            
1679            gig::Sample* pOriginalSample = pSample;
1680            gig::Region* pOriginalRegion = pRegion;
1681            
1682            //NOTE: copy code copied from assignment constructor above, see comment there as well
1683            
1684            *this = *orig; // default memberwise shallow copy of all parameters
1685            
1686            // restore members that shall not be altered
1687            pParentList = p; // restore the chunk pointer
1688            pRegion = pOriginalRegion;
1689            
1690            // only take the raw sample reference reference if the
1691            // two DimensionRegion objects are part of the same file
1692            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1693                pSample = pOriginalSample;
1694            }
1695            
1696            if (mSamples && mSamples->count(orig->pSample)) {
1697                pSample = mSamples->find(orig->pSample)->second;
1698            }
1699    
1700            // deep copy of owned structures
1701            if (orig->VelocityTable) {
1702                VelocityTable = new uint8_t[128];
1703                for (int k = 0 ; k < 128 ; k++)
1704                    VelocityTable[k] = orig->VelocityTable[k];
1705            }
1706            if (orig->pSampleLoops) {
1707                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1708                for (int k = 0 ; k < orig->SampleLoops ; k++)
1709                    pSampleLoops[k] = orig->pSampleLoops[k];
1710            }
1711        }
1712    
1713      /**      /**
1714       * Updates the respective member variable and updates @c SampleAttenuation       * Updates the respective member variable and updates @c SampleAttenuation
# Line 1612  namespace { Line 1725  namespace {
1725       *       *
1726       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
1727       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
1728         *
1729         * @param pProgress - callback function for progress notification
1730       */       */
1731      void DimensionRegion::UpdateChunks() {      void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1732          // first update base class's chunk          // first update base class's chunk
1733          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks(pProgress);
1734    
1735          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1736          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
# Line 1837  namespace { Line 1952  namespace {
1952          }          }
1953    
1954          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1955                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1956          store16(&pData[116], eg3depth);          store16(&pData[116], eg3depth);
1957    
1958          // next 2 bytes unknown          // next 2 bytes unknown
# Line 1885  namespace { Line 2000  namespace {
2000                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2001          pData[137] = vcfbreakpoint;          pData[137] = vcfbreakpoint;
2002    
2003          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2004                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2005          pData[138] = vcfvelocity;          pData[138] = vcfvelocity;
2006    
# Line 1950  namespace { Line 2065  namespace {
2065          return pRegion;          return pRegion;
2066      }      }
2067    
2068    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2069    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2070    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2071    //#pragma GCC diagnostic push
2072    //#pragma GCC diagnostic error "-Wswitch"
2073    
2074      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2075          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2076          switch (EncodedController) {          switch (EncodedController) {
# Line 2061  namespace { Line 2182  namespace {
2182                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2183                  break;                  break;
2184    
2185                // format extension (these controllers are so far only supported by
2186                // LinuxSampler & gigedit) they will *NOT* work with
2187                // Gigasampler/GigaStudio !
2188                case _lev_ctrl_CC3_EXT:
2189                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2190                    decodedcontroller.controller_number = 3;
2191                    break;
2192                case _lev_ctrl_CC6_EXT:
2193                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2194                    decodedcontroller.controller_number = 6;
2195                    break;
2196                case _lev_ctrl_CC7_EXT:
2197                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2198                    decodedcontroller.controller_number = 7;
2199                    break;
2200                case _lev_ctrl_CC8_EXT:
2201                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2202                    decodedcontroller.controller_number = 8;
2203                    break;
2204                case _lev_ctrl_CC9_EXT:
2205                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2206                    decodedcontroller.controller_number = 9;
2207                    break;
2208                case _lev_ctrl_CC10_EXT:
2209                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2210                    decodedcontroller.controller_number = 10;
2211                    break;
2212                case _lev_ctrl_CC11_EXT:
2213                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2214                    decodedcontroller.controller_number = 11;
2215                    break;
2216                case _lev_ctrl_CC14_EXT:
2217                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2218                    decodedcontroller.controller_number = 14;
2219                    break;
2220                case _lev_ctrl_CC15_EXT:
2221                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2222                    decodedcontroller.controller_number = 15;
2223                    break;
2224                case _lev_ctrl_CC20_EXT:
2225                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2226                    decodedcontroller.controller_number = 20;
2227                    break;
2228                case _lev_ctrl_CC21_EXT:
2229                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2230                    decodedcontroller.controller_number = 21;
2231                    break;
2232                case _lev_ctrl_CC22_EXT:
2233                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2234                    decodedcontroller.controller_number = 22;
2235                    break;
2236                case _lev_ctrl_CC23_EXT:
2237                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2238                    decodedcontroller.controller_number = 23;
2239                    break;
2240                case _lev_ctrl_CC24_EXT:
2241                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2242                    decodedcontroller.controller_number = 24;
2243                    break;
2244                case _lev_ctrl_CC25_EXT:
2245                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2246                    decodedcontroller.controller_number = 25;
2247                    break;
2248                case _lev_ctrl_CC26_EXT:
2249                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2250                    decodedcontroller.controller_number = 26;
2251                    break;
2252                case _lev_ctrl_CC27_EXT:
2253                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2254                    decodedcontroller.controller_number = 27;
2255                    break;
2256                case _lev_ctrl_CC28_EXT:
2257                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2258                    decodedcontroller.controller_number = 28;
2259                    break;
2260                case _lev_ctrl_CC29_EXT:
2261                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2262                    decodedcontroller.controller_number = 29;
2263                    break;
2264                case _lev_ctrl_CC30_EXT:
2265                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2266                    decodedcontroller.controller_number = 30;
2267                    break;
2268                case _lev_ctrl_CC31_EXT:
2269                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2270                    decodedcontroller.controller_number = 31;
2271                    break;
2272                case _lev_ctrl_CC68_EXT:
2273                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2274                    decodedcontroller.controller_number = 68;
2275                    break;
2276                case _lev_ctrl_CC69_EXT:
2277                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2278                    decodedcontroller.controller_number = 69;
2279                    break;
2280                case _lev_ctrl_CC70_EXT:
2281                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2282                    decodedcontroller.controller_number = 70;
2283                    break;
2284                case _lev_ctrl_CC71_EXT:
2285                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2286                    decodedcontroller.controller_number = 71;
2287                    break;
2288                case _lev_ctrl_CC72_EXT:
2289                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2290                    decodedcontroller.controller_number = 72;
2291                    break;
2292                case _lev_ctrl_CC73_EXT:
2293                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2294                    decodedcontroller.controller_number = 73;
2295                    break;
2296                case _lev_ctrl_CC74_EXT:
2297                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2298                    decodedcontroller.controller_number = 74;
2299                    break;
2300                case _lev_ctrl_CC75_EXT:
2301                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2302                    decodedcontroller.controller_number = 75;
2303                    break;
2304                case _lev_ctrl_CC76_EXT:
2305                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2306                    decodedcontroller.controller_number = 76;
2307                    break;
2308                case _lev_ctrl_CC77_EXT:
2309                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2310                    decodedcontroller.controller_number = 77;
2311                    break;
2312                case _lev_ctrl_CC78_EXT:
2313                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2314                    decodedcontroller.controller_number = 78;
2315                    break;
2316                case _lev_ctrl_CC79_EXT:
2317                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2318                    decodedcontroller.controller_number = 79;
2319                    break;
2320                case _lev_ctrl_CC84_EXT:
2321                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2322                    decodedcontroller.controller_number = 84;
2323                    break;
2324                case _lev_ctrl_CC85_EXT:
2325                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2326                    decodedcontroller.controller_number = 85;
2327                    break;
2328                case _lev_ctrl_CC86_EXT:
2329                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2330                    decodedcontroller.controller_number = 86;
2331                    break;
2332                case _lev_ctrl_CC87_EXT:
2333                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2334                    decodedcontroller.controller_number = 87;
2335                    break;
2336                case _lev_ctrl_CC89_EXT:
2337                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2338                    decodedcontroller.controller_number = 89;
2339                    break;
2340                case _lev_ctrl_CC90_EXT:
2341                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2342                    decodedcontroller.controller_number = 90;
2343                    break;
2344                case _lev_ctrl_CC96_EXT:
2345                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2346                    decodedcontroller.controller_number = 96;
2347                    break;
2348                case _lev_ctrl_CC97_EXT:
2349                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2350                    decodedcontroller.controller_number = 97;
2351                    break;
2352                case _lev_ctrl_CC102_EXT:
2353                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2354                    decodedcontroller.controller_number = 102;
2355                    break;
2356                case _lev_ctrl_CC103_EXT:
2357                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2358                    decodedcontroller.controller_number = 103;
2359                    break;
2360                case _lev_ctrl_CC104_EXT:
2361                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2362                    decodedcontroller.controller_number = 104;
2363                    break;
2364                case _lev_ctrl_CC105_EXT:
2365                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2366                    decodedcontroller.controller_number = 105;
2367                    break;
2368                case _lev_ctrl_CC106_EXT:
2369                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2370                    decodedcontroller.controller_number = 106;
2371                    break;
2372                case _lev_ctrl_CC107_EXT:
2373                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2374                    decodedcontroller.controller_number = 107;
2375                    break;
2376                case _lev_ctrl_CC108_EXT:
2377                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2378                    decodedcontroller.controller_number = 108;
2379                    break;
2380                case _lev_ctrl_CC109_EXT:
2381                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2382                    decodedcontroller.controller_number = 109;
2383                    break;
2384                case _lev_ctrl_CC110_EXT:
2385                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2386                    decodedcontroller.controller_number = 110;
2387                    break;
2388                case _lev_ctrl_CC111_EXT:
2389                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2390                    decodedcontroller.controller_number = 111;
2391                    break;
2392                case _lev_ctrl_CC112_EXT:
2393                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2394                    decodedcontroller.controller_number = 112;
2395                    break;
2396                case _lev_ctrl_CC113_EXT:
2397                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2398                    decodedcontroller.controller_number = 113;
2399                    break;
2400                case _lev_ctrl_CC114_EXT:
2401                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2402                    decodedcontroller.controller_number = 114;
2403                    break;
2404                case _lev_ctrl_CC115_EXT:
2405                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2406                    decodedcontroller.controller_number = 115;
2407                    break;
2408                case _lev_ctrl_CC116_EXT:
2409                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2410                    decodedcontroller.controller_number = 116;
2411                    break;
2412                case _lev_ctrl_CC117_EXT:
2413                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2414                    decodedcontroller.controller_number = 117;
2415                    break;
2416                case _lev_ctrl_CC118_EXT:
2417                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2418                    decodedcontroller.controller_number = 118;
2419                    break;
2420                case _lev_ctrl_CC119_EXT:
2421                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2422                    decodedcontroller.controller_number = 119;
2423                    break;
2424    
2425              // unknown controller type              // unknown controller type
2426              default:              default:
2427                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2428          }          }
2429          return decodedcontroller;          return decodedcontroller;
2430      }      }
2431        
2432    // see above (diagnostic push not supported prior GCC 4.6)
2433    //#pragma GCC diagnostic pop
2434    
2435      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2436          _lev_ctrl_t encodedcontroller;          _lev_ctrl_t encodedcontroller;
# Line 2154  namespace { Line 2518  namespace {
2518                      case 95:                      case 95:
2519                          encodedcontroller = _lev_ctrl_effect5depth;                          encodedcontroller = _lev_ctrl_effect5depth;
2520                          break;                          break;
2521    
2522                        // format extension (these controllers are so far only
2523                        // supported by LinuxSampler & gigedit) they will *NOT*
2524                        // work with Gigasampler/GigaStudio !
2525                        case 3:
2526                            encodedcontroller = _lev_ctrl_CC3_EXT;
2527                            break;
2528                        case 6:
2529                            encodedcontroller = _lev_ctrl_CC6_EXT;
2530                            break;
2531                        case 7:
2532                            encodedcontroller = _lev_ctrl_CC7_EXT;
2533                            break;
2534                        case 8:
2535                            encodedcontroller = _lev_ctrl_CC8_EXT;
2536                            break;
2537                        case 9:
2538                            encodedcontroller = _lev_ctrl_CC9_EXT;
2539                            break;
2540                        case 10:
2541                            encodedcontroller = _lev_ctrl_CC10_EXT;
2542                            break;
2543                        case 11:
2544                            encodedcontroller = _lev_ctrl_CC11_EXT;
2545                            break;
2546                        case 14:
2547                            encodedcontroller = _lev_ctrl_CC14_EXT;
2548                            break;
2549                        case 15:
2550                            encodedcontroller = _lev_ctrl_CC15_EXT;
2551                            break;
2552                        case 20:
2553                            encodedcontroller = _lev_ctrl_CC20_EXT;
2554                            break;
2555                        case 21:
2556                            encodedcontroller = _lev_ctrl_CC21_EXT;
2557                            break;
2558                        case 22:
2559                            encodedcontroller = _lev_ctrl_CC22_EXT;
2560                            break;
2561                        case 23:
2562                            encodedcontroller = _lev_ctrl_CC23_EXT;
2563                            break;
2564                        case 24:
2565                            encodedcontroller = _lev_ctrl_CC24_EXT;
2566                            break;
2567                        case 25:
2568                            encodedcontroller = _lev_ctrl_CC25_EXT;
2569                            break;
2570                        case 26:
2571                            encodedcontroller = _lev_ctrl_CC26_EXT;
2572                            break;
2573                        case 27:
2574                            encodedcontroller = _lev_ctrl_CC27_EXT;
2575                            break;
2576                        case 28:
2577                            encodedcontroller = _lev_ctrl_CC28_EXT;
2578                            break;
2579                        case 29:
2580                            encodedcontroller = _lev_ctrl_CC29_EXT;
2581                            break;
2582                        case 30:
2583                            encodedcontroller = _lev_ctrl_CC30_EXT;
2584                            break;
2585                        case 31:
2586                            encodedcontroller = _lev_ctrl_CC31_EXT;
2587                            break;
2588                        case 68:
2589                            encodedcontroller = _lev_ctrl_CC68_EXT;
2590                            break;
2591                        case 69:
2592                            encodedcontroller = _lev_ctrl_CC69_EXT;
2593                            break;
2594                        case 70:
2595                            encodedcontroller = _lev_ctrl_CC70_EXT;
2596                            break;
2597                        case 71:
2598                            encodedcontroller = _lev_ctrl_CC71_EXT;
2599                            break;
2600                        case 72:
2601                            encodedcontroller = _lev_ctrl_CC72_EXT;
2602                            break;
2603                        case 73:
2604                            encodedcontroller = _lev_ctrl_CC73_EXT;
2605                            break;
2606                        case 74:
2607                            encodedcontroller = _lev_ctrl_CC74_EXT;
2608                            break;
2609                        case 75:
2610                            encodedcontroller = _lev_ctrl_CC75_EXT;
2611                            break;
2612                        case 76:
2613                            encodedcontroller = _lev_ctrl_CC76_EXT;
2614                            break;
2615                        case 77:
2616                            encodedcontroller = _lev_ctrl_CC77_EXT;
2617                            break;
2618                        case 78:
2619                            encodedcontroller = _lev_ctrl_CC78_EXT;
2620                            break;
2621                        case 79:
2622                            encodedcontroller = _lev_ctrl_CC79_EXT;
2623                            break;
2624                        case 84:
2625                            encodedcontroller = _lev_ctrl_CC84_EXT;
2626                            break;
2627                        case 85:
2628                            encodedcontroller = _lev_ctrl_CC85_EXT;
2629                            break;
2630                        case 86:
2631                            encodedcontroller = _lev_ctrl_CC86_EXT;
2632                            break;
2633                        case 87:
2634                            encodedcontroller = _lev_ctrl_CC87_EXT;
2635                            break;
2636                        case 89:
2637                            encodedcontroller = _lev_ctrl_CC89_EXT;
2638                            break;
2639                        case 90:
2640                            encodedcontroller = _lev_ctrl_CC90_EXT;
2641                            break;
2642                        case 96:
2643                            encodedcontroller = _lev_ctrl_CC96_EXT;
2644                            break;
2645                        case 97:
2646                            encodedcontroller = _lev_ctrl_CC97_EXT;
2647                            break;
2648                        case 102:
2649                            encodedcontroller = _lev_ctrl_CC102_EXT;
2650                            break;
2651                        case 103:
2652                            encodedcontroller = _lev_ctrl_CC103_EXT;
2653                            break;
2654                        case 104:
2655                            encodedcontroller = _lev_ctrl_CC104_EXT;
2656                            break;
2657                        case 105:
2658                            encodedcontroller = _lev_ctrl_CC105_EXT;
2659                            break;
2660                        case 106:
2661                            encodedcontroller = _lev_ctrl_CC106_EXT;
2662                            break;
2663                        case 107:
2664                            encodedcontroller = _lev_ctrl_CC107_EXT;
2665                            break;
2666                        case 108:
2667                            encodedcontroller = _lev_ctrl_CC108_EXT;
2668                            break;
2669                        case 109:
2670                            encodedcontroller = _lev_ctrl_CC109_EXT;
2671                            break;
2672                        case 110:
2673                            encodedcontroller = _lev_ctrl_CC110_EXT;
2674                            break;
2675                        case 111:
2676                            encodedcontroller = _lev_ctrl_CC111_EXT;
2677                            break;
2678                        case 112:
2679                            encodedcontroller = _lev_ctrl_CC112_EXT;
2680                            break;
2681                        case 113:
2682                            encodedcontroller = _lev_ctrl_CC113_EXT;
2683                            break;
2684                        case 114:
2685                            encodedcontroller = _lev_ctrl_CC114_EXT;
2686                            break;
2687                        case 115:
2688                            encodedcontroller = _lev_ctrl_CC115_EXT;
2689                            break;
2690                        case 116:
2691                            encodedcontroller = _lev_ctrl_CC116_EXT;
2692                            break;
2693                        case 117:
2694                            encodedcontroller = _lev_ctrl_CC117_EXT;
2695                            break;
2696                        case 118:
2697                            encodedcontroller = _lev_ctrl_CC118_EXT;
2698                            break;
2699                        case 119:
2700                            encodedcontroller = _lev_ctrl_CC119_EXT;
2701                            break;
2702    
2703                      default:                      default:
2704                          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");
2705                  }                  }
# Line 2455  namespace { Line 3001  namespace {
3001       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
3002       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
3003       *       *
3004         * @param pProgress - callback function for progress notification
3005       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3006       */       */
3007      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
3008          // in the gig format we don't care about the Region's sample reference          // in the gig format we don't care about the Region's sample reference
3009          // but we still have to provide some existing one to not corrupt the          // but we still have to provide some existing one to not corrupt the
3010          // file, so to avoid the latter we simply always assign the sample of          // file, so to avoid the latter we simply always assign the sample of
# Line 2465  namespace { Line 3012  namespace {
3012          pSample = pDimensionRegions[0]->pSample;          pSample = pDimensionRegions[0]->pSample;
3013    
3014          // first update base class's chunks          // first update base class's chunks
3015          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks(pProgress);
3016    
3017          // update dimension region's chunks          // update dimension region's chunks
3018          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
3019              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks(pProgress);
3020          }          }
3021    
3022          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
# Line 2485  namespace { Line 3032  namespace {
3032              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3033    
3034              // move 3prg to last position              // move 3prg to last position
3035              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3036          }          }
3037    
3038          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
# Line 2631  namespace { Line 3178  namespace {
3178       *                        dimension bits limit is violated       *                        dimension bits limit is violated
3179       */       */
3180      void Region::AddDimension(dimension_def_t* pDimDef) {      void Region::AddDimension(dimension_def_t* pDimDef) {
3181            // some initial sanity checks of the given dimension definition
3182            if (pDimDef->zones < 2)
3183                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3184            if (pDimDef->bits < 1)
3185                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3186            if (pDimDef->dimension == dimension_samplechannel) {
3187                if (pDimDef->zones != 2)
3188                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3189                if (pDimDef->bits != 1)
3190                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3191            }
3192    
3193          // check if max. amount of dimensions reached          // check if max. amount of dimensions reached
3194          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3195          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
# Line 2806  namespace { Line 3365  namespace {
3365          if (pDimDef->dimension == dimension_layer) Layers = 1;          if (pDimDef->dimension == dimension_layer) Layers = 1;
3366      }      }
3367    
3368        /** @brief Delete one split zone of a dimension (decrement zone amount).
3369         *
3370         * Instead of deleting an entire dimensions, this method will only delete
3371         * one particular split zone given by @a zone of the Region's dimension
3372         * given by @a type. So this method will simply decrement the amount of
3373         * zones by one of the dimension in question. To be able to do that, the
3374         * respective dimension must exist on this Region and it must have at least
3375         * 3 zones. All DimensionRegion objects associated with the zone will be
3376         * deleted.
3377         *
3378         * @param type - identifies the dimension where a zone shall be deleted
3379         * @param zone - index of the dimension split zone that shall be deleted
3380         * @throws gig::Exception if requested zone could not be deleted
3381         */
3382        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3383            dimension_def_t* oldDef = GetDimensionDefinition(type);
3384            if (!oldDef)
3385                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3386            if (oldDef->zones <= 2)
3387                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3388            if (zone < 0 || zone >= oldDef->zones)
3389                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3390    
3391            const int newZoneSize = oldDef->zones - 1;
3392    
3393            // create a temporary Region which just acts as a temporary copy
3394            // container and will be deleted at the end of this function and will
3395            // also not be visible through the API during this process
3396            gig::Region* tempRgn = NULL;
3397            {
3398                // adding these temporary chunks is probably not even necessary
3399                Instrument* instr = static_cast<Instrument*>(GetParent());
3400                RIFF::List* pCkInstrument = instr->pCkInstrument;
3401                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3402                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3403                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3404                tempRgn = new Region(instr, rgn);
3405            }
3406    
3407            // copy this region's dimensions (with already the dimension split size
3408            // requested by the arguments of this method call) to the temporary
3409            // region, and don't use Region::CopyAssign() here for this task, since
3410            // it would also alter fast lookup helper variables here and there
3411            dimension_def_t newDef;
3412            for (int i = 0; i < Dimensions; ++i) {
3413                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3414                // is this the dimension requested by the method arguments? ...
3415                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3416                    def.zones = newZoneSize;
3417                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3418                    newDef = def;
3419                }
3420                tempRgn->AddDimension(&def);
3421            }
3422    
3423            // find the dimension index in the tempRegion which is the dimension
3424            // type passed to this method (paranoidly expecting different order)
3425            int tempReducedDimensionIndex = -1;
3426            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3427                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3428                    tempReducedDimensionIndex = d;
3429                    break;
3430                }
3431            }
3432    
3433            // copy dimension regions from this region to the temporary region
3434            for (int iDst = 0; iDst < 256; ++iDst) {
3435                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3436                if (!dstDimRgn) continue;
3437                std::map<dimension_t,int> dimCase;
3438                bool isValidZone = true;
3439                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3440                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3441                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3442                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3443                    baseBits += dstBits;
3444                    // there are also DimensionRegion objects of unused zones, skip them
3445                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3446                        isValidZone = false;
3447                        break;
3448                    }
3449                }
3450                if (!isValidZone) continue;
3451                // a bit paranoid: cope with the chance that the dimensions would
3452                // have different order in source and destination regions
3453                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3454                if (dimCase[type] >= zone) dimCase[type]++;
3455                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3456                dstDimRgn->CopyAssign(srcDimRgn);
3457                // if this is the upper most zone of the dimension passed to this
3458                // method, then correct (raise) its upper limit to 127
3459                if (newDef.split_type == split_type_normal && isLastZone)
3460                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3461            }
3462    
3463            // now tempRegion's dimensions and DimensionRegions basically reflect
3464            // what we wanted to get for this actual Region here, so we now just
3465            // delete and recreate the dimension in question with the new amount
3466            // zones and then copy back from tempRegion      
3467            DeleteDimension(oldDef);
3468            AddDimension(&newDef);
3469            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3470                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3471                if (!srcDimRgn) continue;
3472                std::map<dimension_t,int> dimCase;
3473                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3474                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3475                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3476                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3477                    baseBits += srcBits;
3478                }
3479                // a bit paranoid: cope with the chance that the dimensions would
3480                // have different order in source and destination regions
3481                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3482                if (!dstDimRgn) continue;
3483                dstDimRgn->CopyAssign(srcDimRgn);
3484            }
3485    
3486            // delete temporary region
3487            delete tempRgn;
3488    
3489            UpdateVelocityTable();
3490        }
3491    
3492        /** @brief Divide split zone of a dimension in two (increment zone amount).
3493         *
3494         * This will increment the amount of zones for the dimension (given by
3495         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3496         * in the middle of its zone range in two. So the two zones resulting from
3497         * the zone being splitted, will be an equivalent copy regarding all their
3498         * articulation informations and sample reference. The two zones will only
3499         * differ in their zone's upper limit
3500         * (DimensionRegion::DimensionUpperLimits).
3501         *
3502         * @param type - identifies the dimension where a zone shall be splitted
3503         * @param zone - index of the dimension split zone that shall be splitted
3504         * @throws gig::Exception if requested zone could not be splitted
3505         */
3506        void Region::SplitDimensionZone(dimension_t type, int zone) {
3507            dimension_def_t* oldDef = GetDimensionDefinition(type);
3508            if (!oldDef)
3509                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3510            if (zone < 0 || zone >= oldDef->zones)
3511                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3512    
3513            const int newZoneSize = oldDef->zones + 1;
3514    
3515            // create a temporary Region which just acts as a temporary copy
3516            // container and will be deleted at the end of this function and will
3517            // also not be visible through the API during this process
3518            gig::Region* tempRgn = NULL;
3519            {
3520                // adding these temporary chunks is probably not even necessary
3521                Instrument* instr = static_cast<Instrument*>(GetParent());
3522                RIFF::List* pCkInstrument = instr->pCkInstrument;
3523                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3524                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3525                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3526                tempRgn = new Region(instr, rgn);
3527            }
3528    
3529            // copy this region's dimensions (with already the dimension split size
3530            // requested by the arguments of this method call) to the temporary
3531            // region, and don't use Region::CopyAssign() here for this task, since
3532            // it would also alter fast lookup helper variables here and there
3533            dimension_def_t newDef;
3534            for (int i = 0; i < Dimensions; ++i) {
3535                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3536                // is this the dimension requested by the method arguments? ...
3537                if (def.dimension == type) { // ... if yes, increment zone amount by one
3538                    def.zones = newZoneSize;
3539                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3540                    newDef = def;
3541                }
3542                tempRgn->AddDimension(&def);
3543            }
3544    
3545            // find the dimension index in the tempRegion which is the dimension
3546            // type passed to this method (paranoidly expecting different order)
3547            int tempIncreasedDimensionIndex = -1;
3548            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3549                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3550                    tempIncreasedDimensionIndex = d;
3551                    break;
3552                }
3553            }
3554    
3555            // copy dimension regions from this region to the temporary region
3556            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3557                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3558                if (!srcDimRgn) continue;
3559                std::map<dimension_t,int> dimCase;
3560                bool isValidZone = true;
3561                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3562                    const int srcBits = pDimensionDefinitions[d].bits;
3563                    dimCase[pDimensionDefinitions[d].dimension] =
3564                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3565                    // there are also DimensionRegion objects for unused zones, skip them
3566                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3567                        isValidZone = false;
3568                        break;
3569                    }
3570                    baseBits += srcBits;
3571                }
3572                if (!isValidZone) continue;
3573                // a bit paranoid: cope with the chance that the dimensions would
3574                // have different order in source and destination regions            
3575                if (dimCase[type] > zone) dimCase[type]++;
3576                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3577                dstDimRgn->CopyAssign(srcDimRgn);
3578                // if this is the requested zone to be splitted, then also copy
3579                // the source DimensionRegion to the newly created target zone
3580                // and set the old zones upper limit lower
3581                if (dimCase[type] == zone) {
3582                    // lower old zones upper limit
3583                    if (newDef.split_type == split_type_normal) {
3584                        const int high =
3585                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3586                        int low = 0;
3587                        if (zone > 0) {
3588                            std::map<dimension_t,int> lowerCase = dimCase;
3589                            lowerCase[type]--;
3590                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3591                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3592                        }
3593                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3594                    }
3595                    // fill the newly created zone of the divided zone as well
3596                    dimCase[type]++;
3597                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3598                    dstDimRgn->CopyAssign(srcDimRgn);
3599                }
3600            }
3601    
3602            // now tempRegion's dimensions and DimensionRegions basically reflect
3603            // what we wanted to get for this actual Region here, so we now just
3604            // delete and recreate the dimension in question with the new amount
3605            // zones and then copy back from tempRegion      
3606            DeleteDimension(oldDef);
3607            AddDimension(&newDef);
3608            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3609                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3610                if (!srcDimRgn) continue;
3611                std::map<dimension_t,int> dimCase;
3612                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3613                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3614                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3615                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3616                    baseBits += srcBits;
3617                }
3618                // a bit paranoid: cope with the chance that the dimensions would
3619                // have different order in source and destination regions
3620                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3621                if (!dstDimRgn) continue;
3622                dstDimRgn->CopyAssign(srcDimRgn);
3623            }
3624    
3625            // delete temporary region
3626            delete tempRgn;
3627    
3628            UpdateVelocityTable();
3629        }
3630    
3631        /** @brief Change type of an existing dimension.
3632         *
3633         * Alters the dimension type of a dimension already existing on this
3634         * region. If there is currently no dimension on this Region with type
3635         * @a oldType, then this call with throw an Exception. Likewise there are
3636         * cases where the requested dimension type cannot be performed. For example
3637         * if the new dimension type shall be gig::dimension_samplechannel, and the
3638         * current dimension has more than 2 zones. In such cases an Exception is
3639         * thrown as well.
3640         *
3641         * @param oldType - identifies the existing dimension to be changed
3642         * @param newType - to which dimension type it should be changed to
3643         * @throws gig::Exception if requested change cannot be performed
3644         */
3645        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3646            if (oldType == newType) return;
3647            dimension_def_t* def = GetDimensionDefinition(oldType);
3648            if (!def)
3649                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3650            if (newType == dimension_samplechannel && def->zones != 2)
3651                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3652            if (GetDimensionDefinition(newType))
3653                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3654            def->dimension  = newType;
3655            def->split_type = __resolveSplitType(newType);
3656        }
3657    
3658        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3659            uint8_t bits[8] = {};
3660            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3661                 it != DimCase.end(); ++it)
3662            {
3663                for (int d = 0; d < Dimensions; ++d) {
3664                    if (pDimensionDefinitions[d].dimension == it->first) {
3665                        bits[d] = it->second;
3666                        goto nextDimCaseSlice;
3667                    }
3668                }
3669                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3670                nextDimCaseSlice:
3671                ; // noop
3672            }
3673            return GetDimensionRegionByBit(bits);
3674        }
3675    
3676        /**
3677         * Searches in the current Region for a dimension of the given dimension
3678         * type and returns the precise configuration of that dimension in this
3679         * Region.
3680         *
3681         * @param type - dimension type of the sought dimension
3682         * @returns dimension definition or NULL if there is no dimension with
3683         *          sought type in this Region.
3684         */
3685        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3686            for (int i = 0; i < Dimensions; ++i)
3687                if (pDimensionDefinitions[i].dimension == type)
3688                    return &pDimensionDefinitions[i];
3689            return NULL;
3690        }
3691    
3692      Region::~Region() {      Region::~Region() {
3693          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
3694              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
# Line 2863  namespace { Line 3746  namespace {
3746              }              }
3747              bitpos += pDimensionDefinitions[i].bits;              bitpos += pDimensionDefinitions[i].bits;
3748          }          }
3749          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3750            if (!dimreg) return NULL;
3751          if (veldim != -1) {          if (veldim != -1) {
3752              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3753              if (dimreg->VelocityTable) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3754                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3755              else // normal split type              else // normal split type
3756                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3757    
3758              dimregidx |= bits << velbitpos;              const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3759              dimreg = pDimensionRegions[dimregidx];              dimregidx |= (bits & limiter_mask) << velbitpos;
3760                dimreg = pDimensionRegions[dimregidx & 255];
3761          }          }
3762          return dimreg;          return dimreg;
3763      }      }
3764    
3765        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3766            uint8_t bits;
3767            int veldim = -1;
3768            int velbitpos;
3769            int bitpos = 0;
3770            int dimregidx = 0;
3771            for (uint i = 0; i < Dimensions; i++) {
3772                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3773                    // the velocity dimension must be handled after the other dimensions
3774                    veldim = i;
3775                    velbitpos = bitpos;
3776                } else {
3777                    switch (pDimensionDefinitions[i].split_type) {
3778                        case split_type_normal:
3779                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3780                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3781                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3782                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3783                                }
3784                            } else {
3785                                // gig2: evenly sized zones
3786                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3787                            }
3788                            break;
3789                        case split_type_bit: // the value is already the sought dimension bit number
3790                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3791                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3792                            break;
3793                    }
3794                    dimregidx |= bits << bitpos;
3795                }
3796                bitpos += pDimensionDefinitions[i].bits;
3797            }
3798            dimregidx &= 255;
3799            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3800            if (!dimreg) return -1;
3801            if (veldim != -1) {
3802                // (dimreg is now the dimension region for the lowest velocity)
3803                if (dimreg->VelocityTable) // custom defined zone ranges
3804                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3805                else // normal split type
3806                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3807    
3808                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3809                dimregidx |= (bits & limiter_mask) << velbitpos;
3810                dimregidx &= 255;
3811            }
3812            return dimregidx;
3813        }
3814    
3815      /**      /**
3816       * Returns the appropriate DimensionRegion for the given dimension bit       * Returns the appropriate DimensionRegion for the given dimension bit
3817       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
# Line 2915  namespace { Line 3850  namespace {
3850          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
3851          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3852          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
3853          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          if (file->HasMonolithicLargeFilePolicy()) {
3854          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];              uint64_t soughtoffset =
3855          Sample* sample = file->GetFirstSample(pProgress);                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
3856          while (sample) {                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
3857              if (sample->ulWavePoolOffset == soughtoffset &&              Sample* sample = file->GetFirstSample(pProgress);
3858                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);              while (sample) {
3859              sample = file->GetNextSample();                  if (sample->ullWavePoolOffset == soughtoffset)
3860                        return static_cast<gig::Sample*>(sample);
3861                    sample = file->GetNextSample();
3862                }
3863            } else {
3864                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3865                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3866                Sample* sample = file->GetFirstSample(pProgress);
3867                while (sample) {
3868                    if (sample->ullWavePoolOffset == soughtoffset &&
3869                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3870                    sample = file->GetNextSample();
3871                }
3872          }          }
3873          return NULL;          return NULL;
3874      }      }
3875        
3876        /**
3877         * Make a (semi) deep copy of the Region object given by @a orig
3878         * and assign it to this object.
3879         *
3880         * Note that all sample pointers referenced by @a orig are simply copied as
3881         * memory address. Thus the respective samples are shared, not duplicated!
3882         *
3883         * @param orig - original Region object to be copied from
3884         */
3885        void Region::CopyAssign(const Region* orig) {
3886            CopyAssign(orig, NULL);
3887        }
3888        
3889        /**
3890         * Make a (semi) deep copy of the Region object given by @a orig and
3891         * assign it to this object
3892         *
3893         * @param mSamples - crosslink map between the foreign file's samples and
3894         *                   this file's samples
3895         */
3896        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3897            // handle base classes
3898            DLS::Region::CopyAssign(orig);
3899            
3900            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3901                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3902            }
3903            
3904            // handle own member variables
3905            for (int i = Dimensions - 1; i >= 0; --i) {
3906                DeleteDimension(&pDimensionDefinitions[i]);
3907            }
3908            Layers = 0; // just to be sure
3909            for (int i = 0; i < orig->Dimensions; i++) {
3910                // we need to copy the dim definition here, to avoid the compiler
3911                // complaining about const-ness issue
3912                dimension_def_t def = orig->pDimensionDefinitions[i];
3913                AddDimension(&def);
3914            }
3915            for (int i = 0; i < 256; i++) {
3916                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3917                    pDimensionRegions[i]->CopyAssign(
3918                        orig->pDimensionRegions[i],
3919                        mSamples
3920                    );
3921                }
3922            }
3923            Layers = orig->Layers;
3924        }
3925    
3926    
3927  // *************** MidiRule ***************  // *************** MidiRule ***************
3928  // *  // *
3929    
3930  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {      MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3931      _3ewg->SetPos(36);          _3ewg->SetPos(36);
3932      Triggers = _3ewg->ReadUint8();          Triggers = _3ewg->ReadUint8();
3933      _3ewg->SetPos(40);          _3ewg->SetPos(40);
3934      ControllerNumber = _3ewg->ReadUint8();          ControllerNumber = _3ewg->ReadUint8();
3935      _3ewg->SetPos(46);          _3ewg->SetPos(46);
3936      for (int i = 0 ; i < Triggers ; i++) {          for (int i = 0 ; i < Triggers ; i++) {
3937          pTriggers[i].TriggerPoint = _3ewg->ReadUint8();              pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3938          pTriggers[i].Descending = _3ewg->ReadUint8();              pTriggers[i].Descending = _3ewg->ReadUint8();
3939          pTriggers[i].VelSensitivity = _3ewg->ReadUint8();              pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3940          pTriggers[i].Key = _3ewg->ReadUint8();              pTriggers[i].Key = _3ewg->ReadUint8();
3941          pTriggers[i].NoteOff = _3ewg->ReadUint8();              pTriggers[i].NoteOff = _3ewg->ReadUint8();
3942          pTriggers[i].Velocity = _3ewg->ReadUint8();              pTriggers[i].Velocity = _3ewg->ReadUint8();
3943          pTriggers[i].OverridePedal = _3ewg->ReadUint8();              pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3944          _3ewg->ReadUint8();              _3ewg->ReadUint8();
3945            }
3946        }
3947    
3948        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3949            ControllerNumber(0),
3950            Triggers(0) {
3951        }
3952    
3953        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3954            pData[32] = 4;
3955            pData[33] = 16;
3956            pData[36] = Triggers;
3957            pData[40] = ControllerNumber;
3958            for (int i = 0 ; i < Triggers ; i++) {
3959                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3960                pData[47 + i * 8] = pTriggers[i].Descending;
3961                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3962                pData[49 + i * 8] = pTriggers[i].Key;
3963                pData[50 + i * 8] = pTriggers[i].NoteOff;
3964                pData[51 + i * 8] = pTriggers[i].Velocity;
3965                pData[52 + i * 8] = pTriggers[i].OverridePedal;
3966            }
3967        }
3968    
3969        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3970            _3ewg->SetPos(36);
3971            LegatoSamples = _3ewg->ReadUint8(); // always 12
3972            _3ewg->SetPos(40);
3973            BypassUseController = _3ewg->ReadUint8();
3974            BypassKey = _3ewg->ReadUint8();
3975            BypassController = _3ewg->ReadUint8();
3976            ThresholdTime = _3ewg->ReadUint16();
3977            _3ewg->ReadInt16();
3978            ReleaseTime = _3ewg->ReadUint16();
3979            _3ewg->ReadInt16();
3980            KeyRange.low = _3ewg->ReadUint8();
3981            KeyRange.high = _3ewg->ReadUint8();
3982            _3ewg->SetPos(64);
3983            ReleaseTriggerKey = _3ewg->ReadUint8();
3984            AltSustain1Key = _3ewg->ReadUint8();
3985            AltSustain2Key = _3ewg->ReadUint8();
3986        }
3987    
3988        MidiRuleLegato::MidiRuleLegato() :
3989            LegatoSamples(12),
3990            BypassUseController(false),
3991            BypassKey(0),
3992            BypassController(1),
3993            ThresholdTime(20),
3994            ReleaseTime(20),
3995            ReleaseTriggerKey(0),
3996            AltSustain1Key(0),
3997            AltSustain2Key(0)
3998        {
3999            KeyRange.low = KeyRange.high = 0;
4000      }      }
 }  
4001    
4002        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
4003            pData[32] = 0;
4004            pData[33] = 16;
4005            pData[36] = LegatoSamples;
4006            pData[40] = BypassUseController;
4007            pData[41] = BypassKey;
4008            pData[42] = BypassController;
4009            store16(&pData[43], ThresholdTime);
4010            store16(&pData[47], ReleaseTime);
4011            pData[51] = KeyRange.low;
4012            pData[52] = KeyRange.high;
4013            pData[64] = ReleaseTriggerKey;
4014            pData[65] = AltSustain1Key;
4015            pData[66] = AltSustain2Key;
4016        }
4017    
4018        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4019            _3ewg->SetPos(36);
4020            Articulations = _3ewg->ReadUint8();
4021            int flags = _3ewg->ReadUint8();
4022            Polyphonic = flags & 8;
4023            Chained = flags & 4;
4024            Selector = (flags & 2) ? selector_controller :
4025                (flags & 1) ? selector_key_switch : selector_none;
4026            Patterns = _3ewg->ReadUint8();
4027            _3ewg->ReadUint8(); // chosen row
4028            _3ewg->ReadUint8(); // unknown
4029            _3ewg->ReadUint8(); // unknown
4030            _3ewg->ReadUint8(); // unknown
4031            KeySwitchRange.low = _3ewg->ReadUint8();
4032            KeySwitchRange.high = _3ewg->ReadUint8();
4033            Controller = _3ewg->ReadUint8();
4034            PlayRange.low = _3ewg->ReadUint8();
4035            PlayRange.high = _3ewg->ReadUint8();
4036    
4037            int n = std::min(int(Articulations), 32);
4038            for (int i = 0 ; i < n ; i++) {
4039                _3ewg->ReadString(pArticulations[i], 32);
4040            }
4041            _3ewg->SetPos(1072);
4042            n = std::min(int(Patterns), 32);
4043            for (int i = 0 ; i < n ; i++) {
4044                _3ewg->ReadString(pPatterns[i].Name, 16);
4045                pPatterns[i].Size = _3ewg->ReadUint8();
4046                _3ewg->Read(&pPatterns[i][0], 1, 32);
4047            }
4048        }
4049    
4050        MidiRuleAlternator::MidiRuleAlternator() :
4051            Articulations(0),
4052            Patterns(0),
4053            Selector(selector_none),
4054            Controller(0),
4055            Polyphonic(false),
4056            Chained(false)
4057        {
4058            PlayRange.low = PlayRange.high = 0;
4059            KeySwitchRange.low = KeySwitchRange.high = 0;
4060        }
4061    
4062        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4063            pData[32] = 3;
4064            pData[33] = 16;
4065            pData[36] = Articulations;
4066            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4067                (Selector == selector_controller ? 2 :
4068                 (Selector == selector_key_switch ? 1 : 0));
4069            pData[38] = Patterns;
4070    
4071            pData[43] = KeySwitchRange.low;
4072            pData[44] = KeySwitchRange.high;
4073            pData[45] = Controller;
4074            pData[46] = PlayRange.low;
4075            pData[47] = PlayRange.high;
4076    
4077            char* str = reinterpret_cast<char*>(pData);
4078            int pos = 48;
4079            int n = std::min(int(Articulations), 32);
4080            for (int i = 0 ; i < n ; i++, pos += 32) {
4081                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4082            }
4083    
4084            pos = 1072;
4085            n = std::min(int(Patterns), 32);
4086            for (int i = 0 ; i < n ; i++, pos += 49) {
4087                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4088                pData[pos + 16] = pPatterns[i].Size;
4089                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4090            }
4091        }
4092    
4093    // *************** Script ***************
4094    // *
4095    
4096        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4097            pGroup = group;
4098            pChunk = ckScri;
4099            if (ckScri) { // object is loaded from file ...
4100                // read header
4101                uint32_t headerSize = ckScri->ReadUint32();
4102                Compression = (Compression_t) ckScri->ReadUint32();
4103                Encoding    = (Encoding_t) ckScri->ReadUint32();
4104                Language    = (Language_t) ckScri->ReadUint32();
4105                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4106                crc         = ckScri->ReadUint32();
4107                uint32_t nameSize = ckScri->ReadUint32();
4108                Name.resize(nameSize, ' ');
4109                for (int i = 0; i < nameSize; ++i)
4110                    Name[i] = ckScri->ReadUint8();
4111                // to handle potential future extensions of the header
4112                ckScri->SetPos(sizeof(int32_t) + headerSize);
4113                // read actual script data
4114                uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();
4115                data.resize(scriptSize);
4116                for (int i = 0; i < scriptSize; ++i)
4117                    data[i] = ckScri->ReadUint8();
4118            } else { // this is a new script object, so just initialize it as such ...
4119                Compression = COMPRESSION_NONE;
4120                Encoding = ENCODING_ASCII;
4121                Language = LANGUAGE_NKSP;
4122                Bypass   = false;
4123                crc      = 0;
4124                Name     = "Unnamed Script";
4125            }
4126        }
4127    
4128        Script::~Script() {
4129        }
4130    
4131        /**
4132         * Returns the current script (i.e. as source code) in text format.
4133         */
4134        String Script::GetScriptAsText() {
4135            String s;
4136            s.resize(data.size(), ' ');
4137            memcpy(&s[0], &data[0], data.size());
4138            return s;
4139        }
4140    
4141        /**
4142         * Replaces the current script with the new script source code text given
4143         * by @a text.
4144         *
4145         * @param text - new script source code
4146         */
4147        void Script::SetScriptAsText(const String& text) {
4148            data.resize(text.size());
4149            memcpy(&data[0], &text[0], text.size());
4150        }
4151    
4152        /**
4153         * Apply this script to the respective RIFF chunks. You have to call
4154         * File::Save() to make changes persistent.
4155         *
4156         * Usually there is absolutely no need to call this method explicitly.
4157         * It will be called automatically when File::Save() was called.
4158         *
4159         * @param pProgress - callback function for progress notification
4160         */
4161        void Script::UpdateChunks(progress_t* pProgress) {
4162            // recalculate CRC32 check sum
4163            __resetCRC(crc);
4164            __calculateCRC(&data[0], data.size(), crc);
4165            __encodeCRC(crc);
4166            // make sure chunk exists and has the required size
4167            const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size();
4168            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4169            else pChunk->Resize(chunkSize);
4170            // fill the chunk data to be written to disk
4171            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4172            int pos = 0;
4173            store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size
4174            pos += sizeof(int32_t);
4175            store32(&pData[pos], Compression);
4176            pos += sizeof(int32_t);
4177            store32(&pData[pos], Encoding);
4178            pos += sizeof(int32_t);
4179            store32(&pData[pos], Language);
4180            pos += sizeof(int32_t);
4181            store32(&pData[pos], Bypass ? 1 : 0);
4182            pos += sizeof(int32_t);
4183            store32(&pData[pos], crc);
4184            pos += sizeof(int32_t);
4185            store32(&pData[pos], Name.size());
4186            pos += sizeof(int32_t);
4187            for (int i = 0; i < Name.size(); ++i, ++pos)
4188                pData[pos] = Name[i];
4189            for (int i = 0; i < data.size(); ++i, ++pos)
4190                pData[pos] = data[i];
4191        }
4192    
4193        /**
4194         * Move this script from its current ScriptGroup to another ScriptGroup
4195         * given by @a pGroup.
4196         *
4197         * @param pGroup - script's new group
4198         */
4199        void Script::SetGroup(ScriptGroup* pGroup) {
4200            if (this->pGroup == pGroup) return;
4201            if (pChunk)
4202                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4203            this->pGroup = pGroup;
4204        }
4205    
4206        /**
4207         * Returns the script group this script currently belongs to. Each script
4208         * is a member of exactly one ScriptGroup.
4209         *
4210         * @returns current script group
4211         */
4212        ScriptGroup* Script::GetGroup() const {
4213            return pGroup;
4214        }
4215    
4216        void Script::RemoveAllScriptReferences() {
4217            File* pFile = pGroup->pFile;
4218            for (int i = 0; pFile->GetInstrument(i); ++i) {
4219                Instrument* instr = pFile->GetInstrument(i);
4220                instr->RemoveScript(this);
4221            }
4222        }
4223    
4224    // *************** ScriptGroup ***************
4225    // *
4226    
4227        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4228            pFile = file;
4229            pList = lstRTIS;
4230            pScripts = NULL;
4231            if (lstRTIS) {
4232                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4233                ::LoadString(ckName, Name);
4234            } else {
4235                Name = "Default Group";
4236            }
4237        }
4238    
4239        ScriptGroup::~ScriptGroup() {
4240            if (pScripts) {
4241                std::list<Script*>::iterator iter = pScripts->begin();
4242                std::list<Script*>::iterator end  = pScripts->end();
4243                while (iter != end) {
4244                    delete *iter;
4245                    ++iter;
4246                }
4247                delete pScripts;
4248            }
4249        }
4250    
4251        /**
4252         * Apply this script group to the respective RIFF chunks. You have to call
4253         * File::Save() to make changes persistent.
4254         *
4255         * Usually there is absolutely no need to call this method explicitly.
4256         * It will be called automatically when File::Save() was called.
4257         *
4258         * @param pProgress - callback function for progress notification
4259         */
4260        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4261            if (pScripts) {
4262                if (!pList)
4263                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4264    
4265                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4266                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4267    
4268                for (std::list<Script*>::iterator it = pScripts->begin();
4269                     it != pScripts->end(); ++it)
4270                {
4271                    (*it)->UpdateChunks(pProgress);
4272                }
4273            }
4274        }
4275    
4276        /** @brief Get instrument script.
4277         *
4278         * Returns the real-time instrument script with the given index.
4279         *
4280         * @param index - number of the sought script (0..n)
4281         * @returns sought script or NULL if there's no such script
4282         */
4283        Script* ScriptGroup::GetScript(uint index) {
4284            if (!pScripts) LoadScripts();
4285            std::list<Script*>::iterator it = pScripts->begin();
4286            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4287                if (i == index) return *it;
4288            return NULL;
4289        }
4290    
4291        /** @brief Add new instrument script.
4292         *
4293         * Adds a new real-time instrument script to the file. The script is not
4294         * actually used / executed unless it is referenced by an instrument to be
4295         * used. This is similar to samples, which you can add to a file, without
4296         * an instrument necessarily actually using it.
4297         *
4298         * You have to call Save() to make this persistent to the file.
4299         *
4300         * @return new empty script object
4301         */
4302        Script* ScriptGroup::AddScript() {
4303            if (!pScripts) LoadScripts();
4304            Script* pScript = new Script(this, NULL);
4305            pScripts->push_back(pScript);
4306            return pScript;
4307        }
4308    
4309        /** @brief Delete an instrument script.
4310         *
4311         * This will delete the given real-time instrument script. References of
4312         * instruments that are using that script will be removed accordingly.
4313         *
4314         * You have to call Save() to make this persistent to the file.
4315         *
4316         * @param pScript - script to delete
4317         * @throws gig::Exception if given script could not be found
4318         */
4319        void ScriptGroup::DeleteScript(Script* pScript) {
4320            if (!pScripts) LoadScripts();
4321            std::list<Script*>::iterator iter =
4322                find(pScripts->begin(), pScripts->end(), pScript);
4323            if (iter == pScripts->end())
4324                throw gig::Exception("Could not delete script, could not find given script");
4325            pScripts->erase(iter);
4326            pScript->RemoveAllScriptReferences();
4327            if (pScript->pChunk)
4328                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4329            delete pScript;
4330        }
4331    
4332        void ScriptGroup::LoadScripts() {
4333            if (pScripts) return;
4334            pScripts = new std::list<Script*>;
4335            if (!pList) return;
4336    
4337            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4338                 ck = pList->GetNextSubChunk())
4339            {
4340                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4341                    pScripts->push_back(new Script(this, ck));
4342                }
4343            }
4344        }
4345    
4346  // *************** Instrument ***************  // *************** Instrument ***************
4347  // *  // *
# Line 2971  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4365  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4365          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
4366          pMidiRules = new MidiRule*[3];          pMidiRules = new MidiRule*[3];
4367          pMidiRules[0] = NULL;          pMidiRules[0] = NULL;
4368            pScriptRefs = NULL;
4369    
4370          // Loading          // Loading
4371          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2993  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4388  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4388                      uint8_t id1 = _3ewg->ReadUint8();                      uint8_t id1 = _3ewg->ReadUint8();
4389                      uint8_t id2 = _3ewg->ReadUint8();                      uint8_t id2 = _3ewg->ReadUint8();
4390    
4391                      if (id1 == 4 && id2 == 16) {                      if (id2 == 16) {
4392                          pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);                          if (id1 == 4) {
4393                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4394                            } else if (id1 == 0) {
4395                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4396                            } else if (id1 == 3) {
4397                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4398                            } else {
4399                                pMidiRules[i++] = new MidiRuleUnknown;
4400                            }
4401                        }
4402                        else if (id1 != 0 || id2 != 0) {
4403                            pMidiRules[i++] = new MidiRuleUnknown;
4404                      }                      }
4405                      //TODO: all the other types of rules                      //TODO: all the other types of rules
4406    
# Line 3020  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4426  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4426              }              }
4427          }          }
4428    
4429            // own gig format extensions
4430            RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4431            if (lst3LS) {
4432                RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4433                if (ckSCSL) {
4434                    int headerSize = ckSCSL->ReadUint32();
4435                    int slotCount  = ckSCSL->ReadUint32();
4436                    if (slotCount) {
4437                        int slotSize  = ckSCSL->ReadUint32();
4438                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4439                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4440                        for (int i = 0; i < slotCount; ++i) {
4441                            _ScriptPooolEntry e;
4442                            e.fileOffset = ckSCSL->ReadUint32();
4443                            e.bypass     = ckSCSL->ReadUint32() & 1;
4444                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4445                            scriptPoolFileOffsets.push_back(e);
4446                        }
4447                    }
4448                }
4449            }
4450    
4451          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4452      }      }
4453    
# Line 3036  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4464  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4464      }      }
4465    
4466      Instrument::~Instrument() {      Instrument::~Instrument() {
4467            for (int i = 0 ; pMidiRules[i] ; i++) {
4468                delete pMidiRules[i];
4469            }
4470          delete[] pMidiRules;          delete[] pMidiRules;
4471            if (pScriptRefs) delete pScriptRefs;
4472      }      }
4473    
4474      /**      /**
# Line 3046  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4478  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4478       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
4479       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
4480       *       *
4481         * @param pProgress - callback function for progress notification
4482       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
4483       */       */
4484      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
4485          // first update base classes' chunks          // first update base classes' chunks
4486          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks(pProgress);
4487    
4488          // update Regions' chunks          // update Regions' chunks
4489          {          {
4490              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
4491              RegionList::iterator end  = pRegions->end();              RegionList::iterator end  = pRegions->end();
4492              for (; iter != end; ++iter)              for (; iter != end; ++iter)
4493                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
4494          }          }
4495    
4496          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
# Line 3083  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4516  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4516                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
4517          pData[10] = dimkeystart;          pData[10] = dimkeystart;
4518          pData[11] = DimensionKeyRange.high;          pData[11] = DimensionKeyRange.high;
4519    
4520            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4521                pData[32] = 0;
4522                pData[33] = 0;
4523            } else {
4524                for (int i = 0 ; pMidiRules[i] ; i++) {
4525                    pMidiRules[i]->UpdateChunks(pData);
4526                }
4527            }
4528    
4529            // own gig format extensions
4530           if (ScriptSlotCount()) {
4531               // make sure we have converted the original loaded script file
4532               // offsets into valid Script object pointers
4533               LoadScripts();
4534    
4535               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4536               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4537               const int slotCount = pScriptRefs->size();
4538               const int headerSize = 3 * sizeof(uint32_t);
4539               const int slotSize  = 2 * sizeof(uint32_t);
4540               const int totalChunkSize = headerSize + slotCount * slotSize;
4541               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4542               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4543               else ckSCSL->Resize(totalChunkSize);
4544               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4545               int pos = 0;
4546               store32(&pData[pos], headerSize);
4547               pos += sizeof(uint32_t);
4548               store32(&pData[pos], slotCount);
4549               pos += sizeof(uint32_t);
4550               store32(&pData[pos], slotSize);
4551               pos += sizeof(uint32_t);
4552               for (int i = 0; i < slotCount; ++i) {
4553                   // arbitrary value, the actual file offset will be updated in
4554                   // UpdateScriptFileOffsets() after the file has been resized
4555                   int bogusFileOffset = 0;
4556                   store32(&pData[pos], bogusFileOffset);
4557                   pos += sizeof(uint32_t);
4558                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4559                   pos += sizeof(uint32_t);
4560               }
4561           } else {
4562               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4563               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4564               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4565           }
4566        }
4567    
4568        void Instrument::UpdateScriptFileOffsets() {
4569           // own gig format extensions
4570           if (pScriptRefs && pScriptRefs->size() > 0) {
4571               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4572               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4573               const int slotCount = pScriptRefs->size();
4574               const int headerSize = 3 * sizeof(uint32_t);
4575               ckSCSL->SetPos(headerSize);
4576               for (int i = 0; i < slotCount; ++i) {
4577                   uint32_t fileOffset =
4578                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4579                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4580                        CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize());
4581                   ckSCSL->WriteUint32(&fileOffset);
4582                   // jump over flags entry (containing the bypass flag)
4583                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4584               }
4585           }        
4586      }      }
4587    
4588      /**      /**
# Line 3152  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4652  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4652      }      }
4653    
4654      /**      /**
4655         * Move this instrument at the position before @arg dst.
4656         *
4657         * This method can be used to reorder the sequence of instruments in a
4658         * .gig file. This might be helpful especially on large .gig files which
4659         * contain a large number of instruments within the same .gig file. So
4660         * grouping such instruments to similar ones, can help to keep track of them
4661         * when working with such complex .gig files.
4662         *
4663         * When calling this method, this instrument will be removed from in its
4664         * current position in the instruments list and moved to the requested
4665         * target position provided by @param dst. You may also pass NULL as
4666         * argument to this method, in that case this intrument will be moved to the
4667         * very end of the .gig file's instrument list.
4668         *
4669         * You have to call Save() to make the order change persistent to the .gig
4670         * file.
4671         *
4672         * Currently this method is limited to moving the instrument within the same
4673         * .gig file. Trying to move it to another .gig file by calling this method
4674         * will throw an exception.
4675         *
4676         * @param dst - destination instrument at which this instrument will be
4677         *              moved to, or pass NULL for moving to end of list
4678         * @throw gig::Exception if this instrument and target instrument are not
4679         *                       part of the same file
4680         */
4681        void Instrument::MoveTo(Instrument* dst) {
4682            if (dst && GetParent() != dst->GetParent())
4683                throw Exception(
4684                    "gig::Instrument::MoveTo() can only be used for moving within "
4685                    "the same gig file."
4686                );
4687    
4688            File* pFile = (File*) GetParent();
4689    
4690            // move this instrument within the instrument list
4691            {
4692                File::InstrumentList& list = *pFile->pInstruments;
4693    
4694                File::InstrumentList::iterator itFrom =
4695                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4696    
4697                File::InstrumentList::iterator itTo =
4698                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4699    
4700                list.splice(itTo, list, itFrom);
4701            }
4702    
4703            // move the instrument's actual list RIFF chunk appropriately
4704            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4705            lstCkInstruments->MoveSubChunk(
4706                this->pCkInstrument,
4707                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4708            );
4709        }
4710    
4711        /**
4712       * Returns a MIDI rule of the instrument.       * Returns a MIDI rule of the instrument.
4713       *       *
4714       * The list of MIDI rules, at least in gig v3, always contains at       * The list of MIDI rules, at least in gig v3, always contains at
# Line 3165  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4722  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4722          return pMidiRules[i];          return pMidiRules[i];
4723      }      }
4724    
4725        /**
4726         * Adds the "controller trigger" MIDI rule to the instrument.
4727         *
4728         * @returns the new MIDI rule
4729         */
4730        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4731            delete pMidiRules[0];
4732            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4733            pMidiRules[0] = r;
4734            pMidiRules[1] = 0;
4735            return r;
4736        }
4737    
4738        /**
4739         * Adds the legato MIDI rule to the instrument.
4740         *
4741         * @returns the new MIDI rule
4742         */
4743        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4744            delete pMidiRules[0];
4745            MidiRuleLegato* r = new MidiRuleLegato;
4746            pMidiRules[0] = r;
4747            pMidiRules[1] = 0;
4748            return r;
4749        }
4750    
4751        /**
4752         * Adds the alternator MIDI rule to the instrument.
4753         *
4754         * @returns the new MIDI rule
4755         */
4756        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4757            delete pMidiRules[0];
4758            MidiRuleAlternator* r = new MidiRuleAlternator;
4759            pMidiRules[0] = r;
4760            pMidiRules[1] = 0;
4761            return r;
4762        }
4763    
4764        /**
4765         * Deletes a MIDI rule from the instrument.
4766         *
4767         * @param i - MIDI rule number
4768         */
4769        void Instrument::DeleteMidiRule(int i) {
4770            delete pMidiRules[i];
4771            pMidiRules[i] = 0;
4772        }
4773    
4774        void Instrument::LoadScripts() {
4775            if (pScriptRefs) return;
4776            pScriptRefs = new std::vector<_ScriptPooolRef>;
4777            if (scriptPoolFileOffsets.empty()) return;
4778            File* pFile = (File*) GetParent();
4779            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4780                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4781                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4782                    ScriptGroup* group = pFile->GetScriptGroup(i);
4783                    for (uint s = 0; group->GetScript(s); ++s) {
4784                        Script* script = group->GetScript(s);
4785                        if (script->pChunk) {
4786                            uint32_t offset = script->pChunk->GetFilePos() -
4787                                              script->pChunk->GetPos() -
4788                                              CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize());
4789                            if (offset == soughtOffset)
4790                            {
4791                                _ScriptPooolRef ref;
4792                                ref.script = script;
4793                                ref.bypass = scriptPoolFileOffsets[k].bypass;
4794                                pScriptRefs->push_back(ref);
4795                                break;
4796                            }
4797                        }
4798                    }
4799                }
4800            }
4801            // we don't need that anymore
4802            scriptPoolFileOffsets.clear();
4803        }
4804    
4805        /** @brief Get instrument script (gig format extension).
4806         *
4807         * Returns the real-time instrument script of instrument script slot
4808         * @a index.
4809         *
4810         * @note This is an own format extension which did not exist i.e. in the
4811         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4812         * gigedit.
4813         *
4814         * @param index - instrument script slot index
4815         * @returns script or NULL if index is out of bounds
4816         */
4817        Script* Instrument::GetScriptOfSlot(uint index) {
4818            LoadScripts();
4819            if (index >= pScriptRefs->size()) return NULL;
4820            return pScriptRefs->at(index).script;
4821        }
4822    
4823        /** @brief Add new instrument script slot (gig format extension).
4824         *
4825         * Add the given real-time instrument script reference to this instrument,
4826         * which shall be executed by the sampler for for this instrument. The
4827         * script will be added to the end of the script list of this instrument.
4828         * The positions of the scripts in the Instrument's Script list are
4829         * relevant, because they define in which order they shall be executed by
4830         * the sampler. For this reason it is also legal to add the same script
4831         * twice to an instrument, for example you might have a script called
4832         * "MyFilter" which performs an event filter task, and you might have
4833         * another script called "MyNoteTrigger" which triggers new notes, then you
4834         * might for example have the following list of scripts on the instrument:
4835         *
4836         * 1. Script "MyFilter"
4837         * 2. Script "MyNoteTrigger"
4838         * 3. Script "MyFilter"
4839         *
4840         * Which would make sense, because the 2nd script launched new events, which
4841         * you might need to filter as well.
4842         *
4843         * There are two ways to disable / "bypass" scripts. You can either disable
4844         * a script locally for the respective script slot on an instrument (i.e. by
4845         * passing @c false to the 2nd argument of this method, or by calling
4846         * SetScriptBypassed()). Or you can disable a script globally for all slots
4847         * and all instruments by setting Script::Bypass.
4848         *
4849         * @note This is an own format extension which did not exist i.e. in the
4850         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4851         * gigedit.
4852         *
4853         * @param pScript - script that shall be executed for this instrument
4854         * @param bypass  - if enabled, the sampler shall skip executing this
4855         *                  script (in the respective list position)
4856         * @see SetScriptBypassed()
4857         */
4858        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4859            LoadScripts();
4860            _ScriptPooolRef ref = { pScript, bypass };
4861            pScriptRefs->push_back(ref);
4862        }
4863    
4864        /** @brief Flip two script slots with each other (gig format extension).
4865         *
4866         * Swaps the position of the two given scripts in the Instrument's Script
4867         * list. The positions of the scripts in the Instrument's Script list are
4868         * relevant, because they define in which order they shall be executed by
4869         * the sampler.
4870         *
4871         * @note This is an own format extension which did not exist i.e. in the
4872         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4873         * gigedit.
4874         *
4875         * @param index1 - index of the first script slot to swap
4876         * @param index2 - index of the second script slot to swap
4877         */
4878        void Instrument::SwapScriptSlots(uint index1, uint index2) {
4879            LoadScripts();
4880            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4881                return;
4882            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4883            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4884            (*pScriptRefs)[index2] = tmp;
4885        }
4886    
4887        /** @brief Remove script slot.
4888         *
4889         * Removes the script slot with the given slot index.
4890         *
4891         * @param index - index of script slot to remove
4892         */
4893        void Instrument::RemoveScriptSlot(uint index) {
4894            LoadScripts();
4895            if (index >= pScriptRefs->size()) return;
4896            pScriptRefs->erase( pScriptRefs->begin() + index );
4897        }
4898    
4899        /** @brief Remove reference to given Script (gig format extension).
4900         *
4901         * This will remove all script slots on the instrument which are referencing
4902         * the given script.
4903         *
4904         * @note This is an own format extension which did not exist i.e. in the
4905         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4906         * gigedit.
4907         *
4908         * @param pScript - script reference to remove from this instrument
4909         * @see RemoveScriptSlot()
4910         */
4911        void Instrument::RemoveScript(Script* pScript) {
4912            LoadScripts();
4913            for (int i = pScriptRefs->size() - 1; i >= 0; --i) {
4914                if ((*pScriptRefs)[i].script == pScript) {
4915                    pScriptRefs->erase( pScriptRefs->begin() + i );
4916                }
4917            }
4918        }
4919    
4920        /** @brief Instrument's amount of script slots.
4921         *
4922         * This method returns the amount of script slots this instrument currently
4923         * uses.
4924         *
4925         * A script slot is a reference of a real-time instrument script to be
4926         * executed by the sampler. The scripts will be executed by the sampler in
4927         * sequence of the slots. One (same) script may be referenced multiple
4928         * times in different slots.
4929         *
4930         * @note This is an own format extension which did not exist i.e. in the
4931         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4932         * gigedit.
4933         */
4934        uint Instrument::ScriptSlotCount() const {
4935            return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
4936        }
4937    
4938        /** @brief Whether script execution shall be skipped.
4939         *
4940         * Defines locally for the Script reference slot in the Instrument's Script
4941         * list, whether the script shall be skipped by the sampler regarding
4942         * execution.
4943         *
4944         * It is also possible to ignore exeuction of the script globally, for all
4945         * slots and for all instruments by setting Script::Bypass.
4946         *
4947         * @note This is an own format extension which did not exist i.e. in the
4948         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4949         * gigedit.
4950         *
4951         * @param index - index of the script slot on this instrument
4952         * @see Script::Bypass
4953         */
4954        bool Instrument::IsScriptSlotBypassed(uint index) {
4955            if (index >= ScriptSlotCount()) return false;
4956            return pScriptRefs ? pScriptRefs->at(index).bypass
4957                               : scriptPoolFileOffsets.at(index).bypass;
4958            
4959        }
4960    
4961        /** @brief Defines whether execution shall be skipped.
4962         *
4963         * You can call this method to define locally whether or whether not the
4964         * given script slot shall be executed by the sampler.
4965         *
4966         * @note This is an own format extension which did not exist i.e. in the
4967         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4968         * gigedit.
4969         *
4970         * @param index - script slot index on this instrument
4971         * @param bBypass - if true, the script slot will be skipped by the sampler
4972         * @see Script::Bypass
4973         */
4974        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
4975            if (index >= ScriptSlotCount()) return;
4976            if (pScriptRefs)
4977                pScriptRefs->at(index).bypass = bBypass;
4978            else
4979                scriptPoolFileOffsets.at(index).bypass = bBypass;
4980        }
4981    
4982        /**
4983         * Make a (semi) deep copy of the Instrument object given by @a orig
4984         * and assign it to this object.
4985         *
4986         * Note that all sample pointers referenced by @a orig are simply copied as
4987         * memory address. Thus the respective samples are shared, not duplicated!
4988         *
4989         * @param orig - original Instrument object to be copied from
4990         */
4991        void Instrument::CopyAssign(const Instrument* orig) {
4992            CopyAssign(orig, NULL);
4993        }
4994            
4995        /**
4996         * Make a (semi) deep copy of the Instrument object given by @a orig
4997         * and assign it to this object.
4998         *
4999         * @param orig - original Instrument object to be copied from
5000         * @param mSamples - crosslink map between the foreign file's samples and
5001         *                   this file's samples
5002         */
5003        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
5004            // handle base class
5005            // (without copying DLS region stuff)
5006            DLS::Instrument::CopyAssignCore(orig);
5007            
5008            // handle own member variables
5009            Attenuation = orig->Attenuation;
5010            EffectSend = orig->EffectSend;
5011            FineTune = orig->FineTune;
5012            PitchbendRange = orig->PitchbendRange;
5013            PianoReleaseMode = orig->PianoReleaseMode;
5014            DimensionKeyRange = orig->DimensionKeyRange;
5015            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5016            pScriptRefs = orig->pScriptRefs;
5017            
5018            // free old midi rules
5019            for (int i = 0 ; pMidiRules[i] ; i++) {
5020                delete pMidiRules[i];
5021            }
5022            //TODO: MIDI rule copying
5023            pMidiRules[0] = NULL;
5024            
5025            // delete all old regions
5026            while (Regions) DeleteRegion(GetFirstRegion());
5027            // create new regions and copy them from original
5028            {
5029                RegionList::const_iterator it = orig->pRegions->begin();
5030                for (int i = 0; i < orig->Regions; ++i, ++it) {
5031                    Region* dstRgn = AddRegion();
5032                    //NOTE: Region does semi-deep copy !
5033                    dstRgn->CopyAssign(
5034                        static_cast<gig::Region*>(*it),
5035                        mSamples
5036                    );
5037                }
5038            }
5039    
5040            UpdateRegionKeyTable();
5041        }
5042    
5043    
5044  // *************** Group ***************  // *************** Group ***************
5045  // *  // *
# Line 3193  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5068  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5068       *       *
5069       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
5070       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
5071         *
5072         * @param pProgress - callback function for progress notification
5073       */       */
5074      void Group::UpdateChunks() {      void Group::UpdateChunks(progress_t* pProgress) {
5075          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
5076          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5077          if (!_3gri) {          if (!_3gri) {
# Line 3324  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5201  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5201          bAutoLoad = true;          bAutoLoad = true;
5202          *pVersion = VERSION_3;          *pVersion = VERSION_3;
5203          pGroups = NULL;          pGroups = NULL;
5204            pScriptGroups = NULL;
5205          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5206          pInfo->ArchivalLocation = String(256, ' ');          pInfo->ArchivalLocation = String(256, ' ');
5207    
# Line 3339  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5217  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5217      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5218          bAutoLoad = true;          bAutoLoad = true;
5219          pGroups = NULL;          pGroups = NULL;
5220            pScriptGroups = NULL;
5221          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5222      }      }
5223    
# Line 3352  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5231  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5231              }              }
5232              delete pGroups;              delete pGroups;
5233          }          }
5234            if (pScriptGroups) {
5235                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5236                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5237                while (iter != end) {
5238                    delete *iter;
5239                    ++iter;
5240                }
5241                delete pScriptGroups;
5242            }
5243      }      }
5244    
5245      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 3366  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5254  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5254          SamplesIterator++;          SamplesIterator++;
5255          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5256      }      }
5257        
5258        /**
5259         * Returns Sample object of @a index.
5260         *
5261         * @returns sample object or NULL if index is out of bounds
5262         */
5263        Sample* File::GetSample(uint index) {
5264            if (!pSamples) LoadSamples();
5265            if (!pSamples) return NULL;
5266            DLS::File::SampleList::iterator it = pSamples->begin();
5267            for (int i = 0; i < index; ++i) {
5268                ++it;
5269                if (it == pSamples->end()) return NULL;
5270            }
5271            if (it == pSamples->end()) return NULL;
5272            return static_cast<gig::Sample*>( *it );
5273        }
5274    
5275      /** @brief Add a new sample.      /** @brief Add a new sample.
5276       *       *
# Line 3444  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5349  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5349    
5350          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5351          int lastFileNo = 0;          int lastFileNo = 0;
5352          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!HasMonolithicLargeFilePolicy()) {
5353              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5354                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5355                }
5356          }          }
5357          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5358          int nameLen = name.length();          int nameLen = name.length();
# Line 3455  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5362  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5362          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5363              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5364              if (wvpl) {              if (wvpl) {
5365                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5366                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5367                  while (wave) {                  while (wave) {
5368                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 3463  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5370  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5370                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5371                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5372    
5373                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5374                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
5375    
5376                          iSampleIndex++;                          iSampleIndex++;
# Line 3563  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5470  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5470         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
5471         return pInstrument;         return pInstrument;
5472      }      }
5473        
5474        /** @brief Add a duplicate of an existing instrument.
5475         *
5476         * Duplicates the instrument definition given by @a orig and adds it
5477         * to this file. This allows in an instrument editor application to
5478         * easily create variations of an instrument, which will be stored in
5479         * the same .gig file, sharing i.e. the same samples.
5480         *
5481         * Note that all sample pointers referenced by @a orig are simply copied as
5482         * memory address. Thus the respective samples are shared, not duplicated!
5483         *
5484         * You have to call Save() to make this persistent to the file.
5485         *
5486         * @param orig - original instrument to be copied
5487         * @returns duplicated copy of the given instrument
5488         */
5489        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
5490            Instrument* instr = AddInstrument();
5491            instr->CopyAssign(orig);
5492            return instr;
5493        }
5494        
5495        /** @brief Add content of another existing file.
5496         *
5497         * Duplicates the samples, groups and instruments of the original file
5498         * given by @a pFile and adds them to @c this File. In case @c this File is
5499         * a new one that you haven't saved before, then you have to call
5500         * SetFileName() before calling AddContentOf(), because this method will
5501         * automatically save this file during operation, which is required for
5502         * writing the sample waveform data by disk streaming.
5503         *
5504         * @param pFile - original file whose's content shall be copied from
5505         */
5506        void File::AddContentOf(File* pFile) {
5507            static int iCallCount = -1;
5508            iCallCount++;
5509            std::map<Group*,Group*> mGroups;
5510            std::map<Sample*,Sample*> mSamples;
5511            
5512            // clone sample groups
5513            for (int i = 0; pFile->GetGroup(i); ++i) {
5514                Group* g = AddGroup();
5515                g->Name =
5516                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5517                mGroups[pFile->GetGroup(i)] = g;
5518            }
5519            
5520            // clone samples (not waveform data here yet)
5521            for (int i = 0; pFile->GetSample(i); ++i) {
5522                Sample* s = AddSample();
5523                s->CopyAssignMeta(pFile->GetSample(i));
5524                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5525                mSamples[pFile->GetSample(i)] = s;
5526            }
5527            
5528            //BUG: For some reason this method only works with this additional
5529            //     Save() call in between here.
5530            //
5531            // Important: The correct one of the 2 Save() methods has to be called
5532            // here, depending on whether the file is completely new or has been
5533            // saved to disk already, otherwise it will result in data corruption.
5534            if (pRIFF->IsNew())
5535                Save(GetFileName());
5536            else
5537                Save();
5538            
5539            // clone instruments
5540            // (passing the crosslink table here for the cloned samples)
5541            for (int i = 0; pFile->GetInstrument(i); ++i) {
5542                Instrument* instr = AddInstrument();
5543                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5544            }
5545            
5546            // Mandatory: file needs to be saved to disk at this point, so this
5547            // file has the correct size and data layout for writing the samples'
5548            // waveform data to disk.
5549            Save();
5550            
5551            // clone samples' waveform data
5552            // (using direct read & write disk streaming)
5553            for (int i = 0; pFile->GetSample(i); ++i) {
5554                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5555            }
5556        }
5557    
5558      /** @brief Delete an instrument.      /** @brief Delete an instrument.
5559       *       *
# Line 3665  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5656  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5656          return NULL;          return NULL;
5657      }      }
5658    
5659        /**
5660         * Returns the group with the given group name.
5661         *
5662         * Note: group names don't have to be unique in the gig format! So there
5663         * can be multiple groups with the same name. This method will simply
5664         * return the first group found with the given name.
5665         *
5666         * @param name - name of the sought group
5667         * @returns sought group or NULL if there's no group with that name
5668         */
5669        Group* File::GetGroup(String name) {
5670            if (!pGroups) LoadGroups();
5671            GroupsIterator = pGroups->begin();
5672            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
5673                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
5674            return NULL;
5675        }
5676    
5677      Group* File::AddGroup() {      Group* File::AddGroup() {
5678          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5679          // there must always be at least one group          // there must always be at least one group
# Line 3745  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5754  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5754          }          }
5755      }      }
5756    
5757        /** @brief Get instrument script group (by index).
5758         *
5759         * Returns the real-time instrument script group with the given index.
5760         *
5761         * @param index - number of the sought group (0..n)
5762         * @returns sought script group or NULL if there's no such group
5763         */
5764        ScriptGroup* File::GetScriptGroup(uint index) {
5765            if (!pScriptGroups) LoadScriptGroups();
5766            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5767            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5768                if (i == index) return *it;
5769            return NULL;
5770        }
5771    
5772        /** @brief Get instrument script group (by name).
5773         *
5774         * Returns the first real-time instrument script group found with the given
5775         * group name. Note that group names may not necessarily be unique.
5776         *
5777         * @param name - name of the sought script group
5778         * @returns sought script group or NULL if there's no such group
5779         */
5780        ScriptGroup* File::GetScriptGroup(const String& name) {
5781            if (!pScriptGroups) LoadScriptGroups();
5782            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5783            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5784                if ((*it)->Name == name) return *it;
5785            return NULL;
5786        }
5787    
5788        /** @brief Add new instrument script group.
5789         *
5790         * Adds a new, empty real-time instrument script group to the file.
5791         *
5792         * You have to call Save() to make this persistent to the file.
5793         *
5794         * @return new empty script group
5795         */
5796        ScriptGroup* File::AddScriptGroup() {
5797            if (!pScriptGroups) LoadScriptGroups();
5798            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
5799            pScriptGroups->push_back(pScriptGroup);
5800            return pScriptGroup;
5801        }
5802    
5803        /** @brief Delete an instrument script group.
5804         *
5805         * This will delete the given real-time instrument script group and all its
5806         * instrument scripts it contains. References inside instruments that are
5807         * using the deleted scripts will be removed from the respective instruments
5808         * accordingly.
5809         *
5810         * You have to call Save() to make this persistent to the file.
5811         *
5812         * @param pScriptGroup - script group to delete
5813         * @throws gig::Exception if given script group could not be found
5814         */
5815        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
5816            if (!pScriptGroups) LoadScriptGroups();
5817            std::list<ScriptGroup*>::iterator iter =
5818                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
5819            if (iter == pScriptGroups->end())
5820                throw gig::Exception("Could not delete script group, could not find given script group");
5821            pScriptGroups->erase(iter);
5822            for (int i = 0; pScriptGroup->GetScript(i); ++i)
5823                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
5824            if (pScriptGroup->pList)
5825                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
5826            delete pScriptGroup;
5827        }
5828    
5829        void File::LoadScriptGroups() {
5830            if (pScriptGroups) return;
5831            pScriptGroups = new std::list<ScriptGroup*>;
5832            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
5833            if (lstLS) {
5834                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
5835                     lst = lstLS->GetNextSubList())
5836                {
5837                    if (lst->GetListType() == LIST_TYPE_RTIS) {
5838                        pScriptGroups->push_back(new ScriptGroup(this, lst));
5839                    }
5840                }
5841            }
5842        }
5843    
5844        /** @brief Returns the version number of libgig's Giga file format extension.
5845         *
5846         * libgig added several new features which were not available with the
5847         * original GigaStudio software. For those purposes libgig's own custom RIFF
5848         * chunks were added to the Giga file format.
5849         *
5850         * This method returns the version number of the Giga file format extension
5851         * used in this Giga file. Currently there are 3 possible values that might
5852         * be returned by this method:
5853         *
5854         * - @c 0: This gig file is not using any libgig specific file format
5855         *         extension at all.
5856         * - @c 1: This gig file uses the RT instrument script format extension.
5857         * - @c 2: This gig file additionally provides support for monolithic
5858         *         large gig files (larger than 2 GB).
5859         *
5860         * @note This method is currently protected and shall not be used as public
5861         * API method, since its method signature might change in future.
5862         */
5863        uint File::GetFormatExtensionVersion() const {
5864            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
5865            if (!lst3LS) return 0; // is not using custom Giga format extensions at all
5866            RIFF::Chunk* ckFFmt = lst3LS->GetSubChunk(CHUNK_ID_FFMT);
5867            if (!ckFFmt) return 1; // uses custom Giga format extension(s) but had no format version saved
5868            uint8_t* pData = (uint8_t*) ckFFmt->LoadChunkData();
5869            return load32(pData);
5870        }
5871    
5872        /** @brief Returns true in case this file is stored as one, single monolithic gig file.
5873         *
5874         * To avoid issues with operating systems which did not support large files
5875         * (larger than 2 GB) the original Giga file format avoided to ever save gig
5876         * files larger than 2 GB, instead such large Giga files were splitted into
5877         * several files, each one not being larger than 2 GB. It used a predefined
5878         * file name scheme for them like this:
5879         * @code
5880         * foo.gig
5881         * foo.gx01
5882         * foo.gx02
5883         * foo.gx03
5884         * ...
5885         * @endcode
5886         * So when like in this example foo.gig was loaded, all other files
5887         * (foo.gx01, ...) were automatically loaded as well to make up the overall
5888         * large gig file (provided they were located at the same directory). Such
5889         * additional .gxYY files were called "extension files".
5890         *
5891         * Since nowadays all modern systems support large files, libgig always
5892         * saves large gig files as one single monolithic gig file instead, that
5893         * is libgig won't split such a large gig file into separate files like the
5894         * original GigaStudio software did. It uses a custom Giga file format
5895         * extension for this feature.
5896         *
5897         * For still being able though to load old splitted gig files and the new
5898         * large monolithic ones, this method is used to determine which loading
5899         * policy must be used for this gig file.
5900         *
5901         * @note This method is currently protected and shall not be used as public
5902         * API method, since its method signature might change in future and since
5903         * this method should not be directly relevant for applications based on
5904         * libgig.
5905         */
5906        bool File::HasMonolithicLargeFilePolicy() const {
5907            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
5908            if (!lst3LS) return false;
5909            RIFF::Chunk* ckFFmt = lst3LS->GetSubChunk(CHUNK_ID_FFMT);
5910            if (!ckFFmt) return false;
5911            uint8_t* pData = (uint8_t*) ckFFmt->LoadChunkData();
5912            uint32_t formatBitField = load32(&pData[4]);
5913            return formatBitField & 1;
5914        }
5915    
5916      /**      /**
5917       * Apply all the gig file's current instruments, samples, groups and settings       * Apply all the gig file's current instruments, samples, groups and settings
5918       * 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 3753  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5921  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5921       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
5922       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
5923       *       *
5924         * @param pProgress - callback function for progress notification
5925       * @throws Exception - on errors       * @throws Exception - on errors
5926       */       */
5927      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
5928          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
5929    
5930          b64BitWavePoolOffsets = pVersion && pVersion->major == 3;          b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
5931    
5932            // update own gig format extension chunks
5933            // (not part of the GigaStudio 4 format)
5934            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
5935            if (!lst3LS) {
5936                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
5937            }
5938            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
5939            // location of <3LS > is irrelevant, however it MUST BE located BEFORE
5940            // the actual wave data, otherwise the <3LS > chunk becomes
5941            // inaccessible on gig files larger than 4GB !
5942            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
5943            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
5944    
5945            // Update <FFmt> chunk with informations about our file format
5946            // extensions. Currently this <FFmt> chunk has the following
5947            // layout:
5948            //
5949            // <uint32> -> (libgig's) File Format Extension version
5950            // <uint32> -> Format bit field:
5951            //             bit 0: If flag is not set use separate .gx01
5952            //                    extension files if file is larger than 2 GB
5953            //                    like with the original Giga format, if flag
5954            //                    is set use 64 bit sample references and keep
5955            //                    everything as one single monolithic gig file.
5956            RIFF::Chunk* ckFFmt = lst3LS->GetSubChunk(CHUNK_ID_FFMT);
5957            if (!ckFFmt) {
5958                const int iChunkSize = 2 * sizeof(uint32_t);
5959                ckFFmt = lst3LS->AddSubChunk(CHUNK_ID_FFMT, iChunkSize);
5960            }
5961            {
5962                uint8_t* pData = (uint8_t*) ckFFmt->LoadChunkData();
5963                store32(&pData[0], GIG_FILE_EXT_VERSION);
5964                // for now we always save gig files larger than 2 GB as one
5965                // single monolithic file (saving those with extension files is
5966                // currently not supported and probably also not desired anymore
5967                // nowadays).
5968                uint32_t formatBitfield = 1;
5969                store32(&pData[4], formatBitfield);
5970            }
5971            // This must be performed before writing the chunks for instruments,
5972            // because the instruments' script slots will write the file offsets
5973            // of the respective instrument script chunk as reference.
5974            if (pScriptGroups) {
5975                // Update instrument script (group) chunks.
5976                for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5977                     it != pScriptGroups->end(); ++it)
5978                {
5979                    (*it)->UpdateChunks(pProgress);
5980                }
5981            }
5982    
5983          // first update base class's chunks          // first update base class's chunks
5984          DLS::File::UpdateChunks();          DLS::File::UpdateChunks(pProgress);
5985    
5986          if (newFile) {          if (newFile) {
5987              // INFO was added by Resource::UpdateChunks - make sure it              // INFO was added by Resource::UpdateChunks - make sure it
# Line 3775  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5995  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5995    
5996          // update group's chunks          // update group's chunks
5997          if (pGroups) {          if (pGroups) {
5998              std::list<Group*>::iterator iter = pGroups->begin();              // make sure '3gri' and '3gnl' list chunks exist
5999              std::list<Group*>::iterator end  = pGroups->end();              // (before updating the Group chunks)
6000              for (; iter != end; ++iter) {              RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
6001                  (*iter)->UpdateChunks();              if (!_3gri) {
6002                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
6003                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
6004              }              }
6005                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
6006                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
6007    
6008              // v3: make sure the file has 128 3gnm chunks              // v3: make sure the file has 128 3gnm chunks
6009                // (before updating the Group chunks)
6010              if (pVersion && pVersion->major == 3) {              if (pVersion && pVersion->major == 3) {
                 RIFF::List* _3gnl = pRIFF->GetSubList(LIST_TYPE_3GRI)->GetSubList(LIST_TYPE_3GNL);  
6011                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
6012                  for (int i = 0 ; i < 128 ; i++) {                  for (int i = 0 ; i < 128 ; i++) {
6013                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
6014                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
6015                  }                  }
6016              }              }
6017    
6018                std::list<Group*>::iterator iter = pGroups->begin();
6019                std::list<Group*>::iterator end  = pGroups->end();
6020                for (; iter != end; ++iter) {
6021                    (*iter)->UpdateChunks(pProgress);
6022                }
6023          }          }
6024    
6025          // update einf chunk          // update einf chunk
# Line 3920  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6150  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6150              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6151          }          }
6152      }      }
6153        
6154        void File::UpdateFileOffsets() {
6155            DLS::File::UpdateFileOffsets();
6156    
6157            for (Instrument* instrument = GetFirstInstrument(); instrument;
6158                 instrument = GetNextInstrument())
6159            {
6160                instrument->UpdateScriptFileOffsets();
6161            }
6162        }
6163    
6164      /**      /**
6165       * Enable / disable automatic loading. By default this properyt is       * Enable / disable automatic loading. By default this properyt is

Legend:
Removed from v.1875  
changed lines
  Added in v.2912

  ViewVC Help
Powered by ViewVC