/[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 3140 by schoenebeck, Wed May 3 16:19:53 2017 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file access library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2009 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2017 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 24  Line 24 
24  #include "gig.h"  #include "gig.h"
25    
26  #include "helper.h"  #include "helper.h"
27    #include "Serialization.h"
28    
29  #include <algorithm>  #include <algorithm>
30  #include <math.h>  #include <math.h>
31  #include <iostream>  #include <iostream>
32    #include <assert.h>
33    
34    /// libgig's current file format version (for extending the original Giga file
35    /// format with libgig's own custom data / custom features).
36    #define GIG_FILE_EXT_VERSION    2
37    
38  /// Initial size of the sample buffer which is used for decompression of  /// Initial size of the sample buffer which is used for decompression of
39  /// compressed sample wave streams - this value should always be bigger than  /// compressed sample wave streams - this value should always be bigger than
# Line 50  Line 56 
56  #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)  #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)
57  #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)  #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)
58    
59  namespace gig {  #define SRLZ(member) \
60        archive->serializeMember(*this, member, #member);
 // *************** 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;  
         }  
     }  
61    
62    namespace gig {
63    
64  // *************** Internal functions for sample decompression ***************  // *************** Internal functions for sample decompression ***************
65  // *  // *
# Line 122  namespace { Line 99  namespace {
99      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
100                        int srcStep, int dstStep,                        int srcStep, int dstStep,
101                        const unsigned char* pSrc, int16_t* pDst,                        const unsigned char* pSrc, int16_t* pDst,
102                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
103                        unsigned long copysamples)                        file_offset_t copysamples)
104      {      {
105          switch (compressionmode) {          switch (compressionmode) {
106              case 0: // 16 bit uncompressed              case 0: // 16 bit uncompressed
# Line 159  namespace { Line 136  namespace {
136    
137      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
138                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,
139                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
140                        unsigned long copysamples, int truncatedBits)                        file_offset_t copysamples, int truncatedBits)
141      {      {
142          int y, dy, ddy, dddy;          int y, dy, ddy, dddy;
143    
# Line 296  namespace { Line 273  namespace {
273       * steps.       * steps.
274       *       *
275       * Once the whole data was processed by __calculateCRC(), one should       * Once the whole data was processed by __calculateCRC(), one should
276       * call __encodeCRC() to get the final CRC result.       * call __finalizeCRC() to get the final CRC result.
277       *       *
278       * @param buf     - pointer to data the CRC shall be calculated of       * @param buf     - pointer to data the CRC shall be calculated of
279       * @param bufSize - size of the data to be processed       * @param bufSize - size of the data to be processed
280       * @param crc     - variable the CRC sum shall be stored to       * @param crc     - variable the CRC sum shall be stored to
281       */       */
282      static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {      static void __calculateCRC(unsigned char* buf, size_t bufSize, uint32_t& crc) {
283          for (int i = 0 ; i < bufSize ; i++) {          for (size_t i = 0 ; i < bufSize ; i++) {
284              crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);              crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
285          }          }
286      }      }
# Line 313  namespace { Line 290  namespace {
290       *       *
291       * @param crc - variable previously passed to __calculateCRC()       * @param crc - variable previously passed to __calculateCRC()
292       */       */
293      inline static uint32_t __encodeCRC(const uint32_t& crc) {      inline static void __finalizeCRC(uint32_t& crc) {
294          return crc ^ 0xffffffff;          crc ^= 0xffffffff;
295      }      }
296    
297    
# Line 342  namespace { Line 319  namespace {
319    
320    
321    
322    // *************** leverage_ctrl_t ***************
323    // *
324    
325        void leverage_ctrl_t::serialize(Serialization::Archive* archive) {
326            SRLZ(type);
327            SRLZ(controller_number);
328        }
329    
330    
331    
332    // *************** crossfade_t ***************
333    // *
334    
335        void crossfade_t::serialize(Serialization::Archive* archive) {
336            SRLZ(in_start);
337            SRLZ(in_end);
338            SRLZ(out_start);
339            SRLZ(out_end);
340        }
341    
342    
343    
344  // *************** Sample ***************  // *************** Sample ***************
345  // *  // *
346    
347      unsigned int Sample::Instances = 0;      size_t       Sample::Instances = 0;
348      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
349    
350      /** @brief Constructor.      /** @brief Constructor.
# Line 365  namespace { Line 364  namespace {
364       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
365       * @param fileNo         - number of an extension file where this sample       * @param fileNo         - number of an extension file where this sample
366       *                         is located, 0 otherwise       *                         is located, 0 otherwise
367         * @param index          - wave pool index of sample (may be -1 on new sample)
368       */       */
369      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset, unsigned long fileNo, int index)
370            : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset)
371        {
372          static const DLS::Info::string_length_t fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
373              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
374              { 0, 0 }              { 0, 0 }
# Line 376  namespace { Line 378  namespace {
378          FileNo = fileNo;          FileNo = fileNo;
379    
380          __resetCRC(crc);          __resetCRC(crc);
381            // if this is not a new sample, try to get the sample's already existing
382            // CRC32 checksum from disk, this checksum will reflect the sample's CRC32
383            // checksum of the time when the sample was consciously modified by the
384            // user for the last time (by calling Sample::Write() that is).
385            if (index >= 0) { // not a new file ...
386                try {
387                    uint32_t crc = pFile->GetSampleChecksumByIndex(index);
388                    this->crc = crc;
389                } catch (...) {}
390            }
391    
392          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
393          if (pCk3gix) {          if (pCk3gix) {
# Line 454  namespace { Line 466  namespace {
466      }      }
467    
468      /**      /**
469         * Make a (semi) deep copy of the Sample object given by @a orig (without
470         * the actual waveform data) and assign it to this object.
471         *
472         * Discussion: copying .gig samples is a bit tricky. It requires three
473         * steps:
474         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
475         *    its new sample waveform data size.
476         * 2. Saving the file (done by File::Save()) so that it gains correct size
477         *    and layout for writing the actual wave form data directly to disc
478         *    in next step.
479         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
480         *
481         * @param orig - original Sample object to be copied from
482         */
483        void Sample::CopyAssignMeta(const Sample* orig) {
484            // handle base classes
485            DLS::Sample::CopyAssignCore(orig);
486            
487            // handle actual own attributes of this class
488            Manufacturer = orig->Manufacturer;
489            Product = orig->Product;
490            SamplePeriod = orig->SamplePeriod;
491            MIDIUnityNote = orig->MIDIUnityNote;
492            FineTune = orig->FineTune;
493            SMPTEFormat = orig->SMPTEFormat;
494            SMPTEOffset = orig->SMPTEOffset;
495            Loops = orig->Loops;
496            LoopID = orig->LoopID;
497            LoopType = orig->LoopType;
498            LoopStart = orig->LoopStart;
499            LoopEnd = orig->LoopEnd;
500            LoopSize = orig->LoopSize;
501            LoopFraction = orig->LoopFraction;
502            LoopPlayCount = orig->LoopPlayCount;
503            
504            // schedule resizing this sample to the given sample's size
505            Resize(orig->GetSize());
506        }
507    
508        /**
509         * Should be called after CopyAssignMeta() and File::Save() sequence.
510         * Read more about it in the discussion of CopyAssignMeta(). This method
511         * copies the actual waveform data by disk streaming.
512         *
513         * @e CAUTION: this method is currently not thread safe! During this
514         * operation the sample must not be used for other purposes by other
515         * threads!
516         *
517         * @param orig - original Sample object to be copied from
518         */
519        void Sample::CopyAssignWave(const Sample* orig) {
520            const int iReadAtOnce = 32*1024;
521            char* buf = new char[iReadAtOnce * orig->FrameSize];
522            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
523            file_offset_t restorePos = pOrig->GetPos();
524            pOrig->SetPos(0);
525            SetPos(0);
526            for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
527                               n = pOrig->Read(buf, iReadAtOnce))
528            {
529                Write(buf, n);
530            }
531            pOrig->SetPos(restorePos);
532            delete [] buf;
533        }
534    
535        /**
536       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
537       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
538       *       *
539       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
540       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
541       *       *
542         * @param pProgress - callback function for progress notification
543       * @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
544       *                        was provided yet       *                        was provided yet
545       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
546       */       */
547      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
548          // first update base class's chunks          // first update base class's chunks
549          DLS::Sample::UpdateChunks();          DLS::Sample::UpdateChunks(pProgress);
550    
551          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
552          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 514  namespace { Line 594  namespace {
594          // update '3gix' chunk          // update '3gix' chunk
595          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
596          store16(&pData[0], iSampleGroup);          store16(&pData[0], iSampleGroup);
597    
598            // if the library user toggled the "Compressed" attribute from true to
599            // false, then the EWAV chunk associated with compressed samples needs
600            // to be deleted
601            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
602            if (ewav && !Compressed) {
603                pWaveList->DeleteSubChunk(ewav);
604            }
605      }      }
606    
607      /// 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).
608      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
609          //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)
610          this->SamplesTotal = 0;          this->SamplesTotal = 0;
611          std::list<unsigned long> frameOffsets;          std::list<file_offset_t> frameOffsets;
612    
613          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
614          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
# Line 536  namespace { Line 624  namespace {
624                  const int mode_l = pCkData->ReadUint8();                  const int mode_l = pCkData->ReadUint8();
625                  const int mode_r = pCkData->ReadUint8();                  const int mode_r = pCkData->ReadUint8();
626                  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");
627                  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];                  const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
628    
629                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
630                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 555  namespace { Line 643  namespace {
643    
644                  const int mode = pCkData->ReadUint8();                  const int mode = pCkData->ReadUint8();
645                  if (mode > 5) throw gig::Exception("Unknown compression mode");                  if (mode > 5) throw gig::Exception("Unknown compression mode");
646                  const unsigned long frameSize = bytesPerFrame[mode];                  const file_offset_t frameSize = bytesPerFrame[mode];
647    
648                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
649                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 571  namespace { Line 659  namespace {
659    
660          // 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)
661          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
662          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new file_offset_t[frameOffsets.size()];
663          std::list<unsigned long>::iterator end  = frameOffsets.end();          std::list<file_offset_t>::iterator end  = frameOffsets.end();
664          std::list<unsigned long>::iterator iter = frameOffsets.begin();          std::list<file_offset_t>::iterator iter = frameOffsets.begin();
665          for (int i = 0; iter != end; i++, iter++) {          for (int i = 0; iter != end; i++, iter++) {
666              FrameTable[i] = *iter;              FrameTable[i] = *iter;
667          }          }
# Line 614  namespace { Line 702  namespace {
702       *                      the cached sample data in bytes       *                      the cached sample data in bytes
703       * @see                 ReleaseSampleData(), Read(), SetPos()       * @see                 ReleaseSampleData(), Read(), SetPos()
704       */       */
705      buffer_t Sample::LoadSampleData(unsigned long SampleCount) {      buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
706          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
707      }      }
708    
# Line 673  namespace { Line 761  namespace {
761       *                           size of the cached sample data in bytes       *                           size of the cached sample data in bytes
762       * @see                      ReleaseSampleData(), Read(), SetPos()       * @see                      ReleaseSampleData(), Read(), SetPos()
763       */       */
764      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
765          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
766          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
767          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
768          SetPos(0); // reset read position to begin of sample          SetPos(0); // reset read position to begin of sample
769          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
770          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
# Line 740  namespace { Line 828  namespace {
828       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
829       * other formats will fail!       * other formats will fail!
830       *       *
831       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
832       *                   greater than zero)       *                  greater than zero)
833       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
834       *                         or if \a iNewSize is less than 1       * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
835       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
836       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
837       *      DLS::Sample::FormatTag, File::Save()       *      DLS::Sample::FormatTag, File::Save()
838       */       */
839      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
840          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
841          DLS::Sample::Resize(iNewSize);          DLS::Sample::Resize(NewSize);
842      }      }
843    
844      /**      /**
# Line 774  namespace { Line 862  namespace {
862       * @returns            the new sample position       * @returns            the new sample position
863       * @see                Read()       * @see                Read()
864       */       */
865      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) {
866          if (Compressed) {          if (Compressed) {
867              switch (Whence) {              switch (Whence) {
868                  case RIFF::stream_curpos:                  case RIFF::stream_curpos:
# Line 792  namespace { Line 880  namespace {
880              }              }
881              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
882    
883              unsigned long frame = this->SamplePos / 2048; // to which frame to jump              file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
884              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame
885              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
886              return this->SamplePos;              return this->SamplePos;
887          }          }
888          else { // not compressed          else { // not compressed
889              unsigned long orderedBytes = SampleCount * this->FrameSize;              file_offset_t orderedBytes = SampleCount * this->FrameSize;
890              unsigned long result = pCkData->SetPos(orderedBytes, Whence);              file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
891              return (result == orderedBytes) ? SampleCount              return (result == orderedBytes) ? SampleCount
892                                              : result / this->FrameSize;                                              : result / this->FrameSize;
893          }          }
# Line 808  namespace { Line 896  namespace {
896      /**      /**
897       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
898       */       */
899      unsigned long Sample::GetPos() {      file_offset_t Sample::GetPos() const {
900          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
901          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
902      }      }
# Line 847  namespace { Line 935  namespace {
935       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
936       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
937       */       */
938      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,
939                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
940          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
941          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
942    
943          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
# Line 887  namespace { Line 975  namespace {
975                                  // reading, swap all sample frames so it reflects                                  // reading, swap all sample frames so it reflects
976                                  // backward playback                                  // backward playback
977    
978                                  unsigned long swapareastart       = totalreadsamples;                                  file_offset_t swapareastart       = totalreadsamples;
979                                  unsigned long loopoffset          = GetPos() - loop.LoopStart;                                  file_offset_t loopoffset          = GetPos() - loop.LoopStart;
980                                  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                  file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
981                                  unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                  file_offset_t reverseplaybackend  = GetPos() - samplestoreadinloop;
982    
983                                  SetPos(reverseplaybackend);                                  SetPos(reverseplaybackend);
984    
# Line 938  namespace { Line 1026  namespace {
1026                          // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
1027                          // backward playback                          // backward playback
1028    
1029                          unsigned long swapareastart       = totalreadsamples;                          file_offset_t swapareastart       = totalreadsamples;
1030                          unsigned long loopoffset          = GetPos() - loop.LoopStart;                          file_offset_t loopoffset          = GetPos() - loop.LoopStart;
1031                          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)
1032                                                                                    : samplestoread;                                                                                    : samplestoread;
1033                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);                          file_offset_t reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1034    
1035                          SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
1036    
# Line 1022  namespace { Line 1110  namespace {
1110       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1111       * @see                SetPos(), CreateDecompressionBuffer()       * @see                SetPos(), CreateDecompressionBuffer()
1112       */       */
1113      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) {
1114          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1115          if (!Compressed) {          if (!Compressed) {
1116              if (BitDepth == 24) {              if (BitDepth == 24) {
# Line 1037  namespace { Line 1125  namespace {
1125          else {          else {
1126              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1127              //TODO: efficiency: maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1128              unsigned long assumedsize      = GuessSize(SampleCount),              file_offset_t assumedsize      = GuessSize(SampleCount),
1129                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1130                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1131                            copysamples, skipsamples,                            copysamples, skipsamples,
# Line 1060  namespace { Line 1148  namespace {
1148              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1149    
1150              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
1151                  unsigned long framesamples = SamplesPerFrame;                  file_offset_t framesamples = SamplesPerFrame;
1152                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;                  file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1153    
1154                  int mode_l = *pSrc++, mode_r = 0;                  int mode_l = *pSrc++, mode_r = 0;
1155    
# Line 1211  namespace { Line 1299  namespace {
1299       * @throws gig::Exception if sample is compressed       * @throws gig::Exception if sample is compressed
1300       * @see DLS::LoadSampleData()       * @see DLS::LoadSampleData()
1301       */       */
1302      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1303          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)");
1304    
1305          // 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 1308  namespace {
1308              __resetCRC(crc);              __resetCRC(crc);
1309          }          }
1310          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");
1311          unsigned long res;          file_offset_t res;
1312          if (BitDepth == 24) {          if (BitDepth == 24) {
1313              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1314          } else { // 16 bit          } else { // 16 bit
# Line 1232  namespace { Line 1320  namespace {
1320          // if this is the last write, update the checksum chunk in the          // if this is the last write, update the checksum chunk in the
1321          // file          // file
1322          if (pCkData->GetPos() == pCkData->GetSize()) {          if (pCkData->GetPos() == pCkData->GetSize()) {
1323                __finalizeCRC(crc);
1324              File* pFile = static_cast<File*>(GetParent());              File* pFile = static_cast<File*>(GetParent());
1325              pFile->SetSampleChecksum(this, __encodeCRC(crc));              pFile->SetSampleChecksum(this, crc);
1326          }          }
1327          return res;          return res;
1328      }      }
# Line 1254  namespace { Line 1343  namespace {
1343       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1344       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1345       */       */
1346      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1347          buffer_t result;          buffer_t result;
1348          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1349                  (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;
1350          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);
1351          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1352          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1353          return result;          return result;
# Line 1292  namespace { Line 1381  namespace {
1381          return pGroup;          return pGroup;
1382      }      }
1383    
1384        /**
1385         * Returns the CRC-32 checksum of the sample's raw wave form data at the
1386         * time when this sample's wave form data was modified for the last time
1387         * by calling Write(). This checksum only covers the raw wave form data,
1388         * not any meta informations like i.e. bit depth or loop points. Since
1389         * this method just returns the checksum stored for this sample i.e. when
1390         * the gig file was loaded, this method returns immediately. So it does no
1391         * recalcuation of the checksum with the currently available sample wave
1392         * form data.
1393         *
1394         * @see VerifyWaveData()
1395         */
1396        uint32_t Sample::GetWaveDataCRC32Checksum() {
1397            return crc;
1398        }
1399    
1400        /**
1401         * Checks the integrity of this sample's raw audio wave data. Whenever a
1402         * Sample's raw wave data is intentionally modified (i.e. by calling
1403         * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1404         * is calculated and stored/updated for this sample, along to the sample's
1405         * meta informations.
1406         *
1407         * Now by calling this method the current raw audio wave data is checked
1408         * against the already stored CRC32 check sum in order to check whether the
1409         * sample data had been damaged unintentionally for some reason. Since by
1410         * calling this method always the entire raw audio wave data has to be
1411         * read, verifying all samples this way may take a long time accordingly.
1412         * And that's also the reason why the sample integrity is not checked by
1413         * default whenever a gig file is loaded. So this method must be called
1414         * explicitly to fulfill this task.
1415         *
1416         * @param pActually - (optional) if provided, will be set to the actually
1417         *                    calculated checksum of the current raw wave form data,
1418         *                    you can get the expected checksum instead by calling
1419         *                    GetWaveDataCRC32Checksum()
1420         * @returns true if sample is OK or false if the sample is damaged
1421         * @throws Exception if no checksum had been stored to disk for this
1422         *         sample yet, or on I/O issues
1423         * @see GetWaveDataCRC32Checksum()
1424         */
1425        bool Sample::VerifyWaveData(uint32_t* pActually) {
1426            //File* pFile = static_cast<File*>(GetParent());
1427            uint32_t crc = CalculateWaveDataChecksum();
1428            if (pActually) *pActually = crc;
1429            return crc == this->crc;
1430        }
1431    
1432        uint32_t Sample::CalculateWaveDataChecksum() {
1433            const size_t sz = 20*1024; // 20kB buffer size
1434            std::vector<uint8_t> buffer(sz);
1435            buffer.resize(sz);
1436    
1437            const size_t n = sz / FrameSize;
1438            SetPos(0);
1439            uint32_t crc = 0;
1440            __resetCRC(crc);
1441            while (true) {
1442                file_offset_t nRead = Read(&buffer[0], n);
1443                if (nRead <= 0) break;
1444                __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1445            }
1446            __finalizeCRC(crc);
1447            return crc;
1448        }
1449    
1450      Sample::~Sample() {      Sample::~Sample() {
1451          Instances--;          Instances--;
1452          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1308  namespace { Line 1463  namespace {
1463  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1464  // *  // *
1465    
1466      uint                               DimensionRegion::Instances       = 0;      size_t                             DimensionRegion::Instances       = 0;
1467      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1468    
1469      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
# Line 1433  namespace { Line 1588  namespace {
1588                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1589              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1590              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1591                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1592              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1593              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1594              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1502  namespace { Line 1657  namespace {
1657              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1658              EG2Decay1                       = 0.005;              EG2Decay1                       = 0.005;
1659              EG2Sustain                      = 1000;              EG2Sustain                      = 1000;
1660              EG2Release                      = 0.3;              EG2Release                      = 60;
1661              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1662              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1663              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
# Line 1581  namespace { Line 1736  namespace {
1736       */       */
1737      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1738          Instances++;          Instances++;
1739            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1740          *this = src; // default memberwise shallow copy of all parameters          *this = src; // default memberwise shallow copy of all parameters
1741          pParentList = _3ewl; // restore the chunk pointer          pParentList = _3ewl; // restore the chunk pointer
1742    
# Line 1596  namespace { Line 1752  namespace {
1752                  pSampleLoops[k] = src.pSampleLoops[k];                  pSampleLoops[k] = src.pSampleLoops[k];
1753          }          }
1754      }      }
1755        
1756        /**
1757         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1758         * and assign it to this object.
1759         *
1760         * Note that all sample pointers referenced by @a orig are simply copied as
1761         * memory address. Thus the respective samples are shared, not duplicated!
1762         *
1763         * @param orig - original DimensionRegion object to be copied from
1764         */
1765        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1766            CopyAssign(orig, NULL);
1767        }
1768    
1769        /**
1770         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1771         * and assign it to this object.
1772         *
1773         * @param orig - original DimensionRegion object to be copied from
1774         * @param mSamples - crosslink map between the foreign file's samples and
1775         *                   this file's samples
1776         */
1777        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1778            // delete all allocated data first
1779            if (VelocityTable) delete [] VelocityTable;
1780            if (pSampleLoops) delete [] pSampleLoops;
1781            
1782            // backup parent list pointer
1783            RIFF::List* p = pParentList;
1784            
1785            gig::Sample* pOriginalSample = pSample;
1786            gig::Region* pOriginalRegion = pRegion;
1787            
1788            //NOTE: copy code copied from assignment constructor above, see comment there as well
1789            
1790            *this = *orig; // default memberwise shallow copy of all parameters
1791            
1792            // restore members that shall not be altered
1793            pParentList = p; // restore the chunk pointer
1794            pRegion = pOriginalRegion;
1795            
1796            // only take the raw sample reference reference if the
1797            // two DimensionRegion objects are part of the same file
1798            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1799                pSample = pOriginalSample;
1800            }
1801            
1802            if (mSamples && mSamples->count(orig->pSample)) {
1803                pSample = mSamples->find(orig->pSample)->second;
1804            }
1805    
1806            // deep copy of owned structures
1807            if (orig->VelocityTable) {
1808                VelocityTable = new uint8_t[128];
1809                for (int k = 0 ; k < 128 ; k++)
1810                    VelocityTable[k] = orig->VelocityTable[k];
1811            }
1812            if (orig->pSampleLoops) {
1813                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1814                for (int k = 0 ; k < orig->SampleLoops ; k++)
1815                    pSampleLoops[k] = orig->pSampleLoops[k];
1816            }
1817        }
1818    
1819        void DimensionRegion::serialize(Serialization::Archive* archive) {
1820            SRLZ(VelocityUpperLimit);
1821            SRLZ(EG1PreAttack);
1822            SRLZ(EG1Attack);
1823            SRLZ(EG1Decay1);
1824            SRLZ(EG1Decay2);
1825            SRLZ(EG1InfiniteSustain);
1826            SRLZ(EG1Sustain);
1827            SRLZ(EG1Release);
1828            SRLZ(EG1Hold);
1829            SRLZ(EG1Controller);
1830            SRLZ(EG1ControllerInvert);
1831            SRLZ(EG1ControllerAttackInfluence);
1832            SRLZ(EG1ControllerDecayInfluence);
1833            SRLZ(EG1ControllerReleaseInfluence);
1834            SRLZ(LFO1Frequency);
1835            SRLZ(LFO1InternalDepth);
1836            SRLZ(LFO1ControlDepth);
1837            SRLZ(LFO1Controller);
1838            SRLZ(LFO1FlipPhase);
1839            SRLZ(LFO1Sync);
1840            SRLZ(EG2PreAttack);
1841            SRLZ(EG2Attack);
1842            SRLZ(EG2Decay1);
1843            SRLZ(EG2Decay2);
1844            SRLZ(EG2InfiniteSustain);
1845            SRLZ(EG2Sustain);
1846            SRLZ(EG2Release);
1847            SRLZ(EG2Controller);
1848            SRLZ(EG2ControllerInvert);
1849            SRLZ(EG2ControllerAttackInfluence);
1850            SRLZ(EG2ControllerDecayInfluence);
1851            SRLZ(EG2ControllerReleaseInfluence);
1852            SRLZ(LFO2Frequency);
1853            SRLZ(LFO2InternalDepth);
1854            SRLZ(LFO2ControlDepth);
1855            SRLZ(LFO2Controller);
1856            SRLZ(LFO2FlipPhase);
1857            SRLZ(LFO2Sync);
1858            SRLZ(EG3Attack);
1859            SRLZ(EG3Depth);
1860            SRLZ(LFO3Frequency);
1861            SRLZ(LFO3InternalDepth);
1862            SRLZ(LFO3ControlDepth);
1863            SRLZ(LFO3Controller);
1864            SRLZ(LFO3Sync);
1865            SRLZ(VCFEnabled);
1866            SRLZ(VCFType);
1867            SRLZ(VCFCutoffController);
1868            SRLZ(VCFCutoffControllerInvert);
1869            SRLZ(VCFCutoff);
1870            SRLZ(VCFVelocityCurve);
1871            SRLZ(VCFVelocityScale);
1872            SRLZ(VCFVelocityDynamicRange);
1873            SRLZ(VCFResonance);
1874            SRLZ(VCFResonanceDynamic);
1875            SRLZ(VCFResonanceController);
1876            SRLZ(VCFKeyboardTracking);
1877            SRLZ(VCFKeyboardTrackingBreakpoint);
1878            SRLZ(VelocityResponseCurve);
1879            SRLZ(VelocityResponseDepth);
1880            SRLZ(VelocityResponseCurveScaling);
1881            SRLZ(ReleaseVelocityResponseCurve);
1882            SRLZ(ReleaseVelocityResponseDepth);
1883            SRLZ(ReleaseTriggerDecay);
1884            SRLZ(Crossfade);
1885            SRLZ(PitchTrack);
1886            SRLZ(DimensionBypass);
1887            SRLZ(Pan);
1888            SRLZ(SelfMask);
1889            SRLZ(AttenuationController);
1890            SRLZ(InvertAttenuationController);
1891            SRLZ(AttenuationControllerThreshold);
1892            SRLZ(ChannelOffset);
1893            SRLZ(SustainDefeat);
1894            SRLZ(MSDecode);
1895            //SRLZ(SampleStartOffset);
1896            SRLZ(SampleAttenuation);
1897    
1898            // derived attributes from DLS::Sampler
1899            SRLZ(FineTune);
1900            SRLZ(Gain);
1901        }
1902    
1903      /**      /**
1904       * Updates the respective member variable and updates @c SampleAttenuation       * Updates the respective member variable and updates @c SampleAttenuation
# Line 1612  namespace { Line 1915  namespace {
1915       *       *
1916       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
1917       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
1918         *
1919         * @param pProgress - callback function for progress notification
1920       */       */
1921      void DimensionRegion::UpdateChunks() {      void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1922          // first update base class's chunk          // first update base class's chunk
1923          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks(pProgress);
1924    
1925          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1926          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
# Line 1635  namespace { Line 1940  namespace {
1940    
1941          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1942    
1943          const uint32_t chunksize = _3ewa->GetNewSize();          const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1944          store32(&pData[0], chunksize); // unknown, always chunk size?          store32(&pData[0], chunksize); // unknown, always chunk size?
1945    
1946          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
# Line 1837  namespace { Line 2142  namespace {
2142          }          }
2143    
2144          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
2145                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
2146          store16(&pData[116], eg3depth);          store16(&pData[116], eg3depth);
2147    
2148          // next 2 bytes unknown          // next 2 bytes unknown
# Line 1885  namespace { Line 2190  namespace {
2190                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2191          pData[137] = vcfbreakpoint;          pData[137] = vcfbreakpoint;
2192    
2193          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2194                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2195          pData[138] = vcfvelocity;          pData[138] = vcfvelocity;
2196    
# Line 1950  namespace { Line 2255  namespace {
2255          return pRegion;          return pRegion;
2256      }      }
2257    
2258    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2259    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2260    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2261    //#pragma GCC diagnostic push
2262    //#pragma GCC diagnostic error "-Wswitch"
2263    
2264      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2265          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2266          switch (EncodedController) {          switch (EncodedController) {
# Line 2061  namespace { Line 2372  namespace {
2372                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2373                  break;                  break;
2374    
2375                // format extension (these controllers are so far only supported by
2376                // LinuxSampler & gigedit) they will *NOT* work with
2377                // Gigasampler/GigaStudio !
2378                case _lev_ctrl_CC3_EXT:
2379                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2380                    decodedcontroller.controller_number = 3;
2381                    break;
2382                case _lev_ctrl_CC6_EXT:
2383                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2384                    decodedcontroller.controller_number = 6;
2385                    break;
2386                case _lev_ctrl_CC7_EXT:
2387                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2388                    decodedcontroller.controller_number = 7;
2389                    break;
2390                case _lev_ctrl_CC8_EXT:
2391                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2392                    decodedcontroller.controller_number = 8;
2393                    break;
2394                case _lev_ctrl_CC9_EXT:
2395                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2396                    decodedcontroller.controller_number = 9;
2397                    break;
2398                case _lev_ctrl_CC10_EXT:
2399                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2400                    decodedcontroller.controller_number = 10;
2401                    break;
2402                case _lev_ctrl_CC11_EXT:
2403                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2404                    decodedcontroller.controller_number = 11;
2405                    break;
2406                case _lev_ctrl_CC14_EXT:
2407                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2408                    decodedcontroller.controller_number = 14;
2409                    break;
2410                case _lev_ctrl_CC15_EXT:
2411                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2412                    decodedcontroller.controller_number = 15;
2413                    break;
2414                case _lev_ctrl_CC20_EXT:
2415                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2416                    decodedcontroller.controller_number = 20;
2417                    break;
2418                case _lev_ctrl_CC21_EXT:
2419                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2420                    decodedcontroller.controller_number = 21;
2421                    break;
2422                case _lev_ctrl_CC22_EXT:
2423                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2424                    decodedcontroller.controller_number = 22;
2425                    break;
2426                case _lev_ctrl_CC23_EXT:
2427                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2428                    decodedcontroller.controller_number = 23;
2429                    break;
2430                case _lev_ctrl_CC24_EXT:
2431                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2432                    decodedcontroller.controller_number = 24;
2433                    break;
2434                case _lev_ctrl_CC25_EXT:
2435                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2436                    decodedcontroller.controller_number = 25;
2437                    break;
2438                case _lev_ctrl_CC26_EXT:
2439                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2440                    decodedcontroller.controller_number = 26;
2441                    break;
2442                case _lev_ctrl_CC27_EXT:
2443                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2444                    decodedcontroller.controller_number = 27;
2445                    break;
2446                case _lev_ctrl_CC28_EXT:
2447                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2448                    decodedcontroller.controller_number = 28;
2449                    break;
2450                case _lev_ctrl_CC29_EXT:
2451                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2452                    decodedcontroller.controller_number = 29;
2453                    break;
2454                case _lev_ctrl_CC30_EXT:
2455                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2456                    decodedcontroller.controller_number = 30;
2457                    break;
2458                case _lev_ctrl_CC31_EXT:
2459                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2460                    decodedcontroller.controller_number = 31;
2461                    break;
2462                case _lev_ctrl_CC68_EXT:
2463                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2464                    decodedcontroller.controller_number = 68;
2465                    break;
2466                case _lev_ctrl_CC69_EXT:
2467                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2468                    decodedcontroller.controller_number = 69;
2469                    break;
2470                case _lev_ctrl_CC70_EXT:
2471                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2472                    decodedcontroller.controller_number = 70;
2473                    break;
2474                case _lev_ctrl_CC71_EXT:
2475                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2476                    decodedcontroller.controller_number = 71;
2477                    break;
2478                case _lev_ctrl_CC72_EXT:
2479                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2480                    decodedcontroller.controller_number = 72;
2481                    break;
2482                case _lev_ctrl_CC73_EXT:
2483                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2484                    decodedcontroller.controller_number = 73;
2485                    break;
2486                case _lev_ctrl_CC74_EXT:
2487                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2488                    decodedcontroller.controller_number = 74;
2489                    break;
2490                case _lev_ctrl_CC75_EXT:
2491                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2492                    decodedcontroller.controller_number = 75;
2493                    break;
2494                case _lev_ctrl_CC76_EXT:
2495                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2496                    decodedcontroller.controller_number = 76;
2497                    break;
2498                case _lev_ctrl_CC77_EXT:
2499                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2500                    decodedcontroller.controller_number = 77;
2501                    break;
2502                case _lev_ctrl_CC78_EXT:
2503                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2504                    decodedcontroller.controller_number = 78;
2505                    break;
2506                case _lev_ctrl_CC79_EXT:
2507                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2508                    decodedcontroller.controller_number = 79;
2509                    break;
2510                case _lev_ctrl_CC84_EXT:
2511                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2512                    decodedcontroller.controller_number = 84;
2513                    break;
2514                case _lev_ctrl_CC85_EXT:
2515                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2516                    decodedcontroller.controller_number = 85;
2517                    break;
2518                case _lev_ctrl_CC86_EXT:
2519                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2520                    decodedcontroller.controller_number = 86;
2521                    break;
2522                case _lev_ctrl_CC87_EXT:
2523                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2524                    decodedcontroller.controller_number = 87;
2525                    break;
2526                case _lev_ctrl_CC89_EXT:
2527                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2528                    decodedcontroller.controller_number = 89;
2529                    break;
2530                case _lev_ctrl_CC90_EXT:
2531                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2532                    decodedcontroller.controller_number = 90;
2533                    break;
2534                case _lev_ctrl_CC96_EXT:
2535                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2536                    decodedcontroller.controller_number = 96;
2537                    break;
2538                case _lev_ctrl_CC97_EXT:
2539                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2540                    decodedcontroller.controller_number = 97;
2541                    break;
2542                case _lev_ctrl_CC102_EXT:
2543                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2544                    decodedcontroller.controller_number = 102;
2545                    break;
2546                case _lev_ctrl_CC103_EXT:
2547                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2548                    decodedcontroller.controller_number = 103;
2549                    break;
2550                case _lev_ctrl_CC104_EXT:
2551                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2552                    decodedcontroller.controller_number = 104;
2553                    break;
2554                case _lev_ctrl_CC105_EXT:
2555                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2556                    decodedcontroller.controller_number = 105;
2557                    break;
2558                case _lev_ctrl_CC106_EXT:
2559                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2560                    decodedcontroller.controller_number = 106;
2561                    break;
2562                case _lev_ctrl_CC107_EXT:
2563                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2564                    decodedcontroller.controller_number = 107;
2565                    break;
2566                case _lev_ctrl_CC108_EXT:
2567                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2568                    decodedcontroller.controller_number = 108;
2569                    break;
2570                case _lev_ctrl_CC109_EXT:
2571                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2572                    decodedcontroller.controller_number = 109;
2573                    break;
2574                case _lev_ctrl_CC110_EXT:
2575                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2576                    decodedcontroller.controller_number = 110;
2577                    break;
2578                case _lev_ctrl_CC111_EXT:
2579                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2580                    decodedcontroller.controller_number = 111;
2581                    break;
2582                case _lev_ctrl_CC112_EXT:
2583                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2584                    decodedcontroller.controller_number = 112;
2585                    break;
2586                case _lev_ctrl_CC113_EXT:
2587                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2588                    decodedcontroller.controller_number = 113;
2589                    break;
2590                case _lev_ctrl_CC114_EXT:
2591                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2592                    decodedcontroller.controller_number = 114;
2593                    break;
2594                case _lev_ctrl_CC115_EXT:
2595                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2596                    decodedcontroller.controller_number = 115;
2597                    break;
2598                case _lev_ctrl_CC116_EXT:
2599                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2600                    decodedcontroller.controller_number = 116;
2601                    break;
2602                case _lev_ctrl_CC117_EXT:
2603                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2604                    decodedcontroller.controller_number = 117;
2605                    break;
2606                case _lev_ctrl_CC118_EXT:
2607                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2608                    decodedcontroller.controller_number = 118;
2609                    break;
2610                case _lev_ctrl_CC119_EXT:
2611                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2612                    decodedcontroller.controller_number = 119;
2613                    break;
2614    
2615              // unknown controller type              // unknown controller type
2616              default:              default:
2617                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2618          }          }
2619          return decodedcontroller;          return decodedcontroller;
2620      }      }
2621        
2622    // see above (diagnostic push not supported prior GCC 4.6)
2623    //#pragma GCC diagnostic pop
2624    
2625      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2626          _lev_ctrl_t encodedcontroller;          _lev_ctrl_t encodedcontroller;
# Line 2154  namespace { Line 2708  namespace {
2708                      case 95:                      case 95:
2709                          encodedcontroller = _lev_ctrl_effect5depth;                          encodedcontroller = _lev_ctrl_effect5depth;
2710                          break;                          break;
2711    
2712                        // format extension (these controllers are so far only
2713                        // supported by LinuxSampler & gigedit) they will *NOT*
2714                        // work with Gigasampler/GigaStudio !
2715                        case 3:
2716                            encodedcontroller = _lev_ctrl_CC3_EXT;
2717                            break;
2718                        case 6:
2719                            encodedcontroller = _lev_ctrl_CC6_EXT;
2720                            break;
2721                        case 7:
2722                            encodedcontroller = _lev_ctrl_CC7_EXT;
2723                            break;
2724                        case 8:
2725                            encodedcontroller = _lev_ctrl_CC8_EXT;
2726                            break;
2727                        case 9:
2728                            encodedcontroller = _lev_ctrl_CC9_EXT;
2729                            break;
2730                        case 10:
2731                            encodedcontroller = _lev_ctrl_CC10_EXT;
2732                            break;
2733                        case 11:
2734                            encodedcontroller = _lev_ctrl_CC11_EXT;
2735                            break;
2736                        case 14:
2737                            encodedcontroller = _lev_ctrl_CC14_EXT;
2738                            break;
2739                        case 15:
2740                            encodedcontroller = _lev_ctrl_CC15_EXT;
2741                            break;
2742                        case 20:
2743                            encodedcontroller = _lev_ctrl_CC20_EXT;
2744                            break;
2745                        case 21:
2746                            encodedcontroller = _lev_ctrl_CC21_EXT;
2747                            break;
2748                        case 22:
2749                            encodedcontroller = _lev_ctrl_CC22_EXT;
2750                            break;
2751                        case 23:
2752                            encodedcontroller = _lev_ctrl_CC23_EXT;
2753                            break;
2754                        case 24:
2755                            encodedcontroller = _lev_ctrl_CC24_EXT;
2756                            break;
2757                        case 25:
2758                            encodedcontroller = _lev_ctrl_CC25_EXT;
2759                            break;
2760                        case 26:
2761                            encodedcontroller = _lev_ctrl_CC26_EXT;
2762                            break;
2763                        case 27:
2764                            encodedcontroller = _lev_ctrl_CC27_EXT;
2765                            break;
2766                        case 28:
2767                            encodedcontroller = _lev_ctrl_CC28_EXT;
2768                            break;
2769                        case 29:
2770                            encodedcontroller = _lev_ctrl_CC29_EXT;
2771                            break;
2772                        case 30:
2773                            encodedcontroller = _lev_ctrl_CC30_EXT;
2774                            break;
2775                        case 31:
2776                            encodedcontroller = _lev_ctrl_CC31_EXT;
2777                            break;
2778                        case 68:
2779                            encodedcontroller = _lev_ctrl_CC68_EXT;
2780                            break;
2781                        case 69:
2782                            encodedcontroller = _lev_ctrl_CC69_EXT;
2783                            break;
2784                        case 70:
2785                            encodedcontroller = _lev_ctrl_CC70_EXT;
2786                            break;
2787                        case 71:
2788                            encodedcontroller = _lev_ctrl_CC71_EXT;
2789                            break;
2790                        case 72:
2791                            encodedcontroller = _lev_ctrl_CC72_EXT;
2792                            break;
2793                        case 73:
2794                            encodedcontroller = _lev_ctrl_CC73_EXT;
2795                            break;
2796                        case 74:
2797                            encodedcontroller = _lev_ctrl_CC74_EXT;
2798                            break;
2799                        case 75:
2800                            encodedcontroller = _lev_ctrl_CC75_EXT;
2801                            break;
2802                        case 76:
2803                            encodedcontroller = _lev_ctrl_CC76_EXT;
2804                            break;
2805                        case 77:
2806                            encodedcontroller = _lev_ctrl_CC77_EXT;
2807                            break;
2808                        case 78:
2809                            encodedcontroller = _lev_ctrl_CC78_EXT;
2810                            break;
2811                        case 79:
2812                            encodedcontroller = _lev_ctrl_CC79_EXT;
2813                            break;
2814                        case 84:
2815                            encodedcontroller = _lev_ctrl_CC84_EXT;
2816                            break;
2817                        case 85:
2818                            encodedcontroller = _lev_ctrl_CC85_EXT;
2819                            break;
2820                        case 86:
2821                            encodedcontroller = _lev_ctrl_CC86_EXT;
2822                            break;
2823                        case 87:
2824                            encodedcontroller = _lev_ctrl_CC87_EXT;
2825                            break;
2826                        case 89:
2827                            encodedcontroller = _lev_ctrl_CC89_EXT;
2828                            break;
2829                        case 90:
2830                            encodedcontroller = _lev_ctrl_CC90_EXT;
2831                            break;
2832                        case 96:
2833                            encodedcontroller = _lev_ctrl_CC96_EXT;
2834                            break;
2835                        case 97:
2836                            encodedcontroller = _lev_ctrl_CC97_EXT;
2837                            break;
2838                        case 102:
2839                            encodedcontroller = _lev_ctrl_CC102_EXT;
2840                            break;
2841                        case 103:
2842                            encodedcontroller = _lev_ctrl_CC103_EXT;
2843                            break;
2844                        case 104:
2845                            encodedcontroller = _lev_ctrl_CC104_EXT;
2846                            break;
2847                        case 105:
2848                            encodedcontroller = _lev_ctrl_CC105_EXT;
2849                            break;
2850                        case 106:
2851                            encodedcontroller = _lev_ctrl_CC106_EXT;
2852                            break;
2853                        case 107:
2854                            encodedcontroller = _lev_ctrl_CC107_EXT;
2855                            break;
2856                        case 108:
2857                            encodedcontroller = _lev_ctrl_CC108_EXT;
2858                            break;
2859                        case 109:
2860                            encodedcontroller = _lev_ctrl_CC109_EXT;
2861                            break;
2862                        case 110:
2863                            encodedcontroller = _lev_ctrl_CC110_EXT;
2864                            break;
2865                        case 111:
2866                            encodedcontroller = _lev_ctrl_CC111_EXT;
2867                            break;
2868                        case 112:
2869                            encodedcontroller = _lev_ctrl_CC112_EXT;
2870                            break;
2871                        case 113:
2872                            encodedcontroller = _lev_ctrl_CC113_EXT;
2873                            break;
2874                        case 114:
2875                            encodedcontroller = _lev_ctrl_CC114_EXT;
2876                            break;
2877                        case 115:
2878                            encodedcontroller = _lev_ctrl_CC115_EXT;
2879                            break;
2880                        case 116:
2881                            encodedcontroller = _lev_ctrl_CC116_EXT;
2882                            break;
2883                        case 117:
2884                            encodedcontroller = _lev_ctrl_CC117_EXT;
2885                            break;
2886                        case 118:
2887                            encodedcontroller = _lev_ctrl_CC118_EXT;
2888                            break;
2889                        case 119:
2890                            encodedcontroller = _lev_ctrl_CC119_EXT;
2891                            break;
2892    
2893                      default:                      default:
2894                          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");
2895                  }                  }
# Line 2455  namespace { Line 3191  namespace {
3191       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
3192       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
3193       *       *
3194         * @param pProgress - callback function for progress notification
3195       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3196       */       */
3197      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
3198          // 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
3199          // 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
3200          // 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 3202  namespace {
3202          pSample = pDimensionRegions[0]->pSample;          pSample = pDimensionRegions[0]->pSample;
3203    
3204          // first update base class's chunks          // first update base class's chunks
3205          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks(pProgress);
3206    
3207          // update dimension region's chunks          // update dimension region's chunks
3208          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
3209              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks(pProgress);
3210          }          }
3211    
3212          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
# Line 2485  namespace { Line 3222  namespace {
3222              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3223    
3224              // move 3prg to last position              // move 3prg to last position
3225              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3226          }          }
3227    
3228          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
# Line 2559  namespace { Line 3296  namespace {
3296          int step = 1;          int step = 1;
3297          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3298          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3299    
3300          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3301          int dim[8] = { 0 };          int dim[8] = { 0 };
3302          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3303                const int end = i + step * pDimensionDefinitions[veldim].zones;
3304    
3305                // create a velocity table for all cases where the velocity zone is zero
3306              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3307                  pDimensionRegions[i]->VelocityUpperLimit) {                  pDimensionRegions[i]->VelocityUpperLimit) {
3308                  // create the velocity table                  // create the velocity table
# Line 2595  namespace { Line 3333  namespace {
3333                  }                  }
3334              }              }
3335    
3336                // jump to the next case where the velocity zone is zero
3337              int j;              int j;
3338              int shift = 0;              int shift = 0;
3339              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 2631  namespace { Line 3370  namespace {
3370       *                        dimension bits limit is violated       *                        dimension bits limit is violated
3371       */       */
3372      void Region::AddDimension(dimension_def_t* pDimDef) {      void Region::AddDimension(dimension_def_t* pDimDef) {
3373            // some initial sanity checks of the given dimension definition
3374            if (pDimDef->zones < 2)
3375                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3376            if (pDimDef->bits < 1)
3377                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3378            if (pDimDef->dimension == dimension_samplechannel) {
3379                if (pDimDef->zones != 2)
3380                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3381                if (pDimDef->bits != 1)
3382                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3383            }
3384    
3385          // check if max. amount of dimensions reached          // check if max. amount of dimensions reached
3386          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3387          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 3557  namespace {
3557          if (pDimDef->dimension == dimension_layer) Layers = 1;          if (pDimDef->dimension == dimension_layer) Layers = 1;
3558      }      }
3559    
3560        /** @brief Delete one split zone of a dimension (decrement zone amount).
3561         *
3562         * Instead of deleting an entire dimensions, this method will only delete
3563         * one particular split zone given by @a zone of the Region's dimension
3564         * given by @a type. So this method will simply decrement the amount of
3565         * zones by one of the dimension in question. To be able to do that, the
3566         * respective dimension must exist on this Region and it must have at least
3567         * 3 zones. All DimensionRegion objects associated with the zone will be
3568         * deleted.
3569         *
3570         * @param type - identifies the dimension where a zone shall be deleted
3571         * @param zone - index of the dimension split zone that shall be deleted
3572         * @throws gig::Exception if requested zone could not be deleted
3573         */
3574        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3575            dimension_def_t* oldDef = GetDimensionDefinition(type);
3576            if (!oldDef)
3577                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3578            if (oldDef->zones <= 2)
3579                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3580            if (zone < 0 || zone >= oldDef->zones)
3581                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3582    
3583            const int newZoneSize = oldDef->zones - 1;
3584    
3585            // create a temporary Region which just acts as a temporary copy
3586            // container and will be deleted at the end of this function and will
3587            // also not be visible through the API during this process
3588            gig::Region* tempRgn = NULL;
3589            {
3590                // adding these temporary chunks is probably not even necessary
3591                Instrument* instr = static_cast<Instrument*>(GetParent());
3592                RIFF::List* pCkInstrument = instr->pCkInstrument;
3593                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3594                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3595                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3596                tempRgn = new Region(instr, rgn);
3597            }
3598    
3599            // copy this region's dimensions (with already the dimension split size
3600            // requested by the arguments of this method call) to the temporary
3601            // region, and don't use Region::CopyAssign() here for this task, since
3602            // it would also alter fast lookup helper variables here and there
3603            dimension_def_t newDef;
3604            for (int i = 0; i < Dimensions; ++i) {
3605                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3606                // is this the dimension requested by the method arguments? ...
3607                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3608                    def.zones = newZoneSize;
3609                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3610                    newDef = def;
3611                }
3612                tempRgn->AddDimension(&def);
3613            }
3614    
3615            // find the dimension index in the tempRegion which is the dimension
3616            // type passed to this method (paranoidly expecting different order)
3617            int tempReducedDimensionIndex = -1;
3618            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3619                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3620                    tempReducedDimensionIndex = d;
3621                    break;
3622                }
3623            }
3624    
3625            // copy dimension regions from this region to the temporary region
3626            for (int iDst = 0; iDst < 256; ++iDst) {
3627                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3628                if (!dstDimRgn) continue;
3629                std::map<dimension_t,int> dimCase;
3630                bool isValidZone = true;
3631                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3632                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3633                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3634                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3635                    baseBits += dstBits;
3636                    // there are also DimensionRegion objects of unused zones, skip them
3637                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3638                        isValidZone = false;
3639                        break;
3640                    }
3641                }
3642                if (!isValidZone) continue;
3643                // a bit paranoid: cope with the chance that the dimensions would
3644                // have different order in source and destination regions
3645                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3646                if (dimCase[type] >= zone) dimCase[type]++;
3647                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3648                dstDimRgn->CopyAssign(srcDimRgn);
3649                // if this is the upper most zone of the dimension passed to this
3650                // method, then correct (raise) its upper limit to 127
3651                if (newDef.split_type == split_type_normal && isLastZone)
3652                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3653            }
3654    
3655            // now tempRegion's dimensions and DimensionRegions basically reflect
3656            // what we wanted to get for this actual Region here, so we now just
3657            // delete and recreate the dimension in question with the new amount
3658            // zones and then copy back from tempRegion      
3659            DeleteDimension(oldDef);
3660            AddDimension(&newDef);
3661            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3662                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3663                if (!srcDimRgn) continue;
3664                std::map<dimension_t,int> dimCase;
3665                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3666                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3667                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3668                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3669                    baseBits += srcBits;
3670                }
3671                // a bit paranoid: cope with the chance that the dimensions would
3672                // have different order in source and destination regions
3673                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3674                if (!dstDimRgn) continue;
3675                dstDimRgn->CopyAssign(srcDimRgn);
3676            }
3677    
3678            // delete temporary region
3679            delete tempRgn;
3680    
3681            UpdateVelocityTable();
3682        }
3683    
3684        /** @brief Divide split zone of a dimension in two (increment zone amount).
3685         *
3686         * This will increment the amount of zones for the dimension (given by
3687         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3688         * in the middle of its zone range in two. So the two zones resulting from
3689         * the zone being splitted, will be an equivalent copy regarding all their
3690         * articulation informations and sample reference. The two zones will only
3691         * differ in their zone's upper limit
3692         * (DimensionRegion::DimensionUpperLimits).
3693         *
3694         * @param type - identifies the dimension where a zone shall be splitted
3695         * @param zone - index of the dimension split zone that shall be splitted
3696         * @throws gig::Exception if requested zone could not be splitted
3697         */
3698        void Region::SplitDimensionZone(dimension_t type, int zone) {
3699            dimension_def_t* oldDef = GetDimensionDefinition(type);
3700            if (!oldDef)
3701                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3702            if (zone < 0 || zone >= oldDef->zones)
3703                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3704    
3705            const int newZoneSize = oldDef->zones + 1;
3706    
3707            // create a temporary Region which just acts as a temporary copy
3708            // container and will be deleted at the end of this function and will
3709            // also not be visible through the API during this process
3710            gig::Region* tempRgn = NULL;
3711            {
3712                // adding these temporary chunks is probably not even necessary
3713                Instrument* instr = static_cast<Instrument*>(GetParent());
3714                RIFF::List* pCkInstrument = instr->pCkInstrument;
3715                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3716                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3717                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3718                tempRgn = new Region(instr, rgn);
3719            }
3720    
3721            // copy this region's dimensions (with already the dimension split size
3722            // requested by the arguments of this method call) to the temporary
3723            // region, and don't use Region::CopyAssign() here for this task, since
3724            // it would also alter fast lookup helper variables here and there
3725            dimension_def_t newDef;
3726            for (int i = 0; i < Dimensions; ++i) {
3727                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3728                // is this the dimension requested by the method arguments? ...
3729                if (def.dimension == type) { // ... if yes, increment zone amount by one
3730                    def.zones = newZoneSize;
3731                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3732                    newDef = def;
3733                }
3734                tempRgn->AddDimension(&def);
3735            }
3736    
3737            // find the dimension index in the tempRegion which is the dimension
3738            // type passed to this method (paranoidly expecting different order)
3739            int tempIncreasedDimensionIndex = -1;
3740            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3741                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3742                    tempIncreasedDimensionIndex = d;
3743                    break;
3744                }
3745            }
3746    
3747            // copy dimension regions from this region to the temporary region
3748            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3749                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3750                if (!srcDimRgn) continue;
3751                std::map<dimension_t,int> dimCase;
3752                bool isValidZone = true;
3753                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3754                    const int srcBits = pDimensionDefinitions[d].bits;
3755                    dimCase[pDimensionDefinitions[d].dimension] =
3756                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3757                    // there are also DimensionRegion objects for unused zones, skip them
3758                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3759                        isValidZone = false;
3760                        break;
3761                    }
3762                    baseBits += srcBits;
3763                }
3764                if (!isValidZone) continue;
3765                // a bit paranoid: cope with the chance that the dimensions would
3766                // have different order in source and destination regions            
3767                if (dimCase[type] > zone) dimCase[type]++;
3768                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3769                dstDimRgn->CopyAssign(srcDimRgn);
3770                // if this is the requested zone to be splitted, then also copy
3771                // the source DimensionRegion to the newly created target zone
3772                // and set the old zones upper limit lower
3773                if (dimCase[type] == zone) {
3774                    // lower old zones upper limit
3775                    if (newDef.split_type == split_type_normal) {
3776                        const int high =
3777                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3778                        int low = 0;
3779                        if (zone > 0) {
3780                            std::map<dimension_t,int> lowerCase = dimCase;
3781                            lowerCase[type]--;
3782                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3783                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3784                        }
3785                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3786                    }
3787                    // fill the newly created zone of the divided zone as well
3788                    dimCase[type]++;
3789                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3790                    dstDimRgn->CopyAssign(srcDimRgn);
3791                }
3792            }
3793    
3794            // now tempRegion's dimensions and DimensionRegions basically reflect
3795            // what we wanted to get for this actual Region here, so we now just
3796            // delete and recreate the dimension in question with the new amount
3797            // zones and then copy back from tempRegion      
3798            DeleteDimension(oldDef);
3799            AddDimension(&newDef);
3800            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3801                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3802                if (!srcDimRgn) continue;
3803                std::map<dimension_t,int> dimCase;
3804                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3805                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3806                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3807                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3808                    baseBits += srcBits;
3809                }
3810                // a bit paranoid: cope with the chance that the dimensions would
3811                // have different order in source and destination regions
3812                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3813                if (!dstDimRgn) continue;
3814                dstDimRgn->CopyAssign(srcDimRgn);
3815            }
3816    
3817            // delete temporary region
3818            delete tempRgn;
3819    
3820            UpdateVelocityTable();
3821        }
3822    
3823        /** @brief Change type of an existing dimension.
3824         *
3825         * Alters the dimension type of a dimension already existing on this
3826         * region. If there is currently no dimension on this Region with type
3827         * @a oldType, then this call with throw an Exception. Likewise there are
3828         * cases where the requested dimension type cannot be performed. For example
3829         * if the new dimension type shall be gig::dimension_samplechannel, and the
3830         * current dimension has more than 2 zones. In such cases an Exception is
3831         * thrown as well.
3832         *
3833         * @param oldType - identifies the existing dimension to be changed
3834         * @param newType - to which dimension type it should be changed to
3835         * @throws gig::Exception if requested change cannot be performed
3836         */
3837        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3838            if (oldType == newType) return;
3839            dimension_def_t* def = GetDimensionDefinition(oldType);
3840            if (!def)
3841                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3842            if (newType == dimension_samplechannel && def->zones != 2)
3843                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3844            if (GetDimensionDefinition(newType))
3845                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3846            def->dimension  = newType;
3847            def->split_type = __resolveSplitType(newType);
3848        }
3849    
3850        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3851            uint8_t bits[8] = {};
3852            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3853                 it != DimCase.end(); ++it)
3854            {
3855                for (int d = 0; d < Dimensions; ++d) {
3856                    if (pDimensionDefinitions[d].dimension == it->first) {
3857                        bits[d] = it->second;
3858                        goto nextDimCaseSlice;
3859                    }
3860                }
3861                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3862                nextDimCaseSlice:
3863                ; // noop
3864            }
3865            return GetDimensionRegionByBit(bits);
3866        }
3867    
3868        /**
3869         * Searches in the current Region for a dimension of the given dimension
3870         * type and returns the precise configuration of that dimension in this
3871         * Region.
3872         *
3873         * @param type - dimension type of the sought dimension
3874         * @returns dimension definition or NULL if there is no dimension with
3875         *          sought type in this Region.
3876         */
3877        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3878            for (int i = 0; i < Dimensions; ++i)
3879                if (pDimensionDefinitions[i].dimension == type)
3880                    return &pDimensionDefinitions[i];
3881            return NULL;
3882        }
3883    
3884      Region::~Region() {      Region::~Region() {
3885          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
3886              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
# Line 2833  namespace { Line 3908  namespace {
3908      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3909          uint8_t bits;          uint8_t bits;
3910          int veldim = -1;          int veldim = -1;
3911          int velbitpos;          int velbitpos = 0;
3912          int bitpos = 0;          int bitpos = 0;
3913          int dimregidx = 0;          int dimregidx = 0;
3914          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 2863  namespace { Line 3938  namespace {
3938              }              }
3939              bitpos += pDimensionDefinitions[i].bits;              bitpos += pDimensionDefinitions[i].bits;
3940          }          }
3941          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3942            if (!dimreg) return NULL;
3943          if (veldim != -1) {          if (veldim != -1) {
3944              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3945              if (dimreg->VelocityTable) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3946                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3947              else // normal split type              else // normal split type
3948                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3949    
3950              dimregidx |= bits << velbitpos;              const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3951              dimreg = pDimensionRegions[dimregidx];              dimregidx |= (bits & limiter_mask) << velbitpos;
3952                dimreg = pDimensionRegions[dimregidx & 255];
3953          }          }
3954          return dimreg;          return dimreg;
3955      }      }
3956    
3957        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3958            uint8_t bits;
3959            int veldim = -1;
3960            int velbitpos = 0;
3961            int bitpos = 0;
3962            int dimregidx = 0;
3963            for (uint i = 0; i < Dimensions; i++) {
3964                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3965                    // the velocity dimension must be handled after the other dimensions
3966                    veldim = i;
3967                    velbitpos = bitpos;
3968                } else {
3969                    switch (pDimensionDefinitions[i].split_type) {
3970                        case split_type_normal:
3971                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3972                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3973                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3974                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3975                                }
3976                            } else {
3977                                // gig2: evenly sized zones
3978                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3979                            }
3980                            break;
3981                        case split_type_bit: // the value is already the sought dimension bit number
3982                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3983                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3984                            break;
3985                    }
3986                    dimregidx |= bits << bitpos;
3987                }
3988                bitpos += pDimensionDefinitions[i].bits;
3989            }
3990            dimregidx &= 255;
3991            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3992            if (!dimreg) return -1;
3993            if (veldim != -1) {
3994                // (dimreg is now the dimension region for the lowest velocity)
3995                if (dimreg->VelocityTable) // custom defined zone ranges
3996                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3997                else // normal split type
3998                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3999    
4000                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
4001                dimregidx |= (bits & limiter_mask) << velbitpos;
4002                dimregidx &= 255;
4003            }
4004            return dimregidx;
4005        }
4006    
4007      /**      /**
4008       * Returns the appropriate DimensionRegion for the given dimension bit       * Returns the appropriate DimensionRegion for the given dimension bit
4009       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
# Line 2915  namespace { Line 4042  namespace {
4042          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
4043          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
4044          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
4045          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
4046          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
4047          Sample* sample = file->GetFirstSample(pProgress);              // use 64 bit wave pool offsets (treating this as large file)
4048          while (sample) {              uint64_t soughtoffset =
4049              if (sample->ulWavePoolOffset == soughtoffset &&                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
4050                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
4051              sample = file->GetNextSample();              Sample* sample = file->GetFirstSample(pProgress);
4052                while (sample) {
4053                    if (sample->ullWavePoolOffset == soughtoffset)
4054                        return static_cast<gig::Sample*>(sample);
4055                    sample = file->GetNextSample();
4056                }
4057            } else {
4058                // use extension files and 32 bit wave pool offsets
4059                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
4060                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
4061                Sample* sample = file->GetFirstSample(pProgress);
4062                while (sample) {
4063                    if (sample->ullWavePoolOffset == soughtoffset &&
4064                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
4065                    sample = file->GetNextSample();
4066                }
4067          }          }
4068          return NULL;          return NULL;
4069      }      }
4070        
4071        /**
4072         * Make a (semi) deep copy of the Region object given by @a orig
4073         * and assign it to this object.
4074         *
4075         * Note that all sample pointers referenced by @a orig are simply copied as
4076         * memory address. Thus the respective samples are shared, not duplicated!
4077         *
4078         * @param orig - original Region object to be copied from
4079         */
4080        void Region::CopyAssign(const Region* orig) {
4081            CopyAssign(orig, NULL);
4082        }
4083        
4084        /**
4085         * Make a (semi) deep copy of the Region object given by @a orig and
4086         * assign it to this object
4087         *
4088         * @param mSamples - crosslink map between the foreign file's samples and
4089         *                   this file's samples
4090         */
4091        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
4092            // handle base classes
4093            DLS::Region::CopyAssign(orig);
4094            
4095            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
4096                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
4097            }
4098            
4099            // handle own member variables
4100            for (int i = Dimensions - 1; i >= 0; --i) {
4101                DeleteDimension(&pDimensionDefinitions[i]);
4102            }
4103            Layers = 0; // just to be sure
4104            for (int i = 0; i < orig->Dimensions; i++) {
4105                // we need to copy the dim definition here, to avoid the compiler
4106                // complaining about const-ness issue
4107                dimension_def_t def = orig->pDimensionDefinitions[i];
4108                AddDimension(&def);
4109            }
4110            for (int i = 0; i < 256; i++) {
4111                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
4112                    pDimensionRegions[i]->CopyAssign(
4113                        orig->pDimensionRegions[i],
4114                        mSamples
4115                    );
4116                }
4117            }
4118            Layers = orig->Layers;
4119        }
4120    
4121    
4122  // *************** MidiRule ***************  // *************** MidiRule ***************
4123  // *  // *
4124    
4125  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {      MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
4126      _3ewg->SetPos(36);          _3ewg->SetPos(36);
4127      Triggers = _3ewg->ReadUint8();          Triggers = _3ewg->ReadUint8();
4128      _3ewg->SetPos(40);          _3ewg->SetPos(40);
4129      ControllerNumber = _3ewg->ReadUint8();          ControllerNumber = _3ewg->ReadUint8();
4130      _3ewg->SetPos(46);          _3ewg->SetPos(46);
4131      for (int i = 0 ; i < Triggers ; i++) {          for (int i = 0 ; i < Triggers ; i++) {
4132          pTriggers[i].TriggerPoint = _3ewg->ReadUint8();              pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
4133          pTriggers[i].Descending = _3ewg->ReadUint8();              pTriggers[i].Descending = _3ewg->ReadUint8();
4134          pTriggers[i].VelSensitivity = _3ewg->ReadUint8();              pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
4135          pTriggers[i].Key = _3ewg->ReadUint8();              pTriggers[i].Key = _3ewg->ReadUint8();
4136          pTriggers[i].NoteOff = _3ewg->ReadUint8();              pTriggers[i].NoteOff = _3ewg->ReadUint8();
4137          pTriggers[i].Velocity = _3ewg->ReadUint8();              pTriggers[i].Velocity = _3ewg->ReadUint8();
4138          pTriggers[i].OverridePedal = _3ewg->ReadUint8();              pTriggers[i].OverridePedal = _3ewg->ReadUint8();
4139          _3ewg->ReadUint8();              _3ewg->ReadUint8();
4140            }
4141        }
4142    
4143        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
4144            ControllerNumber(0),
4145            Triggers(0) {
4146        }
4147    
4148        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
4149            pData[32] = 4;
4150            pData[33] = 16;
4151            pData[36] = Triggers;
4152            pData[40] = ControllerNumber;
4153            for (int i = 0 ; i < Triggers ; i++) {
4154                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
4155                pData[47 + i * 8] = pTriggers[i].Descending;
4156                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
4157                pData[49 + i * 8] = pTriggers[i].Key;
4158                pData[50 + i * 8] = pTriggers[i].NoteOff;
4159                pData[51 + i * 8] = pTriggers[i].Velocity;
4160                pData[52 + i * 8] = pTriggers[i].OverridePedal;
4161            }
4162        }
4163    
4164        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
4165            _3ewg->SetPos(36);
4166            LegatoSamples = _3ewg->ReadUint8(); // always 12
4167            _3ewg->SetPos(40);
4168            BypassUseController = _3ewg->ReadUint8();
4169            BypassKey = _3ewg->ReadUint8();
4170            BypassController = _3ewg->ReadUint8();
4171            ThresholdTime = _3ewg->ReadUint16();
4172            _3ewg->ReadInt16();
4173            ReleaseTime = _3ewg->ReadUint16();
4174            _3ewg->ReadInt16();
4175            KeyRange.low = _3ewg->ReadUint8();
4176            KeyRange.high = _3ewg->ReadUint8();
4177            _3ewg->SetPos(64);
4178            ReleaseTriggerKey = _3ewg->ReadUint8();
4179            AltSustain1Key = _3ewg->ReadUint8();
4180            AltSustain2Key = _3ewg->ReadUint8();
4181        }
4182    
4183        MidiRuleLegato::MidiRuleLegato() :
4184            LegatoSamples(12),
4185            BypassUseController(false),
4186            BypassKey(0),
4187            BypassController(1),
4188            ThresholdTime(20),
4189            ReleaseTime(20),
4190            ReleaseTriggerKey(0),
4191            AltSustain1Key(0),
4192            AltSustain2Key(0)
4193        {
4194            KeyRange.low = KeyRange.high = 0;
4195        }
4196    
4197        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
4198            pData[32] = 0;
4199            pData[33] = 16;
4200            pData[36] = LegatoSamples;
4201            pData[40] = BypassUseController;
4202            pData[41] = BypassKey;
4203            pData[42] = BypassController;
4204            store16(&pData[43], ThresholdTime);
4205            store16(&pData[47], ReleaseTime);
4206            pData[51] = KeyRange.low;
4207            pData[52] = KeyRange.high;
4208            pData[64] = ReleaseTriggerKey;
4209            pData[65] = AltSustain1Key;
4210            pData[66] = AltSustain2Key;
4211        }
4212    
4213        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4214            _3ewg->SetPos(36);
4215            Articulations = _3ewg->ReadUint8();
4216            int flags = _3ewg->ReadUint8();
4217            Polyphonic = flags & 8;
4218            Chained = flags & 4;
4219            Selector = (flags & 2) ? selector_controller :
4220                (flags & 1) ? selector_key_switch : selector_none;
4221            Patterns = _3ewg->ReadUint8();
4222            _3ewg->ReadUint8(); // chosen row
4223            _3ewg->ReadUint8(); // unknown
4224            _3ewg->ReadUint8(); // unknown
4225            _3ewg->ReadUint8(); // unknown
4226            KeySwitchRange.low = _3ewg->ReadUint8();
4227            KeySwitchRange.high = _3ewg->ReadUint8();
4228            Controller = _3ewg->ReadUint8();
4229            PlayRange.low = _3ewg->ReadUint8();
4230            PlayRange.high = _3ewg->ReadUint8();
4231    
4232            int n = std::min(int(Articulations), 32);
4233            for (int i = 0 ; i < n ; i++) {
4234                _3ewg->ReadString(pArticulations[i], 32);
4235            }
4236            _3ewg->SetPos(1072);
4237            n = std::min(int(Patterns), 32);
4238            for (int i = 0 ; i < n ; i++) {
4239                _3ewg->ReadString(pPatterns[i].Name, 16);
4240                pPatterns[i].Size = _3ewg->ReadUint8();
4241                _3ewg->Read(&pPatterns[i][0], 1, 32);
4242            }
4243        }
4244    
4245        MidiRuleAlternator::MidiRuleAlternator() :
4246            Articulations(0),
4247            Patterns(0),
4248            Selector(selector_none),
4249            Controller(0),
4250            Polyphonic(false),
4251            Chained(false)
4252        {
4253            PlayRange.low = PlayRange.high = 0;
4254            KeySwitchRange.low = KeySwitchRange.high = 0;
4255        }
4256    
4257        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4258            pData[32] = 3;
4259            pData[33] = 16;
4260            pData[36] = Articulations;
4261            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4262                (Selector == selector_controller ? 2 :
4263                 (Selector == selector_key_switch ? 1 : 0));
4264            pData[38] = Patterns;
4265    
4266            pData[43] = KeySwitchRange.low;
4267            pData[44] = KeySwitchRange.high;
4268            pData[45] = Controller;
4269            pData[46] = PlayRange.low;
4270            pData[47] = PlayRange.high;
4271    
4272            char* str = reinterpret_cast<char*>(pData);
4273            int pos = 48;
4274            int n = std::min(int(Articulations), 32);
4275            for (int i = 0 ; i < n ; i++, pos += 32) {
4276                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4277            }
4278    
4279            pos = 1072;
4280            n = std::min(int(Patterns), 32);
4281            for (int i = 0 ; i < n ; i++, pos += 49) {
4282                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4283                pData[pos + 16] = pPatterns[i].Size;
4284                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4285            }
4286        }
4287    
4288    // *************** Script ***************
4289    // *
4290    
4291        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4292            pGroup = group;
4293            pChunk = ckScri;
4294            if (ckScri) { // object is loaded from file ...
4295                // read header
4296                uint32_t headerSize = ckScri->ReadUint32();
4297                Compression = (Compression_t) ckScri->ReadUint32();
4298                Encoding    = (Encoding_t) ckScri->ReadUint32();
4299                Language    = (Language_t) ckScri->ReadUint32();
4300                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4301                crc         = ckScri->ReadUint32();
4302                uint32_t nameSize = ckScri->ReadUint32();
4303                Name.resize(nameSize, ' ');
4304                for (int i = 0; i < nameSize; ++i)
4305                    Name[i] = ckScri->ReadUint8();
4306                // to handle potential future extensions of the header
4307                ckScri->SetPos(sizeof(int32_t) + headerSize);
4308                // read actual script data
4309                uint32_t scriptSize = uint32_t(ckScri->GetSize() - ckScri->GetPos());
4310                data.resize(scriptSize);
4311                for (int i = 0; i < scriptSize; ++i)
4312                    data[i] = ckScri->ReadUint8();
4313            } else { // this is a new script object, so just initialize it as such ...
4314                Compression = COMPRESSION_NONE;
4315                Encoding = ENCODING_ASCII;
4316                Language = LANGUAGE_NKSP;
4317                Bypass   = false;
4318                crc      = 0;
4319                Name     = "Unnamed Script";
4320            }
4321        }
4322    
4323        Script::~Script() {
4324        }
4325    
4326        /**
4327         * Returns the current script (i.e. as source code) in text format.
4328         */
4329        String Script::GetScriptAsText() {
4330            String s;
4331            s.resize(data.size(), ' ');
4332            memcpy(&s[0], &data[0], data.size());
4333            return s;
4334        }
4335    
4336        /**
4337         * Replaces the current script with the new script source code text given
4338         * by @a text.
4339         *
4340         * @param text - new script source code
4341         */
4342        void Script::SetScriptAsText(const String& text) {
4343            data.resize(text.size());
4344            memcpy(&data[0], &text[0], text.size());
4345        }
4346    
4347        /**
4348         * Apply this script to the respective RIFF chunks. You have to call
4349         * File::Save() to make changes persistent.
4350         *
4351         * Usually there is absolutely no need to call this method explicitly.
4352         * It will be called automatically when File::Save() was called.
4353         *
4354         * @param pProgress - callback function for progress notification
4355         */
4356        void Script::UpdateChunks(progress_t* pProgress) {
4357            // recalculate CRC32 check sum
4358            __resetCRC(crc);
4359            __calculateCRC(&data[0], data.size(), crc);
4360            __finalizeCRC(crc);
4361            // make sure chunk exists and has the required size
4362            const file_offset_t chunkSize = (file_offset_t) 7*sizeof(int32_t) + Name.size() + data.size();
4363            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4364            else pChunk->Resize(chunkSize);
4365            // fill the chunk data to be written to disk
4366            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4367            int pos = 0;
4368            store32(&pData[pos], uint32_t(6*sizeof(int32_t) + Name.size())); // total header size
4369            pos += sizeof(int32_t);
4370            store32(&pData[pos], Compression);
4371            pos += sizeof(int32_t);
4372            store32(&pData[pos], Encoding);
4373            pos += sizeof(int32_t);
4374            store32(&pData[pos], Language);
4375            pos += sizeof(int32_t);
4376            store32(&pData[pos], Bypass ? 1 : 0);
4377            pos += sizeof(int32_t);
4378            store32(&pData[pos], crc);
4379            pos += sizeof(int32_t);
4380            store32(&pData[pos], (uint32_t) Name.size());
4381            pos += sizeof(int32_t);
4382            for (int i = 0; i < Name.size(); ++i, ++pos)
4383                pData[pos] = Name[i];
4384            for (int i = 0; i < data.size(); ++i, ++pos)
4385                pData[pos] = data[i];
4386        }
4387    
4388        /**
4389         * Move this script from its current ScriptGroup to another ScriptGroup
4390         * given by @a pGroup.
4391         *
4392         * @param pGroup - script's new group
4393         */
4394        void Script::SetGroup(ScriptGroup* pGroup) {
4395            if (this->pGroup == pGroup) return;
4396            if (pChunk)
4397                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4398            this->pGroup = pGroup;
4399        }
4400    
4401        /**
4402         * Returns the script group this script currently belongs to. Each script
4403         * is a member of exactly one ScriptGroup.
4404         *
4405         * @returns current script group
4406         */
4407        ScriptGroup* Script::GetGroup() const {
4408            return pGroup;
4409        }
4410    
4411        /**
4412         * Make a (semi) deep copy of the Script object given by @a orig
4413         * and assign it to this object. Note: the ScriptGroup this Script
4414         * object belongs to remains untouched by this call.
4415         *
4416         * @param orig - original Script object to be copied from
4417         */
4418        void Script::CopyAssign(const Script* orig) {
4419            Name        = orig->Name;
4420            Compression = orig->Compression;
4421            Encoding    = orig->Encoding;
4422            Language    = orig->Language;
4423            Bypass      = orig->Bypass;
4424            data        = orig->data;
4425        }
4426    
4427        void Script::RemoveAllScriptReferences() {
4428            File* pFile = pGroup->pFile;
4429            for (int i = 0; pFile->GetInstrument(i); ++i) {
4430                Instrument* instr = pFile->GetInstrument(i);
4431                instr->RemoveScript(this);
4432            }
4433        }
4434    
4435    // *************** ScriptGroup ***************
4436    // *
4437    
4438        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4439            pFile = file;
4440            pList = lstRTIS;
4441            pScripts = NULL;
4442            if (lstRTIS) {
4443                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4444                ::LoadString(ckName, Name);
4445            } else {
4446                Name = "Default Group";
4447            }
4448        }
4449    
4450        ScriptGroup::~ScriptGroup() {
4451            if (pScripts) {
4452                std::list<Script*>::iterator iter = pScripts->begin();
4453                std::list<Script*>::iterator end  = pScripts->end();
4454                while (iter != end) {
4455                    delete *iter;
4456                    ++iter;
4457                }
4458                delete pScripts;
4459            }
4460        }
4461    
4462        /**
4463         * Apply this script group to the respective RIFF chunks. You have to call
4464         * File::Save() to make changes persistent.
4465         *
4466         * Usually there is absolutely no need to call this method explicitly.
4467         * It will be called automatically when File::Save() was called.
4468         *
4469         * @param pProgress - callback function for progress notification
4470         */
4471        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4472            if (pScripts) {
4473                if (!pList)
4474                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4475    
4476                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4477                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4478    
4479                for (std::list<Script*>::iterator it = pScripts->begin();
4480                     it != pScripts->end(); ++it)
4481                {
4482                    (*it)->UpdateChunks(pProgress);
4483                }
4484            }
4485        }
4486    
4487        /** @brief Get instrument script.
4488         *
4489         * Returns the real-time instrument script with the given index.
4490         *
4491         * @param index - number of the sought script (0..n)
4492         * @returns sought script or NULL if there's no such script
4493         */
4494        Script* ScriptGroup::GetScript(uint index) {
4495            if (!pScripts) LoadScripts();
4496            std::list<Script*>::iterator it = pScripts->begin();
4497            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4498                if (i == index) return *it;
4499            return NULL;
4500        }
4501    
4502        /** @brief Add new instrument script.
4503         *
4504         * Adds a new real-time instrument script to the file. The script is not
4505         * actually used / executed unless it is referenced by an instrument to be
4506         * used. This is similar to samples, which you can add to a file, without
4507         * an instrument necessarily actually using it.
4508         *
4509         * You have to call Save() to make this persistent to the file.
4510         *
4511         * @return new empty script object
4512         */
4513        Script* ScriptGroup::AddScript() {
4514            if (!pScripts) LoadScripts();
4515            Script* pScript = new Script(this, NULL);
4516            pScripts->push_back(pScript);
4517            return pScript;
4518      }      }
 }  
4519    
4520        /** @brief Delete an instrument script.
4521         *
4522         * This will delete the given real-time instrument script. References of
4523         * instruments that are using that script will be removed accordingly.
4524         *
4525         * You have to call Save() to make this persistent to the file.
4526         *
4527         * @param pScript - script to delete
4528         * @throws gig::Exception if given script could not be found
4529         */
4530        void ScriptGroup::DeleteScript(Script* pScript) {
4531            if (!pScripts) LoadScripts();
4532            std::list<Script*>::iterator iter =
4533                find(pScripts->begin(), pScripts->end(), pScript);
4534            if (iter == pScripts->end())
4535                throw gig::Exception("Could not delete script, could not find given script");
4536            pScripts->erase(iter);
4537            pScript->RemoveAllScriptReferences();
4538            if (pScript->pChunk)
4539                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4540            delete pScript;
4541        }
4542    
4543        void ScriptGroup::LoadScripts() {
4544            if (pScripts) return;
4545            pScripts = new std::list<Script*>;
4546            if (!pList) return;
4547    
4548            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4549                 ck = pList->GetNextSubChunk())
4550            {
4551                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4552                    pScripts->push_back(new Script(this, ck));
4553                }
4554            }
4555        }
4556    
4557  // *************** Instrument ***************  // *************** Instrument ***************
4558  // *  // *
# Line 2965  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4570  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4570          EffectSend = 0;          EffectSend = 0;
4571          Attenuation = 0;          Attenuation = 0;
4572          FineTune = 0;          FineTune = 0;
4573          PitchbendRange = 0;          PitchbendRange = 2;
4574          PianoReleaseMode = false;          PianoReleaseMode = false;
4575          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
4576          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
4577          pMidiRules = new MidiRule*[3];          pMidiRules = new MidiRule*[3];
4578          pMidiRules[0] = NULL;          pMidiRules[0] = NULL;
4579            pScriptRefs = NULL;
4580    
4581          // Loading          // Loading
4582          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2993  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4599  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4599                      uint8_t id1 = _3ewg->ReadUint8();                      uint8_t id1 = _3ewg->ReadUint8();
4600                      uint8_t id2 = _3ewg->ReadUint8();                      uint8_t id2 = _3ewg->ReadUint8();
4601    
4602                      if (id1 == 4 && id2 == 16) {                      if (id2 == 16) {
4603                          pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);                          if (id1 == 4) {
4604                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4605                            } else if (id1 == 0) {
4606                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4607                            } else if (id1 == 3) {
4608                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4609                            } else {
4610                                pMidiRules[i++] = new MidiRuleUnknown;
4611                            }
4612                        }
4613                        else if (id1 != 0 || id2 != 0) {
4614                            pMidiRules[i++] = new MidiRuleUnknown;
4615                      }                      }
4616                      //TODO: all the other types of rules                      //TODO: all the other types of rules
4617    
# Line 3020  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4637  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4637              }              }
4638          }          }
4639    
4640            // own gig format extensions
4641            RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4642            if (lst3LS) {
4643                RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4644                if (ckSCSL) {
4645                    int headerSize = ckSCSL->ReadUint32();
4646                    int slotCount  = ckSCSL->ReadUint32();
4647                    if (slotCount) {
4648                        int slotSize  = ckSCSL->ReadUint32();
4649                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4650                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4651                        for (int i = 0; i < slotCount; ++i) {
4652                            _ScriptPooolEntry e;
4653                            e.fileOffset = ckSCSL->ReadUint32();
4654                            e.bypass     = ckSCSL->ReadUint32() & 1;
4655                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4656                            scriptPoolFileOffsets.push_back(e);
4657                        }
4658                    }
4659                }
4660            }
4661    
4662          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4663      }      }
4664    
# Line 3036  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4675  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4675      }      }
4676    
4677      Instrument::~Instrument() {      Instrument::~Instrument() {
4678            for (int i = 0 ; pMidiRules[i] ; i++) {
4679                delete pMidiRules[i];
4680            }
4681          delete[] pMidiRules;          delete[] pMidiRules;
4682            if (pScriptRefs) delete pScriptRefs;
4683      }      }
4684    
4685      /**      /**
# Line 3046  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4689  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4689       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
4690       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
4691       *       *
4692         * @param pProgress - callback function for progress notification
4693       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
4694       */       */
4695      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
4696          // first update base classes' chunks          // first update base classes' chunks
4697          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks(pProgress);
4698    
4699          // update Regions' chunks          // update Regions' chunks
4700          {          {
4701              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
4702              RegionList::iterator end  = pRegions->end();              RegionList::iterator end  = pRegions->end();
4703              for (; iter != end; ++iter)              for (; iter != end; ++iter)
4704                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
4705          }          }
4706    
4707          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
# Line 3083  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4727  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4727                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
4728          pData[10] = dimkeystart;          pData[10] = dimkeystart;
4729          pData[11] = DimensionKeyRange.high;          pData[11] = DimensionKeyRange.high;
4730    
4731            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4732                pData[32] = 0;
4733                pData[33] = 0;
4734            } else {
4735                for (int i = 0 ; pMidiRules[i] ; i++) {
4736                    pMidiRules[i]->UpdateChunks(pData);
4737                }
4738            }
4739    
4740            // own gig format extensions
4741           if (ScriptSlotCount()) {
4742               // make sure we have converted the original loaded script file
4743               // offsets into valid Script object pointers
4744               LoadScripts();
4745    
4746               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4747               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4748               const int slotCount = (int) pScriptRefs->size();
4749               const int headerSize = 3 * sizeof(uint32_t);
4750               const int slotSize  = 2 * sizeof(uint32_t);
4751               const int totalChunkSize = headerSize + slotCount * slotSize;
4752               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4753               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4754               else ckSCSL->Resize(totalChunkSize);
4755               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4756               int pos = 0;
4757               store32(&pData[pos], headerSize);
4758               pos += sizeof(uint32_t);
4759               store32(&pData[pos], slotCount);
4760               pos += sizeof(uint32_t);
4761               store32(&pData[pos], slotSize);
4762               pos += sizeof(uint32_t);
4763               for (int i = 0; i < slotCount; ++i) {
4764                   // arbitrary value, the actual file offset will be updated in
4765                   // UpdateScriptFileOffsets() after the file has been resized
4766                   int bogusFileOffset = 0;
4767                   store32(&pData[pos], bogusFileOffset);
4768                   pos += sizeof(uint32_t);
4769                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4770                   pos += sizeof(uint32_t);
4771               }
4772           } else {
4773               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4774               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4775               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4776           }
4777        }
4778    
4779        void Instrument::UpdateScriptFileOffsets() {
4780           // own gig format extensions
4781           if (pScriptRefs && pScriptRefs->size() > 0) {
4782               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4783               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4784               const int slotCount = (int) pScriptRefs->size();
4785               const int headerSize = 3 * sizeof(uint32_t);
4786               ckSCSL->SetPos(headerSize);
4787               for (int i = 0; i < slotCount; ++i) {
4788                   uint32_t fileOffset = uint32_t(
4789                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4790                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4791                        CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize())
4792                   );
4793                   ckSCSL->WriteUint32(&fileOffset);
4794                   // jump over flags entry (containing the bypass flag)
4795                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4796               }
4797           }        
4798      }      }
4799    
4800      /**      /**
# Line 3137  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4849  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4849          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4850          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
4851          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
4852          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
4853          // update Region key table for fast lookup          // update Region key table for fast lookup
4854          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4855          // done          // done
# Line 3152  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4864  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4864      }      }
4865    
4866      /**      /**
4867         * Move this instrument at the position before @arg dst.
4868         *
4869         * This method can be used to reorder the sequence of instruments in a
4870         * .gig file. This might be helpful especially on large .gig files which
4871         * contain a large number of instruments within the same .gig file. So
4872         * grouping such instruments to similar ones, can help to keep track of them
4873         * when working with such complex .gig files.
4874         *
4875         * When calling this method, this instrument will be removed from in its
4876         * current position in the instruments list and moved to the requested
4877         * target position provided by @param dst. You may also pass NULL as
4878         * argument to this method, in that case this intrument will be moved to the
4879         * very end of the .gig file's instrument list.
4880         *
4881         * You have to call Save() to make the order change persistent to the .gig
4882         * file.
4883         *
4884         * Currently this method is limited to moving the instrument within the same
4885         * .gig file. Trying to move it to another .gig file by calling this method
4886         * will throw an exception.
4887         *
4888         * @param dst - destination instrument at which this instrument will be
4889         *              moved to, or pass NULL for moving to end of list
4890         * @throw gig::Exception if this instrument and target instrument are not
4891         *                       part of the same file
4892         */
4893        void Instrument::MoveTo(Instrument* dst) {
4894            if (dst && GetParent() != dst->GetParent())
4895                throw Exception(
4896                    "gig::Instrument::MoveTo() can only be used for moving within "
4897                    "the same gig file."
4898                );
4899    
4900            File* pFile = (File*) GetParent();
4901    
4902            // move this instrument within the instrument list
4903            {
4904                File::InstrumentList& list = *pFile->pInstruments;
4905    
4906                File::InstrumentList::iterator itFrom =
4907                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4908    
4909                File::InstrumentList::iterator itTo =
4910                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4911    
4912                list.splice(itTo, list, itFrom);
4913            }
4914    
4915            // move the instrument's actual list RIFF chunk appropriately
4916            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4917            lstCkInstruments->MoveSubChunk(
4918                this->pCkInstrument,
4919                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4920            );
4921        }
4922    
4923        /**
4924       * Returns a MIDI rule of the instrument.       * Returns a MIDI rule of the instrument.
4925       *       *
4926       * 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 4934  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4934          return pMidiRules[i];          return pMidiRules[i];
4935      }      }
4936    
4937        /**
4938         * Adds the "controller trigger" MIDI rule to the instrument.
4939         *
4940         * @returns the new MIDI rule
4941         */
4942        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4943            delete pMidiRules[0];
4944            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4945            pMidiRules[0] = r;
4946            pMidiRules[1] = 0;
4947            return r;
4948        }
4949    
4950        /**
4951         * Adds the legato MIDI rule to the instrument.
4952         *
4953         * @returns the new MIDI rule
4954         */
4955        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4956            delete pMidiRules[0];
4957            MidiRuleLegato* r = new MidiRuleLegato;
4958            pMidiRules[0] = r;
4959            pMidiRules[1] = 0;
4960            return r;
4961        }
4962    
4963        /**
4964         * Adds the alternator MIDI rule to the instrument.
4965         *
4966         * @returns the new MIDI rule
4967         */
4968        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4969            delete pMidiRules[0];
4970            MidiRuleAlternator* r = new MidiRuleAlternator;
4971            pMidiRules[0] = r;
4972            pMidiRules[1] = 0;
4973            return r;
4974        }
4975    
4976        /**
4977         * Deletes a MIDI rule from the instrument.
4978         *
4979         * @param i - MIDI rule number
4980         */
4981        void Instrument::DeleteMidiRule(int i) {
4982            delete pMidiRules[i];
4983            pMidiRules[i] = 0;
4984        }
4985    
4986        void Instrument::LoadScripts() {
4987            if (pScriptRefs) return;
4988            pScriptRefs = new std::vector<_ScriptPooolRef>;
4989            if (scriptPoolFileOffsets.empty()) return;
4990            File* pFile = (File*) GetParent();
4991            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4992                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4993                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4994                    ScriptGroup* group = pFile->GetScriptGroup(i);
4995                    for (uint s = 0; group->GetScript(s); ++s) {
4996                        Script* script = group->GetScript(s);
4997                        if (script->pChunk) {
4998                            uint32_t offset = uint32_t(
4999                                script->pChunk->GetFilePos() -
5000                                script->pChunk->GetPos() -
5001                                CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize())
5002                            );
5003                            if (offset == soughtOffset)
5004                            {
5005                                _ScriptPooolRef ref;
5006                                ref.script = script;
5007                                ref.bypass = scriptPoolFileOffsets[k].bypass;
5008                                pScriptRefs->push_back(ref);
5009                                break;
5010                            }
5011                        }
5012                    }
5013                }
5014            }
5015            // we don't need that anymore
5016            scriptPoolFileOffsets.clear();
5017        }
5018    
5019        /** @brief Get instrument script (gig format extension).
5020         *
5021         * Returns the real-time instrument script of instrument script slot
5022         * @a index.
5023         *
5024         * @note This is an own format extension which did not exist i.e. in the
5025         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5026         * gigedit.
5027         *
5028         * @param index - instrument script slot index
5029         * @returns script or NULL if index is out of bounds
5030         */
5031        Script* Instrument::GetScriptOfSlot(uint index) {
5032            LoadScripts();
5033            if (index >= pScriptRefs->size()) return NULL;
5034            return pScriptRefs->at(index).script;
5035        }
5036    
5037        /** @brief Add new instrument script slot (gig format extension).
5038         *
5039         * Add the given real-time instrument script reference to this instrument,
5040         * which shall be executed by the sampler for for this instrument. The
5041         * script will be added to the end of the script list of this instrument.
5042         * The positions of the scripts in the Instrument's Script list are
5043         * relevant, because they define in which order they shall be executed by
5044         * the sampler. For this reason it is also legal to add the same script
5045         * twice to an instrument, for example you might have a script called
5046         * "MyFilter" which performs an event filter task, and you might have
5047         * another script called "MyNoteTrigger" which triggers new notes, then you
5048         * might for example have the following list of scripts on the instrument:
5049         *
5050         * 1. Script "MyFilter"
5051         * 2. Script "MyNoteTrigger"
5052         * 3. Script "MyFilter"
5053         *
5054         * Which would make sense, because the 2nd script launched new events, which
5055         * you might need to filter as well.
5056         *
5057         * There are two ways to disable / "bypass" scripts. You can either disable
5058         * a script locally for the respective script slot on an instrument (i.e. by
5059         * passing @c false to the 2nd argument of this method, or by calling
5060         * SetScriptBypassed()). Or you can disable a script globally for all slots
5061         * and all instruments by setting Script::Bypass.
5062         *
5063         * @note This is an own format extension which did not exist i.e. in the
5064         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5065         * gigedit.
5066         *
5067         * @param pScript - script that shall be executed for this instrument
5068         * @param bypass  - if enabled, the sampler shall skip executing this
5069         *                  script (in the respective list position)
5070         * @see SetScriptBypassed()
5071         */
5072        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
5073            LoadScripts();
5074            _ScriptPooolRef ref = { pScript, bypass };
5075            pScriptRefs->push_back(ref);
5076        }
5077    
5078        /** @brief Flip two script slots with each other (gig format extension).
5079         *
5080         * Swaps the position of the two given scripts in the Instrument's Script
5081         * list. The positions of the scripts in the Instrument's Script list are
5082         * relevant, because they define in which order they shall be executed by
5083         * the sampler.
5084         *
5085         * @note This is an own format extension which did not exist i.e. in the
5086         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5087         * gigedit.
5088         *
5089         * @param index1 - index of the first script slot to swap
5090         * @param index2 - index of the second script slot to swap
5091         */
5092        void Instrument::SwapScriptSlots(uint index1, uint index2) {
5093            LoadScripts();
5094            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
5095                return;
5096            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
5097            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
5098            (*pScriptRefs)[index2] = tmp;
5099        }
5100    
5101        /** @brief Remove script slot.
5102         *
5103         * Removes the script slot with the given slot index.
5104         *
5105         * @param index - index of script slot to remove
5106         */
5107        void Instrument::RemoveScriptSlot(uint index) {
5108            LoadScripts();
5109            if (index >= pScriptRefs->size()) return;
5110            pScriptRefs->erase( pScriptRefs->begin() + index );
5111        }
5112    
5113        /** @brief Remove reference to given Script (gig format extension).
5114         *
5115         * This will remove all script slots on the instrument which are referencing
5116         * the given script.
5117         *
5118         * @note This is an own format extension which did not exist i.e. in the
5119         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5120         * gigedit.
5121         *
5122         * @param pScript - script reference to remove from this instrument
5123         * @see RemoveScriptSlot()
5124         */
5125        void Instrument::RemoveScript(Script* pScript) {
5126            LoadScripts();
5127            for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5128                if ((*pScriptRefs)[i].script == pScript) {
5129                    pScriptRefs->erase( pScriptRefs->begin() + i );
5130                }
5131            }
5132        }
5133    
5134        /** @brief Instrument's amount of script slots.
5135         *
5136         * This method returns the amount of script slots this instrument currently
5137         * uses.
5138         *
5139         * A script slot is a reference of a real-time instrument script to be
5140         * executed by the sampler. The scripts will be executed by the sampler in
5141         * sequence of the slots. One (same) script may be referenced multiple
5142         * times in different slots.
5143         *
5144         * @note This is an own format extension which did not exist i.e. in the
5145         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5146         * gigedit.
5147         */
5148        uint Instrument::ScriptSlotCount() const {
5149            return uint(pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size());
5150        }
5151    
5152        /** @brief Whether script execution shall be skipped.
5153         *
5154         * Defines locally for the Script reference slot in the Instrument's Script
5155         * list, whether the script shall be skipped by the sampler regarding
5156         * execution.
5157         *
5158         * It is also possible to ignore exeuction of the script globally, for all
5159         * slots and for all instruments by setting Script::Bypass.
5160         *
5161         * @note This is an own format extension which did not exist i.e. in the
5162         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5163         * gigedit.
5164         *
5165         * @param index - index of the script slot on this instrument
5166         * @see Script::Bypass
5167         */
5168        bool Instrument::IsScriptSlotBypassed(uint index) {
5169            if (index >= ScriptSlotCount()) return false;
5170            return pScriptRefs ? pScriptRefs->at(index).bypass
5171                               : scriptPoolFileOffsets.at(index).bypass;
5172            
5173        }
5174    
5175        /** @brief Defines whether execution shall be skipped.
5176         *
5177         * You can call this method to define locally whether or whether not the
5178         * given script slot shall be executed by the sampler.
5179         *
5180         * @note This is an own format extension which did not exist i.e. in the
5181         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5182         * gigedit.
5183         *
5184         * @param index - script slot index on this instrument
5185         * @param bBypass - if true, the script slot will be skipped by the sampler
5186         * @see Script::Bypass
5187         */
5188        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
5189            if (index >= ScriptSlotCount()) return;
5190            if (pScriptRefs)
5191                pScriptRefs->at(index).bypass = bBypass;
5192            else
5193                scriptPoolFileOffsets.at(index).bypass = bBypass;
5194        }
5195    
5196        /**
5197         * Make a (semi) deep copy of the Instrument object given by @a orig
5198         * and assign it to this object.
5199         *
5200         * Note that all sample pointers referenced by @a orig are simply copied as
5201         * memory address. Thus the respective samples are shared, not duplicated!
5202         *
5203         * @param orig - original Instrument object to be copied from
5204         */
5205        void Instrument::CopyAssign(const Instrument* orig) {
5206            CopyAssign(orig, NULL);
5207        }
5208            
5209        /**
5210         * Make a (semi) deep copy of the Instrument object given by @a orig
5211         * and assign it to this object.
5212         *
5213         * @param orig - original Instrument object to be copied from
5214         * @param mSamples - crosslink map between the foreign file's samples and
5215         *                   this file's samples
5216         */
5217        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
5218            // handle base class
5219            // (without copying DLS region stuff)
5220            DLS::Instrument::CopyAssignCore(orig);
5221            
5222            // handle own member variables
5223            Attenuation = orig->Attenuation;
5224            EffectSend = orig->EffectSend;
5225            FineTune = orig->FineTune;
5226            PitchbendRange = orig->PitchbendRange;
5227            PianoReleaseMode = orig->PianoReleaseMode;
5228            DimensionKeyRange = orig->DimensionKeyRange;
5229            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5230            pScriptRefs = orig->pScriptRefs;
5231            
5232            // free old midi rules
5233            for (int i = 0 ; pMidiRules[i] ; i++) {
5234                delete pMidiRules[i];
5235            }
5236            //TODO: MIDI rule copying
5237            pMidiRules[0] = NULL;
5238            
5239            // delete all old regions
5240            while (Regions) DeleteRegion(GetFirstRegion());
5241            // create new regions and copy them from original
5242            {
5243                RegionList::const_iterator it = orig->pRegions->begin();
5244                for (int i = 0; i < orig->Regions; ++i, ++it) {
5245                    Region* dstRgn = AddRegion();
5246                    //NOTE: Region does semi-deep copy !
5247                    dstRgn->CopyAssign(
5248                        static_cast<gig::Region*>(*it),
5249                        mSamples
5250                    );
5251                }
5252            }
5253    
5254            UpdateRegionKeyTable();
5255        }
5256    
5257    
5258  // *************** Group ***************  // *************** Group ***************
5259  // *  // *
# Line 3193  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5282  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5282       *       *
5283       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
5284       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
5285         *
5286         * @param pProgress - callback function for progress notification
5287       */       */
5288      void Group::UpdateChunks() {      void Group::UpdateChunks(progress_t* pProgress) {
5289          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
5290          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5291          if (!_3gri) {          if (!_3gri) {
# Line 3324  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5415  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5415          bAutoLoad = true;          bAutoLoad = true;
5416          *pVersion = VERSION_3;          *pVersion = VERSION_3;
5417          pGroups = NULL;          pGroups = NULL;
5418            pScriptGroups = NULL;
5419          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5420          pInfo->ArchivalLocation = String(256, ' ');          pInfo->ArchivalLocation = String(256, ' ');
5421    
# Line 3339  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5431  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5431      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5432          bAutoLoad = true;          bAutoLoad = true;
5433          pGroups = NULL;          pGroups = NULL;
5434            pScriptGroups = NULL;
5435          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5436      }      }
5437    
# Line 3352  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5445  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5445              }              }
5446              delete pGroups;              delete pGroups;
5447          }          }
5448            if (pScriptGroups) {
5449                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5450                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5451                while (iter != end) {
5452                    delete *iter;
5453                    ++iter;
5454                }
5455                delete pScriptGroups;
5456            }
5457      }      }
5458    
5459      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 3366  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5468  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5468          SamplesIterator++;          SamplesIterator++;
5469          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5470      }      }
5471        
5472        /**
5473         * Returns Sample object of @a index.
5474         *
5475         * @returns sample object or NULL if index is out of bounds
5476         */
5477        Sample* File::GetSample(uint index) {
5478            if (!pSamples) LoadSamples();
5479            if (!pSamples) return NULL;
5480            DLS::File::SampleList::iterator it = pSamples->begin();
5481            for (int i = 0; i < index; ++i) {
5482                ++it;
5483                if (it == pSamples->end()) return NULL;
5484            }
5485            if (it == pSamples->end()) return NULL;
5486            return static_cast<gig::Sample*>( *it );
5487        }
5488    
5489      /** @brief Add a new sample.      /** @brief Add a new sample.
5490       *       *
# Line 3443  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5562  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5562          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5563    
5564          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5565            // (only for old gig files < 2 GB)
5566          int lastFileNo = 0;          int lastFileNo = 0;
5567          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5568              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5569                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5570                }
5571          }          }
5572          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5573          int nameLen = name.length();          int nameLen = (int) name.length();
5574          char suffix[6];          char suffix[6];
5575          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5576    
5577          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5578              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5579              if (wvpl) {              if (wvpl) {
5580                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5581                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5582                  while (wave) {                  while (wave) {
5583                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 3463  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5585  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5585                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5586                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5587    
5588                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5589                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5590    
5591                          iSampleIndex++;                          iSampleIndex++;
5592                      }                      }
# Line 3563  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5685  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5685         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
5686         return pInstrument;         return pInstrument;
5687      }      }
5688        
5689        /** @brief Add a duplicate of an existing instrument.
5690         *
5691         * Duplicates the instrument definition given by @a orig and adds it
5692         * to this file. This allows in an instrument editor application to
5693         * easily create variations of an instrument, which will be stored in
5694         * the same .gig file, sharing i.e. the same samples.
5695         *
5696         * Note that all sample pointers referenced by @a orig are simply copied as
5697         * memory address. Thus the respective samples are shared, not duplicated!
5698         *
5699         * You have to call Save() to make this persistent to the file.
5700         *
5701         * @param orig - original instrument to be copied
5702         * @returns duplicated copy of the given instrument
5703         */
5704        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
5705            Instrument* instr = AddInstrument();
5706            instr->CopyAssign(orig);
5707            return instr;
5708        }
5709        
5710        /** @brief Add content of another existing file.
5711         *
5712         * Duplicates the samples, groups and instruments of the original file
5713         * given by @a pFile and adds them to @c this File. In case @c this File is
5714         * a new one that you haven't saved before, then you have to call
5715         * SetFileName() before calling AddContentOf(), because this method will
5716         * automatically save this file during operation, which is required for
5717         * writing the sample waveform data by disk streaming.
5718         *
5719         * @param pFile - original file whose's content shall be copied from
5720         */
5721        void File::AddContentOf(File* pFile) {
5722            static int iCallCount = -1;
5723            iCallCount++;
5724            std::map<Group*,Group*> mGroups;
5725            std::map<Sample*,Sample*> mSamples;
5726            
5727            // clone sample groups
5728            for (int i = 0; pFile->GetGroup(i); ++i) {
5729                Group* g = AddGroup();
5730                g->Name =
5731                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5732                mGroups[pFile->GetGroup(i)] = g;
5733            }
5734            
5735            // clone samples (not waveform data here yet)
5736            for (int i = 0; pFile->GetSample(i); ++i) {
5737                Sample* s = AddSample();
5738                s->CopyAssignMeta(pFile->GetSample(i));
5739                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5740                mSamples[pFile->GetSample(i)] = s;
5741            }
5742    
5743            // clone script groups and their scripts
5744            for (int iGroup = 0; pFile->GetScriptGroup(iGroup); ++iGroup) {
5745                ScriptGroup* sg = pFile->GetScriptGroup(iGroup);
5746                ScriptGroup* dg = AddScriptGroup();
5747                dg->Name = "COPY" + ToString(iCallCount) + "_" + sg->Name;
5748                for (int iScript = 0; sg->GetScript(iScript); ++iScript) {
5749                    Script* ss = sg->GetScript(iScript);
5750                    Script* ds = dg->AddScript();
5751                    ds->CopyAssign(ss);
5752                }
5753            }
5754    
5755            //BUG: For some reason this method only works with this additional
5756            //     Save() call in between here.
5757            //
5758            // Important: The correct one of the 2 Save() methods has to be called
5759            // here, depending on whether the file is completely new or has been
5760            // saved to disk already, otherwise it will result in data corruption.
5761            if (pRIFF->IsNew())
5762                Save(GetFileName());
5763            else
5764                Save();
5765            
5766            // clone instruments
5767            // (passing the crosslink table here for the cloned samples)
5768            for (int i = 0; pFile->GetInstrument(i); ++i) {
5769                Instrument* instr = AddInstrument();
5770                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5771            }
5772            
5773            // Mandatory: file needs to be saved to disk at this point, so this
5774            // file has the correct size and data layout for writing the samples'
5775            // waveform data to disk.
5776            Save();
5777            
5778            // clone samples' waveform data
5779            // (using direct read & write disk streaming)
5780            for (int i = 0; pFile->GetSample(i); ++i) {
5781                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5782            }
5783        }
5784    
5785      /** @brief Delete an instrument.      /** @brief Delete an instrument.
5786       *       *
# Line 3618  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5836  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5836          if (!_3crc) return;          if (!_3crc) return;
5837    
5838          // get the index of the sample          // get the index of the sample
5839          int iWaveIndex = -1;          int iWaveIndex = GetWaveTableIndexOf(pSample);
         File::SampleList::iterator iter = pSamples->begin();  
         File::SampleList::iterator end  = pSamples->end();  
         for (int index = 0; iter != end; ++iter, ++index) {  
             if (*iter == pSample) {  
                 iWaveIndex = index;  
                 break;  
             }  
         }  
5840          if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");          if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
5841    
5842          // write the CRC-32 checksum to disk          // write the CRC-32 checksum to disk
5843          _3crc->SetPos(iWaveIndex * 8);          _3crc->SetPos(iWaveIndex * 8);
5844          uint32_t tmp = 1;          uint32_t one = 1;
5845          _3crc->WriteUint32(&tmp); // unknown, always 1?          _3crc->WriteUint32(&one); // always 1
5846          _3crc->WriteUint32(&crc);          _3crc->WriteUint32(&crc);
5847      }      }
5848    
5849        uint32_t File::GetSampleChecksum(Sample* pSample) {
5850            // get the index of the sample
5851            int iWaveIndex = GetWaveTableIndexOf(pSample);
5852            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5853    
5854            return GetSampleChecksumByIndex(iWaveIndex);
5855        }
5856    
5857        uint32_t File::GetSampleChecksumByIndex(int index) {
5858            if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5859    
5860            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5861            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5862            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5863            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5864    
5865            // read the CRC-32 checksum directly from disk
5866            size_t pos = index * 8;
5867            if (pos + 8 > _3crc->GetNewSize())
5868                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5869    
5870            uint32_t one = load32(&pData[pos]); // always 1
5871            if (one != 1)
5872                throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5873    
5874            return load32(&pData[pos+4]);
5875        }
5876    
5877        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5878            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5879            File::SampleList::iterator iter = pSamples->begin();
5880            File::SampleList::iterator end  = pSamples->end();
5881            for (int index = 0; iter != end; ++iter, ++index)
5882                if (*iter == pSample)
5883                    return index;
5884            return -1;
5885        }
5886    
5887        /**
5888         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5889         * the CRC32 check sums of all samples' raw wave data.
5890         *
5891         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5892         */
5893        bool File::VerifySampleChecksumTable() {
5894            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5895            if (!_3crc) return false;
5896            if (_3crc->GetNewSize() <= 0) return false;
5897            if (_3crc->GetNewSize() % 8) return false;
5898            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5899            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5900    
5901            const file_offset_t n = _3crc->GetNewSize() / 8;
5902    
5903            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5904            if (!pData) return false;
5905    
5906            for (file_offset_t i = 0; i < n; ++i) {
5907                uint32_t one = pData[i*2];
5908                if (one != 1) return false;
5909            }
5910    
5911            return true;
5912        }
5913    
5914        /**
5915         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5916         * file's checksum table with those new checksums. This might usually
5917         * just be necessary if the checksum table was damaged.
5918         *
5919         * @e IMPORTANT: The current implementation of this method only works
5920         * with files that have not been modified since it was loaded, because
5921         * it expects that no externally caused file structure changes are
5922         * required!
5923         *
5924         * Due to the expectation above, this method is currently protected
5925         * and actually only used by the command line tool "gigdump" yet.
5926         *
5927         * @returns true if Save() is required to be called after this call,
5928         *          false if no further action is required
5929         */
5930        bool File::RebuildSampleChecksumTable() {
5931            // make sure sample chunks were scanned
5932            if (!pSamples) GetFirstSample();
5933    
5934            bool bRequiresSave = false;
5935    
5936            // make sure "3CRC" chunk exists with required size
5937            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5938            if (!_3crc) {
5939                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5940                // the order of einf and 3crc is not the same in v2 and v3
5941                RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5942                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5943                bRequiresSave = true;
5944            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5945                _3crc->Resize(pSamples->size() * 8);
5946                bRequiresSave = true;
5947            }
5948    
5949            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5950                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5951                {
5952                    File::SampleList::iterator iter = pSamples->begin();
5953                    File::SampleList::iterator end  = pSamples->end();
5954                    for (; iter != end; ++iter) {
5955                        gig::Sample* pSample = (gig::Sample*) *iter;
5956                        int index = GetWaveTableIndexOf(pSample);
5957                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5958                        pData[index*2]   = 1; // always 1
5959                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5960                    }
5961                }
5962            } else { // no file structure changes necessary, so directly write to disk and we are done ...
5963                // make sure file is in write mode
5964                pRIFF->SetMode(RIFF::stream_mode_read_write);
5965                {
5966                    File::SampleList::iterator iter = pSamples->begin();
5967                    File::SampleList::iterator end  = pSamples->end();
5968                    for (; iter != end; ++iter) {
5969                        gig::Sample* pSample = (gig::Sample*) *iter;
5970                        int index = GetWaveTableIndexOf(pSample);
5971                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5972                        pSample->crc  = pSample->CalculateWaveDataChecksum();
5973                        SetSampleChecksum(pSample, pSample->crc);
5974                    }
5975                }
5976            }
5977    
5978            return bRequiresSave;
5979        }
5980    
5981      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
5982          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5983          // there must always be at least one group          // there must always be at least one group
# Line 3665  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6007  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6007          return NULL;          return NULL;
6008      }      }
6009    
6010        /**
6011         * Returns the group with the given group name.
6012         *
6013         * Note: group names don't have to be unique in the gig format! So there
6014         * can be multiple groups with the same name. This method will simply
6015         * return the first group found with the given name.
6016         *
6017         * @param name - name of the sought group
6018         * @returns sought group or NULL if there's no group with that name
6019         */
6020        Group* File::GetGroup(String name) {
6021            if (!pGroups) LoadGroups();
6022            GroupsIterator = pGroups->begin();
6023            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
6024                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
6025            return NULL;
6026        }
6027    
6028      Group* File::AddGroup() {      Group* File::AddGroup() {
6029          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
6030          // there must always be at least one group          // there must always be at least one group
# Line 3745  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6105  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6105          }          }
6106      }      }
6107    
6108        /** @brief Get instrument script group (by index).
6109         *
6110         * Returns the real-time instrument script group with the given index.
6111         *
6112         * @param index - number of the sought group (0..n)
6113         * @returns sought script group or NULL if there's no such group
6114         */
6115        ScriptGroup* File::GetScriptGroup(uint index) {
6116            if (!pScriptGroups) LoadScriptGroups();
6117            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6118            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
6119                if (i == index) return *it;
6120            return NULL;
6121        }
6122    
6123        /** @brief Get instrument script group (by name).
6124         *
6125         * Returns the first real-time instrument script group found with the given
6126         * group name. Note that group names may not necessarily be unique.
6127         *
6128         * @param name - name of the sought script group
6129         * @returns sought script group or NULL if there's no such group
6130         */
6131        ScriptGroup* File::GetScriptGroup(const String& name) {
6132            if (!pScriptGroups) LoadScriptGroups();
6133            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6134            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
6135                if ((*it)->Name == name) return *it;
6136            return NULL;
6137        }
6138    
6139        /** @brief Add new instrument script group.
6140         *
6141         * Adds a new, empty real-time instrument script group to the file.
6142         *
6143         * You have to call Save() to make this persistent to the file.
6144         *
6145         * @return new empty script group
6146         */
6147        ScriptGroup* File::AddScriptGroup() {
6148            if (!pScriptGroups) LoadScriptGroups();
6149            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
6150            pScriptGroups->push_back(pScriptGroup);
6151            return pScriptGroup;
6152        }
6153    
6154        /** @brief Delete an instrument script group.
6155         *
6156         * This will delete the given real-time instrument script group and all its
6157         * instrument scripts it contains. References inside instruments that are
6158         * using the deleted scripts will be removed from the respective instruments
6159         * accordingly.
6160         *
6161         * You have to call Save() to make this persistent to the file.
6162         *
6163         * @param pScriptGroup - script group to delete
6164         * @throws gig::Exception if given script group could not be found
6165         */
6166        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
6167            if (!pScriptGroups) LoadScriptGroups();
6168            std::list<ScriptGroup*>::iterator iter =
6169                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
6170            if (iter == pScriptGroups->end())
6171                throw gig::Exception("Could not delete script group, could not find given script group");
6172            pScriptGroups->erase(iter);
6173            for (int i = 0; pScriptGroup->GetScript(i); ++i)
6174                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
6175            if (pScriptGroup->pList)
6176                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
6177            delete pScriptGroup;
6178        }
6179    
6180        void File::LoadScriptGroups() {
6181            if (pScriptGroups) return;
6182            pScriptGroups = new std::list<ScriptGroup*>;
6183            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
6184            if (lstLS) {
6185                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
6186                     lst = lstLS->GetNextSubList())
6187                {
6188                    if (lst->GetListType() == LIST_TYPE_RTIS) {
6189                        pScriptGroups->push_back(new ScriptGroup(this, lst));
6190                    }
6191                }
6192            }
6193        }
6194    
6195      /**      /**
6196       * Apply all the gig file's current instruments, samples, groups and settings       * Apply all the gig file's current instruments, samples, groups and settings
6197       * 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 6200  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6200       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
6201       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
6202       *       *
6203         * @param pProgress - callback function for progress notification
6204       * @throws Exception - on errors       * @throws Exception - on errors
6205       */       */
6206      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
6207          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6208    
6209          b64BitWavePoolOffsets = pVersion && pVersion->major == 3;          // update own gig format extension chunks
6210            // (not part of the GigaStudio 4 format)
6211            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6212            if (!lst3LS) {
6213                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6214            }
6215            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6216            // location of <3LS > is irrelevant, however it should be located
6217            // before  the actual wave data
6218            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6219            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6220    
6221            // This must be performed before writing the chunks for instruments,
6222            // because the instruments' script slots will write the file offsets
6223            // of the respective instrument script chunk as reference.
6224            if (pScriptGroups) {
6225                // Update instrument script (group) chunks.
6226                for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6227                     it != pScriptGroups->end(); ++it)
6228                {
6229                    (*it)->UpdateChunks(pProgress);
6230                }
6231            }
6232    
6233            // in case no libgig custom format data was added, then remove the
6234            // custom "3LS " chunk again
6235            if (!lst3LS->CountSubChunks()) {
6236                pRIFF->DeleteSubChunk(lst3LS);
6237                lst3LS = NULL;
6238            }
6239    
6240          // first update base class's chunks          // first update base class's chunks
6241          DLS::File::UpdateChunks();          DLS::File::UpdateChunks(pProgress);
6242    
6243          if (newFile) {          if (newFile) {
6244              // INFO was added by Resource::UpdateChunks - make sure it              // INFO was added by Resource::UpdateChunks - make sure it
# Line 3775  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6252  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6252    
6253          // update group's chunks          // update group's chunks
6254          if (pGroups) {          if (pGroups) {
6255              std::list<Group*>::iterator iter = pGroups->begin();              // make sure '3gri' and '3gnl' list chunks exist
6256              std::list<Group*>::iterator end  = pGroups->end();              // (before updating the Group chunks)
6257              for (; iter != end; ++iter) {              RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
6258                  (*iter)->UpdateChunks();              if (!_3gri) {
6259                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
6260                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
6261              }              }
6262                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
6263                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
6264    
6265              // v3: make sure the file has 128 3gnm chunks              // v3: make sure the file has 128 3gnm chunks
6266                // (before updating the Group chunks)
6267              if (pVersion && pVersion->major == 3) {              if (pVersion && pVersion->major == 3) {
                 RIFF::List* _3gnl = pRIFF->GetSubList(LIST_TYPE_3GRI)->GetSubList(LIST_TYPE_3GNL);  
6268                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
6269                  for (int i = 0 ; i < 128 ; i++) {                  for (int i = 0 ; i < 128 ; i++) {
6270                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
6271                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
6272                  }                  }
6273              }              }
6274    
6275                std::list<Group*>::iterator iter = pGroups->begin();
6276                std::list<Group*>::iterator end  = pGroups->end();
6277                for (; iter != end; ++iter) {
6278                    (*iter)->UpdateChunks(pProgress);
6279                }
6280          }          }
6281    
6282          // update einf chunk          // update einf chunk
# Line 3808  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6295  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6295          // Note that there are several fields with unknown use. These          // Note that there are several fields with unknown use. These
6296          // are set to zero.          // are set to zero.
6297    
6298          int sublen = pSamples->size() / 8 + 49;          int sublen = int(pSamples->size() / 8 + 49);
6299          int einfSize = (Instruments + 1) * sublen;          int einfSize = (Instruments + 1) * sublen;
6300    
6301          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
# Line 3881  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6368  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6368                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6369                  // next 8 bytes unknown                  // next 8 bytes unknown
6370                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6371                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());                  store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
6372                  // next 4 bytes unknown                  // next 4 bytes unknown
6373    
6374                  totnbregions += instrument->Regions;                  totnbregions += instrument->Regions;
# Line 3899  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6386  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6386              store32(&pData[24], totnbloops);              store32(&pData[24], totnbloops);
6387              // next 8 bytes unknown              // next 8 bytes unknown
6388              // next 4 bytes unknown, not always 0              // next 4 bytes unknown, not always 0
6389              store32(&pData[40], pSamples->size());              store32(&pData[40], (uint32_t) pSamples->size());
6390              // next 4 bytes unknown              // next 4 bytes unknown
6391          }          }
6392    
6393          // update 3crc chunk          // update 3crc chunk
6394    
6395          // The 3crc chunk contains CRC-32 checksums for the          // The 3crc chunk contains CRC-32 checksums for the
6396          // samples. The actual checksum values will be filled in          // samples. When saving a gig file to disk, we first update the 3CRC
6397          // later, by Sample::Write.          // chunk here (in RAM) with the old crc values which we read from the
6398            // 3CRC chunk when we opened the file (available with gig::Sample::crc
6399            // member variable). This step is required, because samples might have
6400            // been deleted by the user since the file was opened, which in turn
6401            // changes the order of the (i.e. old) checksums within the 3crc chunk.
6402            // If a sample was conciously modified by the user (that is if
6403            // Sample::Write() was called later on) then Sample::Write() will just
6404            // update the respective individual checksum(s) directly on disk and
6405            // leaves all other sample checksums untouched.
6406    
6407          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6408          if (_3crc) {          if (_3crc) {
6409              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
6410          } else if (newFile) {          } else /*if (newFile)*/ {
6411              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
             _3crc->LoadChunkData();  
   
6412              // the order of einf and 3crc is not the same in v2 and v3              // the order of einf and 3crc is not the same in v2 and v3
6413              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6414          }          }
6415            { // must be performed in RAM here ...
6416                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6417                if (pData) {
6418                    File::SampleList::iterator iter = pSamples->begin();
6419                    File::SampleList::iterator end  = pSamples->end();
6420                    for (int index = 0; iter != end; ++iter, ++index) {
6421                        gig::Sample* pSample = (gig::Sample*) *iter;
6422                        pData[index*2]   = 1; // always 1
6423                        pData[index*2+1] = pSample->crc;
6424                    }
6425                }
6426            }
6427        }
6428        
6429        void File::UpdateFileOffsets() {
6430            DLS::File::UpdateFileOffsets();
6431    
6432            for (Instrument* instrument = GetFirstInstrument(); instrument;
6433                 instrument = GetNextInstrument())
6434            {
6435                instrument->UpdateScriptFileOffsets();
6436            }
6437      }      }
6438    
6439      /**      /**

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

  ViewVC Help
Powered by ViewVC