/[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 1869 by persson, Sun Mar 22 11:13:25 2009 UTC revision 3198 by schoenebeck, Sun May 21 12:46:05 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 910  namespace { Line 998  namespace {
998                                  }                                  }
999    
1000                                  // reverse the sample frames for backward playback                                  // reverse the sample frames for backward playback
1001                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                                  if (totalreadsamples > swapareastart) //FIXME: this if() is just a crash workaround for now (#102), but totalreadsamples <= swapareastart should never be the case, so there's probably still a bug above!
1002                                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
1003                              }                              }
1004                          } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
1005                          break;                          break;
# Line 937  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 1021  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 1036  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 1059  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 1210  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 1219  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 1231  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 1253  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 1291  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 1307  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 1432  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 1501  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 1580  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 1595  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            // in case this class will become backward incompatible one day,
1821            // then set a version and minimum version for this class like:
1822            //archive->setVersion(*this, 2);
1823            //archive->setMinVersion(*this, 1);
1824    
1825            SRLZ(VelocityUpperLimit);
1826            SRLZ(EG1PreAttack);
1827            SRLZ(EG1Attack);
1828            SRLZ(EG1Decay1);
1829            SRLZ(EG1Decay2);
1830            SRLZ(EG1InfiniteSustain);
1831            SRLZ(EG1Sustain);
1832            SRLZ(EG1Release);
1833            SRLZ(EG1Hold);
1834            SRLZ(EG1Controller);
1835            SRLZ(EG1ControllerInvert);
1836            SRLZ(EG1ControllerAttackInfluence);
1837            SRLZ(EG1ControllerDecayInfluence);
1838            SRLZ(EG1ControllerReleaseInfluence);
1839            SRLZ(LFO1Frequency);
1840            SRLZ(LFO1InternalDepth);
1841            SRLZ(LFO1ControlDepth);
1842            SRLZ(LFO1Controller);
1843            SRLZ(LFO1FlipPhase);
1844            SRLZ(LFO1Sync);
1845            SRLZ(EG2PreAttack);
1846            SRLZ(EG2Attack);
1847            SRLZ(EG2Decay1);
1848            SRLZ(EG2Decay2);
1849            SRLZ(EG2InfiniteSustain);
1850            SRLZ(EG2Sustain);
1851            SRLZ(EG2Release);
1852            SRLZ(EG2Controller);
1853            SRLZ(EG2ControllerInvert);
1854            SRLZ(EG2ControllerAttackInfluence);
1855            SRLZ(EG2ControllerDecayInfluence);
1856            SRLZ(EG2ControllerReleaseInfluence);
1857            SRLZ(LFO2Frequency);
1858            SRLZ(LFO2InternalDepth);
1859            SRLZ(LFO2ControlDepth);
1860            SRLZ(LFO2Controller);
1861            SRLZ(LFO2FlipPhase);
1862            SRLZ(LFO2Sync);
1863            SRLZ(EG3Attack);
1864            SRLZ(EG3Depth);
1865            SRLZ(LFO3Frequency);
1866            SRLZ(LFO3InternalDepth);
1867            SRLZ(LFO3ControlDepth);
1868            SRLZ(LFO3Controller);
1869            SRLZ(LFO3Sync);
1870            SRLZ(VCFEnabled);
1871            SRLZ(VCFType);
1872            SRLZ(VCFCutoffController);
1873            SRLZ(VCFCutoffControllerInvert);
1874            SRLZ(VCFCutoff);
1875            SRLZ(VCFVelocityCurve);
1876            SRLZ(VCFVelocityScale);
1877            SRLZ(VCFVelocityDynamicRange);
1878            SRLZ(VCFResonance);
1879            SRLZ(VCFResonanceDynamic);
1880            SRLZ(VCFResonanceController);
1881            SRLZ(VCFKeyboardTracking);
1882            SRLZ(VCFKeyboardTrackingBreakpoint);
1883            SRLZ(VelocityResponseCurve);
1884            SRLZ(VelocityResponseDepth);
1885            SRLZ(VelocityResponseCurveScaling);
1886            SRLZ(ReleaseVelocityResponseCurve);
1887            SRLZ(ReleaseVelocityResponseDepth);
1888            SRLZ(ReleaseTriggerDecay);
1889            SRLZ(Crossfade);
1890            SRLZ(PitchTrack);
1891            SRLZ(DimensionBypass);
1892            SRLZ(Pan);
1893            SRLZ(SelfMask);
1894            SRLZ(AttenuationController);
1895            SRLZ(InvertAttenuationController);
1896            SRLZ(AttenuationControllerThreshold);
1897            SRLZ(ChannelOffset);
1898            SRLZ(SustainDefeat);
1899            SRLZ(MSDecode);
1900            //SRLZ(SampleStartOffset);
1901            SRLZ(SampleAttenuation);
1902    
1903            // derived attributes from DLS::Sampler
1904            SRLZ(FineTune);
1905            SRLZ(Gain);
1906        }
1907    
1908      /**      /**
1909       * Updates the respective member variable and updates @c SampleAttenuation       * Updates the respective member variable and updates @c SampleAttenuation
# Line 1611  namespace { Line 1920  namespace {
1920       *       *
1921       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
1922       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
1923         *
1924         * @param pProgress - callback function for progress notification
1925       */       */
1926      void DimensionRegion::UpdateChunks() {      void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1927          // first update base class's chunk          // first update base class's chunk
1928          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks(pProgress);
1929    
1930          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1931          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
# Line 1634  namespace { Line 1945  namespace {
1945    
1946          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1947    
1948          const uint32_t chunksize = _3ewa->GetNewSize();          const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1949          store32(&pData[0], chunksize); // unknown, always chunk size?          store32(&pData[0], chunksize); // unknown, always chunk size?
1950    
1951          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
# Line 1836  namespace { Line 2147  namespace {
2147          }          }
2148    
2149          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
2150                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
2151          store16(&pData[116], eg3depth);          store16(&pData[116], eg3depth);
2152    
2153          // next 2 bytes unknown          // next 2 bytes unknown
# Line 1884  namespace { Line 2195  namespace {
2195                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2196          pData[137] = vcfbreakpoint;          pData[137] = vcfbreakpoint;
2197    
2198          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2199                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2200          pData[138] = vcfvelocity;          pData[138] = vcfvelocity;
2201    
# Line 1949  namespace { Line 2260  namespace {
2260          return pRegion;          return pRegion;
2261      }      }
2262    
2263    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2264    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2265    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2266    //#pragma GCC diagnostic push
2267    //#pragma GCC diagnostic error "-Wswitch"
2268    
2269      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2270          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2271          switch (EncodedController) {          switch (EncodedController) {
# Line 2060  namespace { Line 2377  namespace {
2377                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2378                  break;                  break;
2379    
2380                // format extension (these controllers are so far only supported by
2381                // LinuxSampler & gigedit) they will *NOT* work with
2382                // Gigasampler/GigaStudio !
2383                case _lev_ctrl_CC3_EXT:
2384                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2385                    decodedcontroller.controller_number = 3;
2386                    break;
2387                case _lev_ctrl_CC6_EXT:
2388                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2389                    decodedcontroller.controller_number = 6;
2390                    break;
2391                case _lev_ctrl_CC7_EXT:
2392                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2393                    decodedcontroller.controller_number = 7;
2394                    break;
2395                case _lev_ctrl_CC8_EXT:
2396                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2397                    decodedcontroller.controller_number = 8;
2398                    break;
2399                case _lev_ctrl_CC9_EXT:
2400                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2401                    decodedcontroller.controller_number = 9;
2402                    break;
2403                case _lev_ctrl_CC10_EXT:
2404                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2405                    decodedcontroller.controller_number = 10;
2406                    break;
2407                case _lev_ctrl_CC11_EXT:
2408                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2409                    decodedcontroller.controller_number = 11;
2410                    break;
2411                case _lev_ctrl_CC14_EXT:
2412                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2413                    decodedcontroller.controller_number = 14;
2414                    break;
2415                case _lev_ctrl_CC15_EXT:
2416                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2417                    decodedcontroller.controller_number = 15;
2418                    break;
2419                case _lev_ctrl_CC20_EXT:
2420                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2421                    decodedcontroller.controller_number = 20;
2422                    break;
2423                case _lev_ctrl_CC21_EXT:
2424                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2425                    decodedcontroller.controller_number = 21;
2426                    break;
2427                case _lev_ctrl_CC22_EXT:
2428                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2429                    decodedcontroller.controller_number = 22;
2430                    break;
2431                case _lev_ctrl_CC23_EXT:
2432                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2433                    decodedcontroller.controller_number = 23;
2434                    break;
2435                case _lev_ctrl_CC24_EXT:
2436                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2437                    decodedcontroller.controller_number = 24;
2438                    break;
2439                case _lev_ctrl_CC25_EXT:
2440                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2441                    decodedcontroller.controller_number = 25;
2442                    break;
2443                case _lev_ctrl_CC26_EXT:
2444                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2445                    decodedcontroller.controller_number = 26;
2446                    break;
2447                case _lev_ctrl_CC27_EXT:
2448                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2449                    decodedcontroller.controller_number = 27;
2450                    break;
2451                case _lev_ctrl_CC28_EXT:
2452                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2453                    decodedcontroller.controller_number = 28;
2454                    break;
2455                case _lev_ctrl_CC29_EXT:
2456                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2457                    decodedcontroller.controller_number = 29;
2458                    break;
2459                case _lev_ctrl_CC30_EXT:
2460                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2461                    decodedcontroller.controller_number = 30;
2462                    break;
2463                case _lev_ctrl_CC31_EXT:
2464                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2465                    decodedcontroller.controller_number = 31;
2466                    break;
2467                case _lev_ctrl_CC68_EXT:
2468                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2469                    decodedcontroller.controller_number = 68;
2470                    break;
2471                case _lev_ctrl_CC69_EXT:
2472                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2473                    decodedcontroller.controller_number = 69;
2474                    break;
2475                case _lev_ctrl_CC70_EXT:
2476                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2477                    decodedcontroller.controller_number = 70;
2478                    break;
2479                case _lev_ctrl_CC71_EXT:
2480                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2481                    decodedcontroller.controller_number = 71;
2482                    break;
2483                case _lev_ctrl_CC72_EXT:
2484                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2485                    decodedcontroller.controller_number = 72;
2486                    break;
2487                case _lev_ctrl_CC73_EXT:
2488                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2489                    decodedcontroller.controller_number = 73;
2490                    break;
2491                case _lev_ctrl_CC74_EXT:
2492                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2493                    decodedcontroller.controller_number = 74;
2494                    break;
2495                case _lev_ctrl_CC75_EXT:
2496                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2497                    decodedcontroller.controller_number = 75;
2498                    break;
2499                case _lev_ctrl_CC76_EXT:
2500                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2501                    decodedcontroller.controller_number = 76;
2502                    break;
2503                case _lev_ctrl_CC77_EXT:
2504                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2505                    decodedcontroller.controller_number = 77;
2506                    break;
2507                case _lev_ctrl_CC78_EXT:
2508                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2509                    decodedcontroller.controller_number = 78;
2510                    break;
2511                case _lev_ctrl_CC79_EXT:
2512                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2513                    decodedcontroller.controller_number = 79;
2514                    break;
2515                case _lev_ctrl_CC84_EXT:
2516                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2517                    decodedcontroller.controller_number = 84;
2518                    break;
2519                case _lev_ctrl_CC85_EXT:
2520                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2521                    decodedcontroller.controller_number = 85;
2522                    break;
2523                case _lev_ctrl_CC86_EXT:
2524                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2525                    decodedcontroller.controller_number = 86;
2526                    break;
2527                case _lev_ctrl_CC87_EXT:
2528                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2529                    decodedcontroller.controller_number = 87;
2530                    break;
2531                case _lev_ctrl_CC89_EXT:
2532                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2533                    decodedcontroller.controller_number = 89;
2534                    break;
2535                case _lev_ctrl_CC90_EXT:
2536                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2537                    decodedcontroller.controller_number = 90;
2538                    break;
2539                case _lev_ctrl_CC96_EXT:
2540                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2541                    decodedcontroller.controller_number = 96;
2542                    break;
2543                case _lev_ctrl_CC97_EXT:
2544                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2545                    decodedcontroller.controller_number = 97;
2546                    break;
2547                case _lev_ctrl_CC102_EXT:
2548                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2549                    decodedcontroller.controller_number = 102;
2550                    break;
2551                case _lev_ctrl_CC103_EXT:
2552                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2553                    decodedcontroller.controller_number = 103;
2554                    break;
2555                case _lev_ctrl_CC104_EXT:
2556                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2557                    decodedcontroller.controller_number = 104;
2558                    break;
2559                case _lev_ctrl_CC105_EXT:
2560                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2561                    decodedcontroller.controller_number = 105;
2562                    break;
2563                case _lev_ctrl_CC106_EXT:
2564                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2565                    decodedcontroller.controller_number = 106;
2566                    break;
2567                case _lev_ctrl_CC107_EXT:
2568                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2569                    decodedcontroller.controller_number = 107;
2570                    break;
2571                case _lev_ctrl_CC108_EXT:
2572                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2573                    decodedcontroller.controller_number = 108;
2574                    break;
2575                case _lev_ctrl_CC109_EXT:
2576                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2577                    decodedcontroller.controller_number = 109;
2578                    break;
2579                case _lev_ctrl_CC110_EXT:
2580                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2581                    decodedcontroller.controller_number = 110;
2582                    break;
2583                case _lev_ctrl_CC111_EXT:
2584                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2585                    decodedcontroller.controller_number = 111;
2586                    break;
2587                case _lev_ctrl_CC112_EXT:
2588                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2589                    decodedcontroller.controller_number = 112;
2590                    break;
2591                case _lev_ctrl_CC113_EXT:
2592                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2593                    decodedcontroller.controller_number = 113;
2594                    break;
2595                case _lev_ctrl_CC114_EXT:
2596                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2597                    decodedcontroller.controller_number = 114;
2598                    break;
2599                case _lev_ctrl_CC115_EXT:
2600                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2601                    decodedcontroller.controller_number = 115;
2602                    break;
2603                case _lev_ctrl_CC116_EXT:
2604                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2605                    decodedcontroller.controller_number = 116;
2606                    break;
2607                case _lev_ctrl_CC117_EXT:
2608                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2609                    decodedcontroller.controller_number = 117;
2610                    break;
2611                case _lev_ctrl_CC118_EXT:
2612                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2613                    decodedcontroller.controller_number = 118;
2614                    break;
2615                case _lev_ctrl_CC119_EXT:
2616                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2617                    decodedcontroller.controller_number = 119;
2618                    break;
2619    
2620              // unknown controller type              // unknown controller type
2621              default:              default:
2622                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type (0x%x).", EncodedController);
2623          }          }
2624          return decodedcontroller;          return decodedcontroller;
2625      }      }
2626        
2627    // see above (diagnostic push not supported prior GCC 4.6)
2628    //#pragma GCC diagnostic pop
2629    
2630      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2631          _lev_ctrl_t encodedcontroller;          _lev_ctrl_t encodedcontroller;
# Line 2153  namespace { Line 2713  namespace {
2713                      case 95:                      case 95:
2714                          encodedcontroller = _lev_ctrl_effect5depth;                          encodedcontroller = _lev_ctrl_effect5depth;
2715                          break;                          break;
2716    
2717                        // format extension (these controllers are so far only
2718                        // supported by LinuxSampler & gigedit) they will *NOT*
2719                        // work with Gigasampler/GigaStudio !
2720                        case 3:
2721                            encodedcontroller = _lev_ctrl_CC3_EXT;
2722                            break;
2723                        case 6:
2724                            encodedcontroller = _lev_ctrl_CC6_EXT;
2725                            break;
2726                        case 7:
2727                            encodedcontroller = _lev_ctrl_CC7_EXT;
2728                            break;
2729                        case 8:
2730                            encodedcontroller = _lev_ctrl_CC8_EXT;
2731                            break;
2732                        case 9:
2733                            encodedcontroller = _lev_ctrl_CC9_EXT;
2734                            break;
2735                        case 10:
2736                            encodedcontroller = _lev_ctrl_CC10_EXT;
2737                            break;
2738                        case 11:
2739                            encodedcontroller = _lev_ctrl_CC11_EXT;
2740                            break;
2741                        case 14:
2742                            encodedcontroller = _lev_ctrl_CC14_EXT;
2743                            break;
2744                        case 15:
2745                            encodedcontroller = _lev_ctrl_CC15_EXT;
2746                            break;
2747                        case 20:
2748                            encodedcontroller = _lev_ctrl_CC20_EXT;
2749                            break;
2750                        case 21:
2751                            encodedcontroller = _lev_ctrl_CC21_EXT;
2752                            break;
2753                        case 22:
2754                            encodedcontroller = _lev_ctrl_CC22_EXT;
2755                            break;
2756                        case 23:
2757                            encodedcontroller = _lev_ctrl_CC23_EXT;
2758                            break;
2759                        case 24:
2760                            encodedcontroller = _lev_ctrl_CC24_EXT;
2761                            break;
2762                        case 25:
2763                            encodedcontroller = _lev_ctrl_CC25_EXT;
2764                            break;
2765                        case 26:
2766                            encodedcontroller = _lev_ctrl_CC26_EXT;
2767                            break;
2768                        case 27:
2769                            encodedcontroller = _lev_ctrl_CC27_EXT;
2770                            break;
2771                        case 28:
2772                            encodedcontroller = _lev_ctrl_CC28_EXT;
2773                            break;
2774                        case 29:
2775                            encodedcontroller = _lev_ctrl_CC29_EXT;
2776                            break;
2777                        case 30:
2778                            encodedcontroller = _lev_ctrl_CC30_EXT;
2779                            break;
2780                        case 31:
2781                            encodedcontroller = _lev_ctrl_CC31_EXT;
2782                            break;
2783                        case 68:
2784                            encodedcontroller = _lev_ctrl_CC68_EXT;
2785                            break;
2786                        case 69:
2787                            encodedcontroller = _lev_ctrl_CC69_EXT;
2788                            break;
2789                        case 70:
2790                            encodedcontroller = _lev_ctrl_CC70_EXT;
2791                            break;
2792                        case 71:
2793                            encodedcontroller = _lev_ctrl_CC71_EXT;
2794                            break;
2795                        case 72:
2796                            encodedcontroller = _lev_ctrl_CC72_EXT;
2797                            break;
2798                        case 73:
2799                            encodedcontroller = _lev_ctrl_CC73_EXT;
2800                            break;
2801                        case 74:
2802                            encodedcontroller = _lev_ctrl_CC74_EXT;
2803                            break;
2804                        case 75:
2805                            encodedcontroller = _lev_ctrl_CC75_EXT;
2806                            break;
2807                        case 76:
2808                            encodedcontroller = _lev_ctrl_CC76_EXT;
2809                            break;
2810                        case 77:
2811                            encodedcontroller = _lev_ctrl_CC77_EXT;
2812                            break;
2813                        case 78:
2814                            encodedcontroller = _lev_ctrl_CC78_EXT;
2815                            break;
2816                        case 79:
2817                            encodedcontroller = _lev_ctrl_CC79_EXT;
2818                            break;
2819                        case 84:
2820                            encodedcontroller = _lev_ctrl_CC84_EXT;
2821                            break;
2822                        case 85:
2823                            encodedcontroller = _lev_ctrl_CC85_EXT;
2824                            break;
2825                        case 86:
2826                            encodedcontroller = _lev_ctrl_CC86_EXT;
2827                            break;
2828                        case 87:
2829                            encodedcontroller = _lev_ctrl_CC87_EXT;
2830                            break;
2831                        case 89:
2832                            encodedcontroller = _lev_ctrl_CC89_EXT;
2833                            break;
2834                        case 90:
2835                            encodedcontroller = _lev_ctrl_CC90_EXT;
2836                            break;
2837                        case 96:
2838                            encodedcontroller = _lev_ctrl_CC96_EXT;
2839                            break;
2840                        case 97:
2841                            encodedcontroller = _lev_ctrl_CC97_EXT;
2842                            break;
2843                        case 102:
2844                            encodedcontroller = _lev_ctrl_CC102_EXT;
2845                            break;
2846                        case 103:
2847                            encodedcontroller = _lev_ctrl_CC103_EXT;
2848                            break;
2849                        case 104:
2850                            encodedcontroller = _lev_ctrl_CC104_EXT;
2851                            break;
2852                        case 105:
2853                            encodedcontroller = _lev_ctrl_CC105_EXT;
2854                            break;
2855                        case 106:
2856                            encodedcontroller = _lev_ctrl_CC106_EXT;
2857                            break;
2858                        case 107:
2859                            encodedcontroller = _lev_ctrl_CC107_EXT;
2860                            break;
2861                        case 108:
2862                            encodedcontroller = _lev_ctrl_CC108_EXT;
2863                            break;
2864                        case 109:
2865                            encodedcontroller = _lev_ctrl_CC109_EXT;
2866                            break;
2867                        case 110:
2868                            encodedcontroller = _lev_ctrl_CC110_EXT;
2869                            break;
2870                        case 111:
2871                            encodedcontroller = _lev_ctrl_CC111_EXT;
2872                            break;
2873                        case 112:
2874                            encodedcontroller = _lev_ctrl_CC112_EXT;
2875                            break;
2876                        case 113:
2877                            encodedcontroller = _lev_ctrl_CC113_EXT;
2878                            break;
2879                        case 114:
2880                            encodedcontroller = _lev_ctrl_CC114_EXT;
2881                            break;
2882                        case 115:
2883                            encodedcontroller = _lev_ctrl_CC115_EXT;
2884                            break;
2885                        case 116:
2886                            encodedcontroller = _lev_ctrl_CC116_EXT;
2887                            break;
2888                        case 117:
2889                            encodedcontroller = _lev_ctrl_CC117_EXT;
2890                            break;
2891                        case 118:
2892                            encodedcontroller = _lev_ctrl_CC118_EXT;
2893                            break;
2894                        case 119:
2895                            encodedcontroller = _lev_ctrl_CC119_EXT;
2896                            break;
2897    
2898                      default:                      default:
2899                          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");
2900                  }                  }
# Line 2454  namespace { Line 3196  namespace {
3196       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
3197       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
3198       *       *
3199         * @param pProgress - callback function for progress notification
3200       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3201       */       */
3202      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
3203          // 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
3204          // 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
3205          // 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 2464  namespace { Line 3207  namespace {
3207          pSample = pDimensionRegions[0]->pSample;          pSample = pDimensionRegions[0]->pSample;
3208    
3209          // first update base class's chunks          // first update base class's chunks
3210          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks(pProgress);
3211    
3212          // update dimension region's chunks          // update dimension region's chunks
3213          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
3214              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks(pProgress);
3215          }          }
3216    
3217          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
# Line 2484  namespace { Line 3227  namespace {
3227              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3228    
3229              // move 3prg to last position              // move 3prg to last position
3230              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3231          }          }
3232    
3233          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
# Line 2558  namespace { Line 3301  namespace {
3301          int step = 1;          int step = 1;
3302          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3303          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3304    
3305          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3306          int dim[8] = { 0 };          int dim[8] = { 0 };
3307          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3308                const int end = i + step * pDimensionDefinitions[veldim].zones;
3309    
3310                // create a velocity table for all cases where the velocity zone is zero
3311              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3312                  pDimensionRegions[i]->VelocityUpperLimit) {                  pDimensionRegions[i]->VelocityUpperLimit) {
3313                  // create the velocity table                  // create the velocity table
# Line 2594  namespace { Line 3338  namespace {
3338                  }                  }
3339              }              }
3340    
3341                // jump to the next case where the velocity zone is zero
3342              int j;              int j;
3343              int shift = 0;              int shift = 0;
3344              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 2630  namespace { Line 3375  namespace {
3375       *                        dimension bits limit is violated       *                        dimension bits limit is violated
3376       */       */
3377      void Region::AddDimension(dimension_def_t* pDimDef) {      void Region::AddDimension(dimension_def_t* pDimDef) {
3378            // some initial sanity checks of the given dimension definition
3379            if (pDimDef->zones < 2)
3380                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3381            if (pDimDef->bits < 1)
3382                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3383            if (pDimDef->dimension == dimension_samplechannel) {
3384                if (pDimDef->zones != 2)
3385                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3386                if (pDimDef->bits != 1)
3387                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3388            }
3389    
3390          // check if max. amount of dimensions reached          // check if max. amount of dimensions reached
3391          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3392          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
# Line 2805  namespace { Line 3562  namespace {
3562          if (pDimDef->dimension == dimension_layer) Layers = 1;          if (pDimDef->dimension == dimension_layer) Layers = 1;
3563      }      }
3564    
3565        /** @brief Delete one split zone of a dimension (decrement zone amount).
3566         *
3567         * Instead of deleting an entire dimensions, this method will only delete
3568         * one particular split zone given by @a zone of the Region's dimension
3569         * given by @a type. So this method will simply decrement the amount of
3570         * zones by one of the dimension in question. To be able to do that, the
3571         * respective dimension must exist on this Region and it must have at least
3572         * 3 zones. All DimensionRegion objects associated with the zone will be
3573         * deleted.
3574         *
3575         * @param type - identifies the dimension where a zone shall be deleted
3576         * @param zone - index of the dimension split zone that shall be deleted
3577         * @throws gig::Exception if requested zone could not be deleted
3578         */
3579        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3580            dimension_def_t* oldDef = GetDimensionDefinition(type);
3581            if (!oldDef)
3582                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3583            if (oldDef->zones <= 2)
3584                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3585            if (zone < 0 || zone >= oldDef->zones)
3586                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3587    
3588            const int newZoneSize = oldDef->zones - 1;
3589    
3590            // create a temporary Region which just acts as a temporary copy
3591            // container and will be deleted at the end of this function and will
3592            // also not be visible through the API during this process
3593            gig::Region* tempRgn = NULL;
3594            {
3595                // adding these temporary chunks is probably not even necessary
3596                Instrument* instr = static_cast<Instrument*>(GetParent());
3597                RIFF::List* pCkInstrument = instr->pCkInstrument;
3598                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3599                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3600                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3601                tempRgn = new Region(instr, rgn);
3602            }
3603    
3604            // copy this region's dimensions (with already the dimension split size
3605            // requested by the arguments of this method call) to the temporary
3606            // region, and don't use Region::CopyAssign() here for this task, since
3607            // it would also alter fast lookup helper variables here and there
3608            dimension_def_t newDef;
3609            for (int i = 0; i < Dimensions; ++i) {
3610                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3611                // is this the dimension requested by the method arguments? ...
3612                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3613                    def.zones = newZoneSize;
3614                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3615                    newDef = def;
3616                }
3617                tempRgn->AddDimension(&def);
3618            }
3619    
3620            // find the dimension index in the tempRegion which is the dimension
3621            // type passed to this method (paranoidly expecting different order)
3622            int tempReducedDimensionIndex = -1;
3623            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3624                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3625                    tempReducedDimensionIndex = d;
3626                    break;
3627                }
3628            }
3629    
3630            // copy dimension regions from this region to the temporary region
3631            for (int iDst = 0; iDst < 256; ++iDst) {
3632                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3633                if (!dstDimRgn) continue;
3634                std::map<dimension_t,int> dimCase;
3635                bool isValidZone = true;
3636                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3637                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3638                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3639                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3640                    baseBits += dstBits;
3641                    // there are also DimensionRegion objects of unused zones, skip them
3642                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3643                        isValidZone = false;
3644                        break;
3645                    }
3646                }
3647                if (!isValidZone) continue;
3648                // a bit paranoid: cope with the chance that the dimensions would
3649                // have different order in source and destination regions
3650                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3651                if (dimCase[type] >= zone) dimCase[type]++;
3652                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3653                dstDimRgn->CopyAssign(srcDimRgn);
3654                // if this is the upper most zone of the dimension passed to this
3655                // method, then correct (raise) its upper limit to 127
3656                if (newDef.split_type == split_type_normal && isLastZone)
3657                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3658            }
3659    
3660            // now tempRegion's dimensions and DimensionRegions basically reflect
3661            // what we wanted to get for this actual Region here, so we now just
3662            // delete and recreate the dimension in question with the new amount
3663            // zones and then copy back from tempRegion      
3664            DeleteDimension(oldDef);
3665            AddDimension(&newDef);
3666            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3667                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3668                if (!srcDimRgn) continue;
3669                std::map<dimension_t,int> dimCase;
3670                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3671                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3672                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3673                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3674                    baseBits += srcBits;
3675                }
3676                // a bit paranoid: cope with the chance that the dimensions would
3677                // have different order in source and destination regions
3678                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3679                if (!dstDimRgn) continue;
3680                dstDimRgn->CopyAssign(srcDimRgn);
3681            }
3682    
3683            // delete temporary region
3684            delete tempRgn;
3685    
3686            UpdateVelocityTable();
3687        }
3688    
3689        /** @brief Divide split zone of a dimension in two (increment zone amount).
3690         *
3691         * This will increment the amount of zones for the dimension (given by
3692         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3693         * in the middle of its zone range in two. So the two zones resulting from
3694         * the zone being splitted, will be an equivalent copy regarding all their
3695         * articulation informations and sample reference. The two zones will only
3696         * differ in their zone's upper limit
3697         * (DimensionRegion::DimensionUpperLimits).
3698         *
3699         * @param type - identifies the dimension where a zone shall be splitted
3700         * @param zone - index of the dimension split zone that shall be splitted
3701         * @throws gig::Exception if requested zone could not be splitted
3702         */
3703        void Region::SplitDimensionZone(dimension_t type, int zone) {
3704            dimension_def_t* oldDef = GetDimensionDefinition(type);
3705            if (!oldDef)
3706                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3707            if (zone < 0 || zone >= oldDef->zones)
3708                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3709    
3710            const int newZoneSize = oldDef->zones + 1;
3711    
3712            // create a temporary Region which just acts as a temporary copy
3713            // container and will be deleted at the end of this function and will
3714            // also not be visible through the API during this process
3715            gig::Region* tempRgn = NULL;
3716            {
3717                // adding these temporary chunks is probably not even necessary
3718                Instrument* instr = static_cast<Instrument*>(GetParent());
3719                RIFF::List* pCkInstrument = instr->pCkInstrument;
3720                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3721                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3722                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3723                tempRgn = new Region(instr, rgn);
3724            }
3725    
3726            // copy this region's dimensions (with already the dimension split size
3727            // requested by the arguments of this method call) to the temporary
3728            // region, and don't use Region::CopyAssign() here for this task, since
3729            // it would also alter fast lookup helper variables here and there
3730            dimension_def_t newDef;
3731            for (int i = 0; i < Dimensions; ++i) {
3732                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3733                // is this the dimension requested by the method arguments? ...
3734                if (def.dimension == type) { // ... if yes, increment zone amount by one
3735                    def.zones = newZoneSize;
3736                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3737                    newDef = def;
3738                }
3739                tempRgn->AddDimension(&def);
3740            }
3741    
3742            // find the dimension index in the tempRegion which is the dimension
3743            // type passed to this method (paranoidly expecting different order)
3744            int tempIncreasedDimensionIndex = -1;
3745            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3746                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3747                    tempIncreasedDimensionIndex = d;
3748                    break;
3749                }
3750            }
3751    
3752            // copy dimension regions from this region to the temporary region
3753            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3754                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3755                if (!srcDimRgn) continue;
3756                std::map<dimension_t,int> dimCase;
3757                bool isValidZone = true;
3758                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3759                    const int srcBits = pDimensionDefinitions[d].bits;
3760                    dimCase[pDimensionDefinitions[d].dimension] =
3761                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3762                    // there are also DimensionRegion objects for unused zones, skip them
3763                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3764                        isValidZone = false;
3765                        break;
3766                    }
3767                    baseBits += srcBits;
3768                }
3769                if (!isValidZone) continue;
3770                // a bit paranoid: cope with the chance that the dimensions would
3771                // have different order in source and destination regions            
3772                if (dimCase[type] > zone) dimCase[type]++;
3773                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3774                dstDimRgn->CopyAssign(srcDimRgn);
3775                // if this is the requested zone to be splitted, then also copy
3776                // the source DimensionRegion to the newly created target zone
3777                // and set the old zones upper limit lower
3778                if (dimCase[type] == zone) {
3779                    // lower old zones upper limit
3780                    if (newDef.split_type == split_type_normal) {
3781                        const int high =
3782                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3783                        int low = 0;
3784                        if (zone > 0) {
3785                            std::map<dimension_t,int> lowerCase = dimCase;
3786                            lowerCase[type]--;
3787                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3788                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3789                        }
3790                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3791                    }
3792                    // fill the newly created zone of the divided zone as well
3793                    dimCase[type]++;
3794                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3795                    dstDimRgn->CopyAssign(srcDimRgn);
3796                }
3797            }
3798    
3799            // now tempRegion's dimensions and DimensionRegions basically reflect
3800            // what we wanted to get for this actual Region here, so we now just
3801            // delete and recreate the dimension in question with the new amount
3802            // zones and then copy back from tempRegion      
3803            DeleteDimension(oldDef);
3804            AddDimension(&newDef);
3805            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3806                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3807                if (!srcDimRgn) continue;
3808                std::map<dimension_t,int> dimCase;
3809                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3810                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3811                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3812                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3813                    baseBits += srcBits;
3814                }
3815                // a bit paranoid: cope with the chance that the dimensions would
3816                // have different order in source and destination regions
3817                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3818                if (!dstDimRgn) continue;
3819                dstDimRgn->CopyAssign(srcDimRgn);
3820            }
3821    
3822            // delete temporary region
3823            delete tempRgn;
3824    
3825            UpdateVelocityTable();
3826        }
3827    
3828        /** @brief Change type of an existing dimension.
3829         *
3830         * Alters the dimension type of a dimension already existing on this
3831         * region. If there is currently no dimension on this Region with type
3832         * @a oldType, then this call with throw an Exception. Likewise there are
3833         * cases where the requested dimension type cannot be performed. For example
3834         * if the new dimension type shall be gig::dimension_samplechannel, and the
3835         * current dimension has more than 2 zones. In such cases an Exception is
3836         * thrown as well.
3837         *
3838         * @param oldType - identifies the existing dimension to be changed
3839         * @param newType - to which dimension type it should be changed to
3840         * @throws gig::Exception if requested change cannot be performed
3841         */
3842        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3843            if (oldType == newType) return;
3844            dimension_def_t* def = GetDimensionDefinition(oldType);
3845            if (!def)
3846                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3847            if (newType == dimension_samplechannel && def->zones != 2)
3848                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3849            if (GetDimensionDefinition(newType))
3850                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3851            def->dimension  = newType;
3852            def->split_type = __resolveSplitType(newType);
3853        }
3854    
3855        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3856            uint8_t bits[8] = {};
3857            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3858                 it != DimCase.end(); ++it)
3859            {
3860                for (int d = 0; d < Dimensions; ++d) {
3861                    if (pDimensionDefinitions[d].dimension == it->first) {
3862                        bits[d] = it->second;
3863                        goto nextDimCaseSlice;
3864                    }
3865                }
3866                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3867                nextDimCaseSlice:
3868                ; // noop
3869            }
3870            return GetDimensionRegionByBit(bits);
3871        }
3872    
3873        /**
3874         * Searches in the current Region for a dimension of the given dimension
3875         * type and returns the precise configuration of that dimension in this
3876         * Region.
3877         *
3878         * @param type - dimension type of the sought dimension
3879         * @returns dimension definition or NULL if there is no dimension with
3880         *          sought type in this Region.
3881         */
3882        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3883            for (int i = 0; i < Dimensions; ++i)
3884                if (pDimensionDefinitions[i].dimension == type)
3885                    return &pDimensionDefinitions[i];
3886            return NULL;
3887        }
3888    
3889      Region::~Region() {      Region::~Region() {
3890          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
3891              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
# Line 2832  namespace { Line 3913  namespace {
3913      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3914          uint8_t bits;          uint8_t bits;
3915          int veldim = -1;          int veldim = -1;
3916          int velbitpos;          int velbitpos = 0;
3917          int bitpos = 0;          int bitpos = 0;
3918          int dimregidx = 0;          int dimregidx = 0;
3919          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 2862  namespace { Line 3943  namespace {
3943              }              }
3944              bitpos += pDimensionDefinitions[i].bits;              bitpos += pDimensionDefinitions[i].bits;
3945          }          }
3946          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3947            if (!dimreg) return NULL;
3948          if (veldim != -1) {          if (veldim != -1) {
3949              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3950              if (dimreg->VelocityTable) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3951                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3952              else // normal split type              else // normal split type
3953                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3954    
3955              dimregidx |= bits << velbitpos;              const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3956              dimreg = pDimensionRegions[dimregidx];              dimregidx |= (bits & limiter_mask) << velbitpos;
3957                dimreg = pDimensionRegions[dimregidx & 255];
3958          }          }
3959          return dimreg;          return dimreg;
3960      }      }
3961    
3962        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3963            uint8_t bits;
3964            int veldim = -1;
3965            int velbitpos = 0;
3966            int bitpos = 0;
3967            int dimregidx = 0;
3968            for (uint i = 0; i < Dimensions; i++) {
3969                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3970                    // the velocity dimension must be handled after the other dimensions
3971                    veldim = i;
3972                    velbitpos = bitpos;
3973                } else {
3974                    switch (pDimensionDefinitions[i].split_type) {
3975                        case split_type_normal:
3976                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3977                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3978                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3979                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3980                                }
3981                            } else {
3982                                // gig2: evenly sized zones
3983                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3984                            }
3985                            break;
3986                        case split_type_bit: // the value is already the sought dimension bit number
3987                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3988                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3989                            break;
3990                    }
3991                    dimregidx |= bits << bitpos;
3992                }
3993                bitpos += pDimensionDefinitions[i].bits;
3994            }
3995            dimregidx &= 255;
3996            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3997            if (!dimreg) return -1;
3998            if (veldim != -1) {
3999                // (dimreg is now the dimension region for the lowest velocity)
4000                if (dimreg->VelocityTable) // custom defined zone ranges
4001                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
4002                else // normal split type
4003                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
4004    
4005                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
4006                dimregidx |= (bits & limiter_mask) << velbitpos;
4007                dimregidx &= 255;
4008            }
4009            return dimregidx;
4010        }
4011    
4012      /**      /**
4013       * Returns the appropriate DimensionRegion for the given dimension bit       * Returns the appropriate DimensionRegion for the given dimension bit
4014       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
# Line 2914  namespace { Line 4047  namespace {
4047          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
4048          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
4049          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
4050          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
4051          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
4052          Sample* sample = file->GetFirstSample(pProgress);              // use 64 bit wave pool offsets (treating this as large file)
4053          while (sample) {              uint64_t soughtoffset =
4054              if (sample->ulWavePoolOffset == soughtoffset &&                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
4055                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
4056              sample = file->GetNextSample();              Sample* sample = file->GetFirstSample(pProgress);
4057                while (sample) {
4058                    if (sample->ullWavePoolOffset == soughtoffset)
4059                        return static_cast<gig::Sample*>(sample);
4060                    sample = file->GetNextSample();
4061                }
4062            } else {
4063                // use extension files and 32 bit wave pool offsets
4064                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
4065                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
4066                Sample* sample = file->GetFirstSample(pProgress);
4067                while (sample) {
4068                    if (sample->ullWavePoolOffset == soughtoffset &&
4069                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
4070                    sample = file->GetNextSample();
4071                }
4072          }          }
4073          return NULL;          return NULL;
4074      }      }
4075        
4076        /**
4077         * Make a (semi) deep copy of the Region object given by @a orig
4078         * and assign it to this object.
4079         *
4080         * Note that all sample pointers referenced by @a orig are simply copied as
4081         * memory address. Thus the respective samples are shared, not duplicated!
4082         *
4083         * @param orig - original Region object to be copied from
4084         */
4085        void Region::CopyAssign(const Region* orig) {
4086            CopyAssign(orig, NULL);
4087        }
4088        
4089        /**
4090         * Make a (semi) deep copy of the Region object given by @a orig and
4091         * assign it to this object
4092         *
4093         * @param mSamples - crosslink map between the foreign file's samples and
4094         *                   this file's samples
4095         */
4096        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
4097            // handle base classes
4098            DLS::Region::CopyAssign(orig);
4099            
4100            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
4101                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
4102            }
4103            
4104            // handle own member variables
4105            for (int i = Dimensions - 1; i >= 0; --i) {
4106                DeleteDimension(&pDimensionDefinitions[i]);
4107            }
4108            Layers = 0; // just to be sure
4109            for (int i = 0; i < orig->Dimensions; i++) {
4110                // we need to copy the dim definition here, to avoid the compiler
4111                // complaining about const-ness issue
4112                dimension_def_t def = orig->pDimensionDefinitions[i];
4113                AddDimension(&def);
4114            }
4115            for (int i = 0; i < 256; i++) {
4116                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
4117                    pDimensionRegions[i]->CopyAssign(
4118                        orig->pDimensionRegions[i],
4119                        mSamples
4120                    );
4121                }
4122            }
4123            Layers = orig->Layers;
4124        }
4125    
4126    
4127  // *************** MidiRule ***************  // *************** MidiRule ***************
4128  // *  // *
4129    
4130  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {      MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
4131      _3ewg->SetPos(36);          _3ewg->SetPos(36);
4132      Triggers = _3ewg->ReadUint8();          Triggers = _3ewg->ReadUint8();
4133      _3ewg->SetPos(40);          _3ewg->SetPos(40);
4134      ControllerNumber = _3ewg->ReadUint8();          ControllerNumber = _3ewg->ReadUint8();
4135      _3ewg->SetPos(46);          _3ewg->SetPos(46);
4136      for (int i = 0 ; i < Triggers ; i++) {          for (int i = 0 ; i < Triggers ; i++) {
4137          pTriggers[i].TriggerPoint = _3ewg->ReadUint8();              pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
4138          pTriggers[i].Descending = _3ewg->ReadUint8();              pTriggers[i].Descending = _3ewg->ReadUint8();
4139          pTriggers[i].VelSensitivity = _3ewg->ReadUint8();              pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
4140          pTriggers[i].Key = _3ewg->ReadUint8();              pTriggers[i].Key = _3ewg->ReadUint8();
4141          pTriggers[i].NoteOff = _3ewg->ReadUint8();              pTriggers[i].NoteOff = _3ewg->ReadUint8();
4142          pTriggers[i].Velocity = _3ewg->ReadUint8();              pTriggers[i].Velocity = _3ewg->ReadUint8();
4143          pTriggers[i].OverridePedal = _3ewg->ReadUint8();              pTriggers[i].OverridePedal = _3ewg->ReadUint8();
4144          _3ewg->ReadUint8();              _3ewg->ReadUint8();
4145            }
4146        }
4147    
4148        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
4149            ControllerNumber(0),
4150            Triggers(0) {
4151        }
4152    
4153        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
4154            pData[32] = 4;
4155            pData[33] = 16;
4156            pData[36] = Triggers;
4157            pData[40] = ControllerNumber;
4158            for (int i = 0 ; i < Triggers ; i++) {
4159                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
4160                pData[47 + i * 8] = pTriggers[i].Descending;
4161                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
4162                pData[49 + i * 8] = pTriggers[i].Key;
4163                pData[50 + i * 8] = pTriggers[i].NoteOff;
4164                pData[51 + i * 8] = pTriggers[i].Velocity;
4165                pData[52 + i * 8] = pTriggers[i].OverridePedal;
4166            }
4167        }
4168    
4169        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
4170            _3ewg->SetPos(36);
4171            LegatoSamples = _3ewg->ReadUint8(); // always 12
4172            _3ewg->SetPos(40);
4173            BypassUseController = _3ewg->ReadUint8();
4174            BypassKey = _3ewg->ReadUint8();
4175            BypassController = _3ewg->ReadUint8();
4176            ThresholdTime = _3ewg->ReadUint16();
4177            _3ewg->ReadInt16();
4178            ReleaseTime = _3ewg->ReadUint16();
4179            _3ewg->ReadInt16();
4180            KeyRange.low = _3ewg->ReadUint8();
4181            KeyRange.high = _3ewg->ReadUint8();
4182            _3ewg->SetPos(64);
4183            ReleaseTriggerKey = _3ewg->ReadUint8();
4184            AltSustain1Key = _3ewg->ReadUint8();
4185            AltSustain2Key = _3ewg->ReadUint8();
4186        }
4187    
4188        MidiRuleLegato::MidiRuleLegato() :
4189            LegatoSamples(12),
4190            BypassUseController(false),
4191            BypassKey(0),
4192            BypassController(1),
4193            ThresholdTime(20),
4194            ReleaseTime(20),
4195            ReleaseTriggerKey(0),
4196            AltSustain1Key(0),
4197            AltSustain2Key(0)
4198        {
4199            KeyRange.low = KeyRange.high = 0;
4200      }      }
 }  
4201    
4202        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
4203            pData[32] = 0;
4204            pData[33] = 16;
4205            pData[36] = LegatoSamples;
4206            pData[40] = BypassUseController;
4207            pData[41] = BypassKey;
4208            pData[42] = BypassController;
4209            store16(&pData[43], ThresholdTime);
4210            store16(&pData[47], ReleaseTime);
4211            pData[51] = KeyRange.low;
4212            pData[52] = KeyRange.high;
4213            pData[64] = ReleaseTriggerKey;
4214            pData[65] = AltSustain1Key;
4215            pData[66] = AltSustain2Key;
4216        }
4217    
4218        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4219            _3ewg->SetPos(36);
4220            Articulations = _3ewg->ReadUint8();
4221            int flags = _3ewg->ReadUint8();
4222            Polyphonic = flags & 8;
4223            Chained = flags & 4;
4224            Selector = (flags & 2) ? selector_controller :
4225                (flags & 1) ? selector_key_switch : selector_none;
4226            Patterns = _3ewg->ReadUint8();
4227            _3ewg->ReadUint8(); // chosen row
4228            _3ewg->ReadUint8(); // unknown
4229            _3ewg->ReadUint8(); // unknown
4230            _3ewg->ReadUint8(); // unknown
4231            KeySwitchRange.low = _3ewg->ReadUint8();
4232            KeySwitchRange.high = _3ewg->ReadUint8();
4233            Controller = _3ewg->ReadUint8();
4234            PlayRange.low = _3ewg->ReadUint8();
4235            PlayRange.high = _3ewg->ReadUint8();
4236    
4237            int n = std::min(int(Articulations), 32);
4238            for (int i = 0 ; i < n ; i++) {
4239                _3ewg->ReadString(pArticulations[i], 32);
4240            }
4241            _3ewg->SetPos(1072);
4242            n = std::min(int(Patterns), 32);
4243            for (int i = 0 ; i < n ; i++) {
4244                _3ewg->ReadString(pPatterns[i].Name, 16);
4245                pPatterns[i].Size = _3ewg->ReadUint8();
4246                _3ewg->Read(&pPatterns[i][0], 1, 32);
4247            }
4248        }
4249    
4250        MidiRuleAlternator::MidiRuleAlternator() :
4251            Articulations(0),
4252            Patterns(0),
4253            Selector(selector_none),
4254            Controller(0),
4255            Polyphonic(false),
4256            Chained(false)
4257        {
4258            PlayRange.low = PlayRange.high = 0;
4259            KeySwitchRange.low = KeySwitchRange.high = 0;
4260        }
4261    
4262        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4263            pData[32] = 3;
4264            pData[33] = 16;
4265            pData[36] = Articulations;
4266            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4267                (Selector == selector_controller ? 2 :
4268                 (Selector == selector_key_switch ? 1 : 0));
4269            pData[38] = Patterns;
4270    
4271            pData[43] = KeySwitchRange.low;
4272            pData[44] = KeySwitchRange.high;
4273            pData[45] = Controller;
4274            pData[46] = PlayRange.low;
4275            pData[47] = PlayRange.high;
4276    
4277            char* str = reinterpret_cast<char*>(pData);
4278            int pos = 48;
4279            int n = std::min(int(Articulations), 32);
4280            for (int i = 0 ; i < n ; i++, pos += 32) {
4281                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4282            }
4283    
4284            pos = 1072;
4285            n = std::min(int(Patterns), 32);
4286            for (int i = 0 ; i < n ; i++, pos += 49) {
4287                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4288                pData[pos + 16] = pPatterns[i].Size;
4289                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4290            }
4291        }
4292    
4293    // *************** Script ***************
4294    // *
4295    
4296        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4297            pGroup = group;
4298            pChunk = ckScri;
4299            if (ckScri) { // object is loaded from file ...
4300                // read header
4301                uint32_t headerSize = ckScri->ReadUint32();
4302                Compression = (Compression_t) ckScri->ReadUint32();
4303                Encoding    = (Encoding_t) ckScri->ReadUint32();
4304                Language    = (Language_t) ckScri->ReadUint32();
4305                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4306                crc         = ckScri->ReadUint32();
4307                uint32_t nameSize = ckScri->ReadUint32();
4308                Name.resize(nameSize, ' ');
4309                for (int i = 0; i < nameSize; ++i)
4310                    Name[i] = ckScri->ReadUint8();
4311                // to handle potential future extensions of the header
4312                ckScri->SetPos(sizeof(int32_t) + headerSize);
4313                // read actual script data
4314                uint32_t scriptSize = uint32_t(ckScri->GetSize() - ckScri->GetPos());
4315                data.resize(scriptSize);
4316                for (int i = 0; i < scriptSize; ++i)
4317                    data[i] = ckScri->ReadUint8();
4318            } else { // this is a new script object, so just initialize it as such ...
4319                Compression = COMPRESSION_NONE;
4320                Encoding = ENCODING_ASCII;
4321                Language = LANGUAGE_NKSP;
4322                Bypass   = false;
4323                crc      = 0;
4324                Name     = "Unnamed Script";
4325            }
4326        }
4327    
4328        Script::~Script() {
4329        }
4330    
4331        /**
4332         * Returns the current script (i.e. as source code) in text format.
4333         */
4334        String Script::GetScriptAsText() {
4335            String s;
4336            s.resize(data.size(), ' ');
4337            memcpy(&s[0], &data[0], data.size());
4338            return s;
4339        }
4340    
4341        /**
4342         * Replaces the current script with the new script source code text given
4343         * by @a text.
4344         *
4345         * @param text - new script source code
4346         */
4347        void Script::SetScriptAsText(const String& text) {
4348            data.resize(text.size());
4349            memcpy(&data[0], &text[0], text.size());
4350        }
4351    
4352        /**
4353         * Apply this script to the respective RIFF chunks. You have to call
4354         * File::Save() to make changes persistent.
4355         *
4356         * Usually there is absolutely no need to call this method explicitly.
4357         * It will be called automatically when File::Save() was called.
4358         *
4359         * @param pProgress - callback function for progress notification
4360         */
4361        void Script::UpdateChunks(progress_t* pProgress) {
4362            // recalculate CRC32 check sum
4363            __resetCRC(crc);
4364            __calculateCRC(&data[0], data.size(), crc);
4365            __finalizeCRC(crc);
4366            // make sure chunk exists and has the required size
4367            const file_offset_t chunkSize = (file_offset_t) 7*sizeof(int32_t) + Name.size() + data.size();
4368            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4369            else pChunk->Resize(chunkSize);
4370            // fill the chunk data to be written to disk
4371            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4372            int pos = 0;
4373            store32(&pData[pos], uint32_t(6*sizeof(int32_t) + Name.size())); // total header size
4374            pos += sizeof(int32_t);
4375            store32(&pData[pos], Compression);
4376            pos += sizeof(int32_t);
4377            store32(&pData[pos], Encoding);
4378            pos += sizeof(int32_t);
4379            store32(&pData[pos], Language);
4380            pos += sizeof(int32_t);
4381            store32(&pData[pos], Bypass ? 1 : 0);
4382            pos += sizeof(int32_t);
4383            store32(&pData[pos], crc);
4384            pos += sizeof(int32_t);
4385            store32(&pData[pos], (uint32_t) Name.size());
4386            pos += sizeof(int32_t);
4387            for (int i = 0; i < Name.size(); ++i, ++pos)
4388                pData[pos] = Name[i];
4389            for (int i = 0; i < data.size(); ++i, ++pos)
4390                pData[pos] = data[i];
4391        }
4392    
4393        /**
4394         * Move this script from its current ScriptGroup to another ScriptGroup
4395         * given by @a pGroup.
4396         *
4397         * @param pGroup - script's new group
4398         */
4399        void Script::SetGroup(ScriptGroup* pGroup) {
4400            if (this->pGroup == pGroup) return;
4401            if (pChunk)
4402                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4403            this->pGroup = pGroup;
4404        }
4405    
4406        /**
4407         * Returns the script group this script currently belongs to. Each script
4408         * is a member of exactly one ScriptGroup.
4409         *
4410         * @returns current script group
4411         */
4412        ScriptGroup* Script::GetGroup() const {
4413            return pGroup;
4414        }
4415    
4416        /**
4417         * Make a (semi) deep copy of the Script object given by @a orig
4418         * and assign it to this object. Note: the ScriptGroup this Script
4419         * object belongs to remains untouched by this call.
4420         *
4421         * @param orig - original Script object to be copied from
4422         */
4423        void Script::CopyAssign(const Script* orig) {
4424            Name        = orig->Name;
4425            Compression = orig->Compression;
4426            Encoding    = orig->Encoding;
4427            Language    = orig->Language;
4428            Bypass      = orig->Bypass;
4429            data        = orig->data;
4430        }
4431    
4432        void Script::RemoveAllScriptReferences() {
4433            File* pFile = pGroup->pFile;
4434            for (int i = 0; pFile->GetInstrument(i); ++i) {
4435                Instrument* instr = pFile->GetInstrument(i);
4436                instr->RemoveScript(this);
4437            }
4438        }
4439    
4440    // *************** ScriptGroup ***************
4441    // *
4442    
4443        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4444            pFile = file;
4445            pList = lstRTIS;
4446            pScripts = NULL;
4447            if (lstRTIS) {
4448                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4449                ::LoadString(ckName, Name);
4450            } else {
4451                Name = "Default Group";
4452            }
4453        }
4454    
4455        ScriptGroup::~ScriptGroup() {
4456            if (pScripts) {
4457                std::list<Script*>::iterator iter = pScripts->begin();
4458                std::list<Script*>::iterator end  = pScripts->end();
4459                while (iter != end) {
4460                    delete *iter;
4461                    ++iter;
4462                }
4463                delete pScripts;
4464            }
4465        }
4466    
4467        /**
4468         * Apply this script group to the respective RIFF chunks. You have to call
4469         * File::Save() to make changes persistent.
4470         *
4471         * Usually there is absolutely no need to call this method explicitly.
4472         * It will be called automatically when File::Save() was called.
4473         *
4474         * @param pProgress - callback function for progress notification
4475         */
4476        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4477            if (pScripts) {
4478                if (!pList)
4479                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4480    
4481                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4482                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4483    
4484                for (std::list<Script*>::iterator it = pScripts->begin();
4485                     it != pScripts->end(); ++it)
4486                {
4487                    (*it)->UpdateChunks(pProgress);
4488                }
4489            }
4490        }
4491    
4492        /** @brief Get instrument script.
4493         *
4494         * Returns the real-time instrument script with the given index.
4495         *
4496         * @param index - number of the sought script (0..n)
4497         * @returns sought script or NULL if there's no such script
4498         */
4499        Script* ScriptGroup::GetScript(uint index) {
4500            if (!pScripts) LoadScripts();
4501            std::list<Script*>::iterator it = pScripts->begin();
4502            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4503                if (i == index) return *it;
4504            return NULL;
4505        }
4506    
4507        /** @brief Add new instrument script.
4508         *
4509         * Adds a new real-time instrument script to the file. The script is not
4510         * actually used / executed unless it is referenced by an instrument to be
4511         * used. This is similar to samples, which you can add to a file, without
4512         * an instrument necessarily actually using it.
4513         *
4514         * You have to call Save() to make this persistent to the file.
4515         *
4516         * @return new empty script object
4517         */
4518        Script* ScriptGroup::AddScript() {
4519            if (!pScripts) LoadScripts();
4520            Script* pScript = new Script(this, NULL);
4521            pScripts->push_back(pScript);
4522            return pScript;
4523        }
4524    
4525        /** @brief Delete an instrument script.
4526         *
4527         * This will delete the given real-time instrument script. References of
4528         * instruments that are using that script will be removed accordingly.
4529         *
4530         * You have to call Save() to make this persistent to the file.
4531         *
4532         * @param pScript - script to delete
4533         * @throws gig::Exception if given script could not be found
4534         */
4535        void ScriptGroup::DeleteScript(Script* pScript) {
4536            if (!pScripts) LoadScripts();
4537            std::list<Script*>::iterator iter =
4538                find(pScripts->begin(), pScripts->end(), pScript);
4539            if (iter == pScripts->end())
4540                throw gig::Exception("Could not delete script, could not find given script");
4541            pScripts->erase(iter);
4542            pScript->RemoveAllScriptReferences();
4543            if (pScript->pChunk)
4544                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4545            delete pScript;
4546        }
4547    
4548        void ScriptGroup::LoadScripts() {
4549            if (pScripts) return;
4550            pScripts = new std::list<Script*>;
4551            if (!pList) return;
4552    
4553            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4554                 ck = pList->GetNextSubChunk())
4555            {
4556                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4557                    pScripts->push_back(new Script(this, ck));
4558                }
4559            }
4560        }
4561    
4562  // *************** Instrument ***************  // *************** Instrument ***************
4563  // *  // *
# Line 2964  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4575  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4575          EffectSend = 0;          EffectSend = 0;
4576          Attenuation = 0;          Attenuation = 0;
4577          FineTune = 0;          FineTune = 0;
4578          PitchbendRange = 0;          PitchbendRange = 2;
4579          PianoReleaseMode = false;          PianoReleaseMode = false;
4580          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
4581          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
4582          pMidiRules = new MidiRule*[3];          pMidiRules = new MidiRule*[3];
4583          pMidiRules[0] = NULL;          pMidiRules[0] = NULL;
4584            pScriptRefs = NULL;
4585    
4586          // Loading          // Loading
4587          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2992  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4604  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4604                      uint8_t id1 = _3ewg->ReadUint8();                      uint8_t id1 = _3ewg->ReadUint8();
4605                      uint8_t id2 = _3ewg->ReadUint8();                      uint8_t id2 = _3ewg->ReadUint8();
4606    
4607                      if (id1 == 4 && id2 == 16) {                      if (id2 == 16) {
4608                          pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);                          if (id1 == 4) {
4609                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4610                            } else if (id1 == 0) {
4611                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4612                            } else if (id1 == 3) {
4613                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4614                            } else {
4615                                pMidiRules[i++] = new MidiRuleUnknown;
4616                            }
4617                        }
4618                        else if (id1 != 0 || id2 != 0) {
4619                            pMidiRules[i++] = new MidiRuleUnknown;
4620                      }                      }
4621                      //TODO: all the other types of rules                      //TODO: all the other types of rules
4622    
# Line 3019  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4642  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4642              }              }
4643          }          }
4644    
4645            // own gig format extensions
4646            RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4647            if (lst3LS) {
4648                RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4649                if (ckSCSL) {
4650                    int headerSize = ckSCSL->ReadUint32();
4651                    int slotCount  = ckSCSL->ReadUint32();
4652                    if (slotCount) {
4653                        int slotSize  = ckSCSL->ReadUint32();
4654                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4655                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4656                        for (int i = 0; i < slotCount; ++i) {
4657                            _ScriptPooolEntry e;
4658                            e.fileOffset = ckSCSL->ReadUint32();
4659                            e.bypass     = ckSCSL->ReadUint32() & 1;
4660                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4661                            scriptPoolFileOffsets.push_back(e);
4662                        }
4663                    }
4664                }
4665            }
4666    
4667          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4668      }      }
4669    
# Line 3035  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4680  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4680      }      }
4681    
4682      Instrument::~Instrument() {      Instrument::~Instrument() {
4683            for (int i = 0 ; pMidiRules[i] ; i++) {
4684                delete pMidiRules[i];
4685            }
4686          delete[] pMidiRules;          delete[] pMidiRules;
4687            if (pScriptRefs) delete pScriptRefs;
4688      }      }
4689    
4690      /**      /**
# Line 3045  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4694  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4694       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
4695       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
4696       *       *
4697         * @param pProgress - callback function for progress notification
4698       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
4699       */       */
4700      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
4701          // first update base classes' chunks          // first update base classes' chunks
4702          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks(pProgress);
4703    
4704          // update Regions' chunks          // update Regions' chunks
4705          {          {
4706              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
4707              RegionList::iterator end  = pRegions->end();              RegionList::iterator end  = pRegions->end();
4708              for (; iter != end; ++iter)              for (; iter != end; ++iter)
4709                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
4710          }          }
4711    
4712          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
# Line 3082  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4732  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4732                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
4733          pData[10] = dimkeystart;          pData[10] = dimkeystart;
4734          pData[11] = DimensionKeyRange.high;          pData[11] = DimensionKeyRange.high;
4735    
4736            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4737                pData[32] = 0;
4738                pData[33] = 0;
4739            } else {
4740                for (int i = 0 ; pMidiRules[i] ; i++) {
4741                    pMidiRules[i]->UpdateChunks(pData);
4742                }
4743            }
4744    
4745            // own gig format extensions
4746           if (ScriptSlotCount()) {
4747               // make sure we have converted the original loaded script file
4748               // offsets into valid Script object pointers
4749               LoadScripts();
4750    
4751               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4752               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4753               const int slotCount = (int) pScriptRefs->size();
4754               const int headerSize = 3 * sizeof(uint32_t);
4755               const int slotSize  = 2 * sizeof(uint32_t);
4756               const int totalChunkSize = headerSize + slotCount * slotSize;
4757               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4758               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4759               else ckSCSL->Resize(totalChunkSize);
4760               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4761               int pos = 0;
4762               store32(&pData[pos], headerSize);
4763               pos += sizeof(uint32_t);
4764               store32(&pData[pos], slotCount);
4765               pos += sizeof(uint32_t);
4766               store32(&pData[pos], slotSize);
4767               pos += sizeof(uint32_t);
4768               for (int i = 0; i < slotCount; ++i) {
4769                   // arbitrary value, the actual file offset will be updated in
4770                   // UpdateScriptFileOffsets() after the file has been resized
4771                   int bogusFileOffset = 0;
4772                   store32(&pData[pos], bogusFileOffset);
4773                   pos += sizeof(uint32_t);
4774                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4775                   pos += sizeof(uint32_t);
4776               }
4777           } else {
4778               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4779               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4780               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4781           }
4782        }
4783    
4784        void Instrument::UpdateScriptFileOffsets() {
4785           // own gig format extensions
4786           if (pScriptRefs && pScriptRefs->size() > 0) {
4787               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4788               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4789               const int slotCount = (int) pScriptRefs->size();
4790               const int headerSize = 3 * sizeof(uint32_t);
4791               ckSCSL->SetPos(headerSize);
4792               for (int i = 0; i < slotCount; ++i) {
4793                   uint32_t fileOffset = uint32_t(
4794                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4795                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4796                        CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize())
4797                   );
4798                   ckSCSL->WriteUint32(&fileOffset);
4799                   // jump over flags entry (containing the bypass flag)
4800                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4801               }
4802           }        
4803      }      }
4804    
4805      /**      /**
# Line 3136  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4854  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4854          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4855          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
4856          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
4857          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
4858          // update Region key table for fast lookup          // update Region key table for fast lookup
4859          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4860          // done          // done
# Line 3151  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4869  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4869      }      }
4870    
4871      /**      /**
4872         * Move this instrument at the position before @arg dst.
4873         *
4874         * This method can be used to reorder the sequence of instruments in a
4875         * .gig file. This might be helpful especially on large .gig files which
4876         * contain a large number of instruments within the same .gig file. So
4877         * grouping such instruments to similar ones, can help to keep track of them
4878         * when working with such complex .gig files.
4879         *
4880         * When calling this method, this instrument will be removed from in its
4881         * current position in the instruments list and moved to the requested
4882         * target position provided by @param dst. You may also pass NULL as
4883         * argument to this method, in that case this intrument will be moved to the
4884         * very end of the .gig file's instrument list.
4885         *
4886         * You have to call Save() to make the order change persistent to the .gig
4887         * file.
4888         *
4889         * Currently this method is limited to moving the instrument within the same
4890         * .gig file. Trying to move it to another .gig file by calling this method
4891         * will throw an exception.
4892         *
4893         * @param dst - destination instrument at which this instrument will be
4894         *              moved to, or pass NULL for moving to end of list
4895         * @throw gig::Exception if this instrument and target instrument are not
4896         *                       part of the same file
4897         */
4898        void Instrument::MoveTo(Instrument* dst) {
4899            if (dst && GetParent() != dst->GetParent())
4900                throw Exception(
4901                    "gig::Instrument::MoveTo() can only be used for moving within "
4902                    "the same gig file."
4903                );
4904    
4905            File* pFile = (File*) GetParent();
4906    
4907            // move this instrument within the instrument list
4908            {
4909                File::InstrumentList& list = *pFile->pInstruments;
4910    
4911                File::InstrumentList::iterator itFrom =
4912                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4913    
4914                File::InstrumentList::iterator itTo =
4915                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4916    
4917                list.splice(itTo, list, itFrom);
4918            }
4919    
4920            // move the instrument's actual list RIFF chunk appropriately
4921            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4922            lstCkInstruments->MoveSubChunk(
4923                this->pCkInstrument,
4924                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4925            );
4926        }
4927    
4928        /**
4929       * Returns a MIDI rule of the instrument.       * Returns a MIDI rule of the instrument.
4930       *       *
4931       * 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 3164  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4939  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4939          return pMidiRules[i];          return pMidiRules[i];
4940      }      }
4941    
4942        /**
4943         * Adds the "controller trigger" MIDI rule to the instrument.
4944         *
4945         * @returns the new MIDI rule
4946         */
4947        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4948            delete pMidiRules[0];
4949            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4950            pMidiRules[0] = r;
4951            pMidiRules[1] = 0;
4952            return r;
4953        }
4954    
4955        /**
4956         * Adds the legato MIDI rule to the instrument.
4957         *
4958         * @returns the new MIDI rule
4959         */
4960        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4961            delete pMidiRules[0];
4962            MidiRuleLegato* r = new MidiRuleLegato;
4963            pMidiRules[0] = r;
4964            pMidiRules[1] = 0;
4965            return r;
4966        }
4967    
4968        /**
4969         * Adds the alternator MIDI rule to the instrument.
4970         *
4971         * @returns the new MIDI rule
4972         */
4973        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4974            delete pMidiRules[0];
4975            MidiRuleAlternator* r = new MidiRuleAlternator;
4976            pMidiRules[0] = r;
4977            pMidiRules[1] = 0;
4978            return r;
4979        }
4980    
4981        /**
4982         * Deletes a MIDI rule from the instrument.
4983         *
4984         * @param i - MIDI rule number
4985         */
4986        void Instrument::DeleteMidiRule(int i) {
4987            delete pMidiRules[i];
4988            pMidiRules[i] = 0;
4989        }
4990    
4991        void Instrument::LoadScripts() {
4992            if (pScriptRefs) return;
4993            pScriptRefs = new std::vector<_ScriptPooolRef>;
4994            if (scriptPoolFileOffsets.empty()) return;
4995            File* pFile = (File*) GetParent();
4996            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4997                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4998                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4999                    ScriptGroup* group = pFile->GetScriptGroup(i);
5000                    for (uint s = 0; group->GetScript(s); ++s) {
5001                        Script* script = group->GetScript(s);
5002                        if (script->pChunk) {
5003                            uint32_t offset = uint32_t(
5004                                script->pChunk->GetFilePos() -
5005                                script->pChunk->GetPos() -
5006                                CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize())
5007                            );
5008                            if (offset == soughtOffset)
5009                            {
5010                                _ScriptPooolRef ref;
5011                                ref.script = script;
5012                                ref.bypass = scriptPoolFileOffsets[k].bypass;
5013                                pScriptRefs->push_back(ref);
5014                                break;
5015                            }
5016                        }
5017                    }
5018                }
5019            }
5020            // we don't need that anymore
5021            scriptPoolFileOffsets.clear();
5022        }
5023    
5024        /** @brief Get instrument script (gig format extension).
5025         *
5026         * Returns the real-time instrument script of instrument script slot
5027         * @a index.
5028         *
5029         * @note This is an own format extension which did not exist i.e. in the
5030         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5031         * gigedit.
5032         *
5033         * @param index - instrument script slot index
5034         * @returns script or NULL if index is out of bounds
5035         */
5036        Script* Instrument::GetScriptOfSlot(uint index) {
5037            LoadScripts();
5038            if (index >= pScriptRefs->size()) return NULL;
5039            return pScriptRefs->at(index).script;
5040        }
5041    
5042        /** @brief Add new instrument script slot (gig format extension).
5043         *
5044         * Add the given real-time instrument script reference to this instrument,
5045         * which shall be executed by the sampler for for this instrument. The
5046         * script will be added to the end of the script list of this instrument.
5047         * The positions of the scripts in the Instrument's Script list are
5048         * relevant, because they define in which order they shall be executed by
5049         * the sampler. For this reason it is also legal to add the same script
5050         * twice to an instrument, for example you might have a script called
5051         * "MyFilter" which performs an event filter task, and you might have
5052         * another script called "MyNoteTrigger" which triggers new notes, then you
5053         * might for example have the following list of scripts on the instrument:
5054         *
5055         * 1. Script "MyFilter"
5056         * 2. Script "MyNoteTrigger"
5057         * 3. Script "MyFilter"
5058         *
5059         * Which would make sense, because the 2nd script launched new events, which
5060         * you might need to filter as well.
5061         *
5062         * There are two ways to disable / "bypass" scripts. You can either disable
5063         * a script locally for the respective script slot on an instrument (i.e. by
5064         * passing @c false to the 2nd argument of this method, or by calling
5065         * SetScriptBypassed()). Or you can disable a script globally for all slots
5066         * and all instruments by setting Script::Bypass.
5067         *
5068         * @note This is an own format extension which did not exist i.e. in the
5069         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5070         * gigedit.
5071         *
5072         * @param pScript - script that shall be executed for this instrument
5073         * @param bypass  - if enabled, the sampler shall skip executing this
5074         *                  script (in the respective list position)
5075         * @see SetScriptBypassed()
5076         */
5077        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
5078            LoadScripts();
5079            _ScriptPooolRef ref = { pScript, bypass };
5080            pScriptRefs->push_back(ref);
5081        }
5082    
5083        /** @brief Flip two script slots with each other (gig format extension).
5084         *
5085         * Swaps the position of the two given scripts in the Instrument's Script
5086         * list. The positions of the scripts in the Instrument's Script list are
5087         * relevant, because they define in which order they shall be executed by
5088         * the sampler.
5089         *
5090         * @note This is an own format extension which did not exist i.e. in the
5091         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5092         * gigedit.
5093         *
5094         * @param index1 - index of the first script slot to swap
5095         * @param index2 - index of the second script slot to swap
5096         */
5097        void Instrument::SwapScriptSlots(uint index1, uint index2) {
5098            LoadScripts();
5099            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
5100                return;
5101            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
5102            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
5103            (*pScriptRefs)[index2] = tmp;
5104        }
5105    
5106        /** @brief Remove script slot.
5107         *
5108         * Removes the script slot with the given slot index.
5109         *
5110         * @param index - index of script slot to remove
5111         */
5112        void Instrument::RemoveScriptSlot(uint index) {
5113            LoadScripts();
5114            if (index >= pScriptRefs->size()) return;
5115            pScriptRefs->erase( pScriptRefs->begin() + index );
5116        }
5117    
5118        /** @brief Remove reference to given Script (gig format extension).
5119         *
5120         * This will remove all script slots on the instrument which are referencing
5121         * the given script.
5122         *
5123         * @note This is an own format extension which did not exist i.e. in the
5124         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5125         * gigedit.
5126         *
5127         * @param pScript - script reference to remove from this instrument
5128         * @see RemoveScriptSlot()
5129         */
5130        void Instrument::RemoveScript(Script* pScript) {
5131            LoadScripts();
5132            for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5133                if ((*pScriptRefs)[i].script == pScript) {
5134                    pScriptRefs->erase( pScriptRefs->begin() + i );
5135                }
5136            }
5137        }
5138    
5139        /** @brief Instrument's amount of script slots.
5140         *
5141         * This method returns the amount of script slots this instrument currently
5142         * uses.
5143         *
5144         * A script slot is a reference of a real-time instrument script to be
5145         * executed by the sampler. The scripts will be executed by the sampler in
5146         * sequence of the slots. One (same) script may be referenced multiple
5147         * times in different slots.
5148         *
5149         * @note This is an own format extension which did not exist i.e. in the
5150         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5151         * gigedit.
5152         */
5153        uint Instrument::ScriptSlotCount() const {
5154            return uint(pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size());
5155        }
5156    
5157        /** @brief Whether script execution shall be skipped.
5158         *
5159         * Defines locally for the Script reference slot in the Instrument's Script
5160         * list, whether the script shall be skipped by the sampler regarding
5161         * execution.
5162         *
5163         * It is also possible to ignore exeuction of the script globally, for all
5164         * slots and for all instruments by setting Script::Bypass.
5165         *
5166         * @note This is an own format extension which did not exist i.e. in the
5167         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5168         * gigedit.
5169         *
5170         * @param index - index of the script slot on this instrument
5171         * @see Script::Bypass
5172         */
5173        bool Instrument::IsScriptSlotBypassed(uint index) {
5174            if (index >= ScriptSlotCount()) return false;
5175            return pScriptRefs ? pScriptRefs->at(index).bypass
5176                               : scriptPoolFileOffsets.at(index).bypass;
5177            
5178        }
5179    
5180        /** @brief Defines whether execution shall be skipped.
5181         *
5182         * You can call this method to define locally whether or whether not the
5183         * given script slot shall be executed by the sampler.
5184         *
5185         * @note This is an own format extension which did not exist i.e. in the
5186         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5187         * gigedit.
5188         *
5189         * @param index - script slot index on this instrument
5190         * @param bBypass - if true, the script slot will be skipped by the sampler
5191         * @see Script::Bypass
5192         */
5193        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
5194            if (index >= ScriptSlotCount()) return;
5195            if (pScriptRefs)
5196                pScriptRefs->at(index).bypass = bBypass;
5197            else
5198                scriptPoolFileOffsets.at(index).bypass = bBypass;
5199        }
5200    
5201        /**
5202         * Make a (semi) deep copy of the Instrument object given by @a orig
5203         * and assign it to this object.
5204         *
5205         * Note that all sample pointers referenced by @a orig are simply copied as
5206         * memory address. Thus the respective samples are shared, not duplicated!
5207         *
5208         * @param orig - original Instrument object to be copied from
5209         */
5210        void Instrument::CopyAssign(const Instrument* orig) {
5211            CopyAssign(orig, NULL);
5212        }
5213            
5214        /**
5215         * Make a (semi) deep copy of the Instrument object given by @a orig
5216         * and assign it to this object.
5217         *
5218         * @param orig - original Instrument object to be copied from
5219         * @param mSamples - crosslink map between the foreign file's samples and
5220         *                   this file's samples
5221         */
5222        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
5223            // handle base class
5224            // (without copying DLS region stuff)
5225            DLS::Instrument::CopyAssignCore(orig);
5226            
5227            // handle own member variables
5228            Attenuation = orig->Attenuation;
5229            EffectSend = orig->EffectSend;
5230            FineTune = orig->FineTune;
5231            PitchbendRange = orig->PitchbendRange;
5232            PianoReleaseMode = orig->PianoReleaseMode;
5233            DimensionKeyRange = orig->DimensionKeyRange;
5234            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5235            pScriptRefs = orig->pScriptRefs;
5236            
5237            // free old midi rules
5238            for (int i = 0 ; pMidiRules[i] ; i++) {
5239                delete pMidiRules[i];
5240            }
5241            //TODO: MIDI rule copying
5242            pMidiRules[0] = NULL;
5243            
5244            // delete all old regions
5245            while (Regions) DeleteRegion(GetFirstRegion());
5246            // create new regions and copy them from original
5247            {
5248                RegionList::const_iterator it = orig->pRegions->begin();
5249                for (int i = 0; i < orig->Regions; ++i, ++it) {
5250                    Region* dstRgn = AddRegion();
5251                    //NOTE: Region does semi-deep copy !
5252                    dstRgn->CopyAssign(
5253                        static_cast<gig::Region*>(*it),
5254                        mSamples
5255                    );
5256                }
5257            }
5258    
5259            UpdateRegionKeyTable();
5260        }
5261    
5262    
5263  // *************** Group ***************  // *************** Group ***************
5264  // *  // *
# Line 3192  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5287  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5287       *       *
5288       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
5289       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
5290         *
5291         * @param pProgress - callback function for progress notification
5292       */       */
5293      void Group::UpdateChunks() {      void Group::UpdateChunks(progress_t* pProgress) {
5294          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
5295          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5296          if (!_3gri) {          if (!_3gri) {
# Line 3323  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5420  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5420          bAutoLoad = true;          bAutoLoad = true;
5421          *pVersion = VERSION_3;          *pVersion = VERSION_3;
5422          pGroups = NULL;          pGroups = NULL;
5423            pScriptGroups = NULL;
5424          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5425          pInfo->ArchivalLocation = String(256, ' ');          pInfo->ArchivalLocation = String(256, ' ');
5426    
# Line 3338  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5436  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5436      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5437          bAutoLoad = true;          bAutoLoad = true;
5438          pGroups = NULL;          pGroups = NULL;
5439            pScriptGroups = NULL;
5440          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5441      }      }
5442    
# Line 3351  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5450  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5450              }              }
5451              delete pGroups;              delete pGroups;
5452          }          }
5453            if (pScriptGroups) {
5454                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5455                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5456                while (iter != end) {
5457                    delete *iter;
5458                    ++iter;
5459                }
5460                delete pScriptGroups;
5461            }
5462      }      }
5463    
5464      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 3365  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5473  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5473          SamplesIterator++;          SamplesIterator++;
5474          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5475      }      }
5476        
5477        /**
5478         * Returns Sample object of @a index.
5479         *
5480         * @returns sample object or NULL if index is out of bounds
5481         */
5482        Sample* File::GetSample(uint index) {
5483            if (!pSamples) LoadSamples();
5484            if (!pSamples) return NULL;
5485            DLS::File::SampleList::iterator it = pSamples->begin();
5486            for (int i = 0; i < index; ++i) {
5487                ++it;
5488                if (it == pSamples->end()) return NULL;
5489            }
5490            if (it == pSamples->end()) return NULL;
5491            return static_cast<gig::Sample*>( *it );
5492        }
5493    
5494      /** @brief Add a new sample.      /** @brief Add a new sample.
5495       *       *
# Line 3442  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5567  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5567          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5568    
5569          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5570            // (only for old gig files < 2 GB)
5571          int lastFileNo = 0;          int lastFileNo = 0;
5572          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5573              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5574                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5575                }
5576          }          }
5577          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5578          int nameLen = name.length();          int nameLen = (int) name.length();
5579          char suffix[6];          char suffix[6];
5580          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5581    
5582          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5583              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5584              if (wvpl) {              if (wvpl) {
5585                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5586                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5587                  while (wave) {                  while (wave) {
5588                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 3462  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5590  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5590                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5591                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5592    
5593                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5594                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5595    
5596                          iSampleIndex++;                          iSampleIndex++;
5597                      }                      }
# Line 3562  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5690  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5690         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
5691         return pInstrument;         return pInstrument;
5692      }      }
5693        
5694        /** @brief Add a duplicate of an existing instrument.
5695         *
5696         * Duplicates the instrument definition given by @a orig and adds it
5697         * to this file. This allows in an instrument editor application to
5698         * easily create variations of an instrument, which will be stored in
5699         * the same .gig file, sharing i.e. the same samples.
5700         *
5701         * Note that all sample pointers referenced by @a orig are simply copied as
5702         * memory address. Thus the respective samples are shared, not duplicated!
5703         *
5704         * You have to call Save() to make this persistent to the file.
5705         *
5706         * @param orig - original instrument to be copied
5707         * @returns duplicated copy of the given instrument
5708         */
5709        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
5710            Instrument* instr = AddInstrument();
5711            instr->CopyAssign(orig);
5712            return instr;
5713        }
5714        
5715        /** @brief Add content of another existing file.
5716         *
5717         * Duplicates the samples, groups and instruments of the original file
5718         * given by @a pFile and adds them to @c this File. In case @c this File is
5719         * a new one that you haven't saved before, then you have to call
5720         * SetFileName() before calling AddContentOf(), because this method will
5721         * automatically save this file during operation, which is required for
5722         * writing the sample waveform data by disk streaming.
5723         *
5724         * @param pFile - original file whose's content shall be copied from
5725         */
5726        void File::AddContentOf(File* pFile) {
5727            static int iCallCount = -1;
5728            iCallCount++;
5729            std::map<Group*,Group*> mGroups;
5730            std::map<Sample*,Sample*> mSamples;
5731            
5732            // clone sample groups
5733            for (int i = 0; pFile->GetGroup(i); ++i) {
5734                Group* g = AddGroup();
5735                g->Name =
5736                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5737                mGroups[pFile->GetGroup(i)] = g;
5738            }
5739            
5740            // clone samples (not waveform data here yet)
5741            for (int i = 0; pFile->GetSample(i); ++i) {
5742                Sample* s = AddSample();
5743                s->CopyAssignMeta(pFile->GetSample(i));
5744                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5745                mSamples[pFile->GetSample(i)] = s;
5746            }
5747    
5748            // clone script groups and their scripts
5749            for (int iGroup = 0; pFile->GetScriptGroup(iGroup); ++iGroup) {
5750                ScriptGroup* sg = pFile->GetScriptGroup(iGroup);
5751                ScriptGroup* dg = AddScriptGroup();
5752                dg->Name = "COPY" + ToString(iCallCount) + "_" + sg->Name;
5753                for (int iScript = 0; sg->GetScript(iScript); ++iScript) {
5754                    Script* ss = sg->GetScript(iScript);
5755                    Script* ds = dg->AddScript();
5756                    ds->CopyAssign(ss);
5757                }
5758            }
5759    
5760            //BUG: For some reason this method only works with this additional
5761            //     Save() call in between here.
5762            //
5763            // Important: The correct one of the 2 Save() methods has to be called
5764            // here, depending on whether the file is completely new or has been
5765            // saved to disk already, otherwise it will result in data corruption.
5766            if (pRIFF->IsNew())
5767                Save(GetFileName());
5768            else
5769                Save();
5770            
5771            // clone instruments
5772            // (passing the crosslink table here for the cloned samples)
5773            for (int i = 0; pFile->GetInstrument(i); ++i) {
5774                Instrument* instr = AddInstrument();
5775                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5776            }
5777            
5778            // Mandatory: file needs to be saved to disk at this point, so this
5779            // file has the correct size and data layout for writing the samples'
5780            // waveform data to disk.
5781            Save();
5782            
5783            // clone samples' waveform data
5784            // (using direct read & write disk streaming)
5785            for (int i = 0; pFile->GetSample(i); ++i) {
5786                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5787            }
5788        }
5789    
5790      /** @brief Delete an instrument.      /** @brief Delete an instrument.
5791       *       *
# Line 3617  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5841  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5841          if (!_3crc) return;          if (!_3crc) return;
5842    
5843          // get the index of the sample          // get the index of the sample
5844          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;  
             }  
         }  
5845          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");
5846    
5847          // write the CRC-32 checksum to disk          // write the CRC-32 checksum to disk
5848          _3crc->SetPos(iWaveIndex * 8);          _3crc->SetPos(iWaveIndex * 8);
5849          uint32_t tmp = 1;          uint32_t one = 1;
5850          _3crc->WriteUint32(&tmp); // unknown, always 1?          _3crc->WriteUint32(&one); // always 1
5851          _3crc->WriteUint32(&crc);          _3crc->WriteUint32(&crc);
5852      }      }
5853    
5854        uint32_t File::GetSampleChecksum(Sample* pSample) {
5855            // get the index of the sample
5856            int iWaveIndex = GetWaveTableIndexOf(pSample);
5857            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5858    
5859            return GetSampleChecksumByIndex(iWaveIndex);
5860        }
5861    
5862        uint32_t File::GetSampleChecksumByIndex(int index) {
5863            if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5864    
5865            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5866            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5867            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5868            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5869    
5870            // read the CRC-32 checksum directly from disk
5871            size_t pos = index * 8;
5872            if (pos + 8 > _3crc->GetNewSize())
5873                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5874    
5875            uint32_t one = load32(&pData[pos]); // always 1
5876            if (one != 1)
5877                throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5878    
5879            return load32(&pData[pos+4]);
5880        }
5881    
5882        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5883            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5884            File::SampleList::iterator iter = pSamples->begin();
5885            File::SampleList::iterator end  = pSamples->end();
5886            for (int index = 0; iter != end; ++iter, ++index)
5887                if (*iter == pSample)
5888                    return index;
5889            return -1;
5890        }
5891    
5892        /**
5893         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5894         * the CRC32 check sums of all samples' raw wave data.
5895         *
5896         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5897         */
5898        bool File::VerifySampleChecksumTable() {
5899            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5900            if (!_3crc) return false;
5901            if (_3crc->GetNewSize() <= 0) return false;
5902            if (_3crc->GetNewSize() % 8) return false;
5903            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5904            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5905    
5906            const file_offset_t n = _3crc->GetNewSize() / 8;
5907    
5908            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5909            if (!pData) return false;
5910    
5911            for (file_offset_t i = 0; i < n; ++i) {
5912                uint32_t one = pData[i*2];
5913                if (one != 1) return false;
5914            }
5915    
5916            return true;
5917        }
5918    
5919        /**
5920         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5921         * file's checksum table with those new checksums. This might usually
5922         * just be necessary if the checksum table was damaged.
5923         *
5924         * @e IMPORTANT: The current implementation of this method only works
5925         * with files that have not been modified since it was loaded, because
5926         * it expects that no externally caused file structure changes are
5927         * required!
5928         *
5929         * Due to the expectation above, this method is currently protected
5930         * and actually only used by the command line tool "gigdump" yet.
5931         *
5932         * @returns true if Save() is required to be called after this call,
5933         *          false if no further action is required
5934         */
5935        bool File::RebuildSampleChecksumTable() {
5936            // make sure sample chunks were scanned
5937            if (!pSamples) GetFirstSample();
5938    
5939            bool bRequiresSave = false;
5940    
5941            // make sure "3CRC" chunk exists with required size
5942            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5943            if (!_3crc) {
5944                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5945                // the order of einf and 3crc is not the same in v2 and v3
5946                RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5947                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5948                bRequiresSave = true;
5949            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5950                _3crc->Resize(pSamples->size() * 8);
5951                bRequiresSave = true;
5952            }
5953    
5954            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5955                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5956                {
5957                    File::SampleList::iterator iter = pSamples->begin();
5958                    File::SampleList::iterator end  = pSamples->end();
5959                    for (; iter != end; ++iter) {
5960                        gig::Sample* pSample = (gig::Sample*) *iter;
5961                        int index = GetWaveTableIndexOf(pSample);
5962                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5963                        pData[index*2]   = 1; // always 1
5964                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5965                    }
5966                }
5967            } else { // no file structure changes necessary, so directly write to disk and we are done ...
5968                // make sure file is in write mode
5969                pRIFF->SetMode(RIFF::stream_mode_read_write);
5970                {
5971                    File::SampleList::iterator iter = pSamples->begin();
5972                    File::SampleList::iterator end  = pSamples->end();
5973                    for (; iter != end; ++iter) {
5974                        gig::Sample* pSample = (gig::Sample*) *iter;
5975                        int index = GetWaveTableIndexOf(pSample);
5976                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5977                        pSample->crc  = pSample->CalculateWaveDataChecksum();
5978                        SetSampleChecksum(pSample, pSample->crc);
5979                    }
5980                }
5981            }
5982    
5983            return bRequiresSave;
5984        }
5985    
5986      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
5987          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5988          // there must always be at least one group          // there must always be at least one group
# Line 3664  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6012  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6012          return NULL;          return NULL;
6013      }      }
6014    
6015        /**
6016         * Returns the group with the given group name.
6017         *
6018         * Note: group names don't have to be unique in the gig format! So there
6019         * can be multiple groups with the same name. This method will simply
6020         * return the first group found with the given name.
6021         *
6022         * @param name - name of the sought group
6023         * @returns sought group or NULL if there's no group with that name
6024         */
6025        Group* File::GetGroup(String name) {
6026            if (!pGroups) LoadGroups();
6027            GroupsIterator = pGroups->begin();
6028            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
6029                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
6030            return NULL;
6031        }
6032    
6033      Group* File::AddGroup() {      Group* File::AddGroup() {
6034          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
6035          // there must always be at least one group          // there must always be at least one group
# Line 3744  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6110  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6110          }          }
6111      }      }
6112    
6113        /** @brief Get instrument script group (by index).
6114         *
6115         * Returns the real-time instrument script group with the given index.
6116         *
6117         * @param index - number of the sought group (0..n)
6118         * @returns sought script group or NULL if there's no such group
6119         */
6120        ScriptGroup* File::GetScriptGroup(uint index) {
6121            if (!pScriptGroups) LoadScriptGroups();
6122            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6123            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
6124                if (i == index) return *it;
6125            return NULL;
6126        }
6127    
6128        /** @brief Get instrument script group (by name).
6129         *
6130         * Returns the first real-time instrument script group found with the given
6131         * group name. Note that group names may not necessarily be unique.
6132         *
6133         * @param name - name of the sought script group
6134         * @returns sought script group or NULL if there's no such group
6135         */
6136        ScriptGroup* File::GetScriptGroup(const String& name) {
6137            if (!pScriptGroups) LoadScriptGroups();
6138            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6139            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
6140                if ((*it)->Name == name) return *it;
6141            return NULL;
6142        }
6143    
6144        /** @brief Add new instrument script group.
6145         *
6146         * Adds a new, empty real-time instrument script group to the file.
6147         *
6148         * You have to call Save() to make this persistent to the file.
6149         *
6150         * @return new empty script group
6151         */
6152        ScriptGroup* File::AddScriptGroup() {
6153            if (!pScriptGroups) LoadScriptGroups();
6154            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
6155            pScriptGroups->push_back(pScriptGroup);
6156            return pScriptGroup;
6157        }
6158    
6159        /** @brief Delete an instrument script group.
6160         *
6161         * This will delete the given real-time instrument script group and all its
6162         * instrument scripts it contains. References inside instruments that are
6163         * using the deleted scripts will be removed from the respective instruments
6164         * accordingly.
6165         *
6166         * You have to call Save() to make this persistent to the file.
6167         *
6168         * @param pScriptGroup - script group to delete
6169         * @throws gig::Exception if given script group could not be found
6170         */
6171        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
6172            if (!pScriptGroups) LoadScriptGroups();
6173            std::list<ScriptGroup*>::iterator iter =
6174                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
6175            if (iter == pScriptGroups->end())
6176                throw gig::Exception("Could not delete script group, could not find given script group");
6177            pScriptGroups->erase(iter);
6178            for (int i = 0; pScriptGroup->GetScript(i); ++i)
6179                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
6180            if (pScriptGroup->pList)
6181                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
6182            delete pScriptGroup;
6183        }
6184    
6185        void File::LoadScriptGroups() {
6186            if (pScriptGroups) return;
6187            pScriptGroups = new std::list<ScriptGroup*>;
6188            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
6189            if (lstLS) {
6190                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
6191                     lst = lstLS->GetNextSubList())
6192                {
6193                    if (lst->GetListType() == LIST_TYPE_RTIS) {
6194                        pScriptGroups->push_back(new ScriptGroup(this, lst));
6195                    }
6196                }
6197            }
6198        }
6199    
6200      /**      /**
6201       * Apply all the gig file's current instruments, samples, groups and settings       * Apply all the gig file's current instruments, samples, groups and settings
6202       * 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 3752  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6205  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6205       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
6206       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
6207       *       *
6208         * @param pProgress - callback function for progress notification
6209       * @throws Exception - on errors       * @throws Exception - on errors
6210       */       */
6211      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
6212          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6213    
6214          b64BitWavePoolOffsets = pVersion && pVersion->major == 3;          // update own gig format extension chunks
6215            // (not part of the GigaStudio 4 format)
6216            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6217            if (!lst3LS) {
6218                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6219            }
6220            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6221            // location of <3LS > is irrelevant, however it should be located
6222            // before  the actual wave data
6223            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6224            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6225    
6226            // This must be performed before writing the chunks for instruments,
6227            // because the instruments' script slots will write the file offsets
6228            // of the respective instrument script chunk as reference.
6229            if (pScriptGroups) {
6230                // Update instrument script (group) chunks.
6231                for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6232                     it != pScriptGroups->end(); ++it)
6233                {
6234                    (*it)->UpdateChunks(pProgress);
6235                }
6236            }
6237    
6238            // in case no libgig custom format data was added, then remove the
6239            // custom "3LS " chunk again
6240            if (!lst3LS->CountSubChunks()) {
6241                pRIFF->DeleteSubChunk(lst3LS);
6242                lst3LS = NULL;
6243            }
6244    
6245          // first update base class's chunks          // first update base class's chunks
6246          DLS::File::UpdateChunks();          DLS::File::UpdateChunks(pProgress);
6247    
6248          if (newFile) {          if (newFile) {
6249              // INFO was added by Resource::UpdateChunks - make sure it              // INFO was added by Resource::UpdateChunks - make sure it
# Line 3774  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6257  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6257    
6258          // update group's chunks          // update group's chunks
6259          if (pGroups) {          if (pGroups) {
6260              std::list<Group*>::iterator iter = pGroups->begin();              // make sure '3gri' and '3gnl' list chunks exist
6261              std::list<Group*>::iterator end  = pGroups->end();              // (before updating the Group chunks)
6262              for (; iter != end; ++iter) {              RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
6263                  (*iter)->UpdateChunks();              if (!_3gri) {
6264                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
6265                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
6266              }              }
6267                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
6268                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
6269    
6270              // v3: make sure the file has 128 3gnm chunks              // v3: make sure the file has 128 3gnm chunks
6271                // (before updating the Group chunks)
6272              if (pVersion && pVersion->major == 3) {              if (pVersion && pVersion->major == 3) {
                 RIFF::List* _3gnl = pRIFF->GetSubList(LIST_TYPE_3GRI)->GetSubList(LIST_TYPE_3GNL);  
6273                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
6274                  for (int i = 0 ; i < 128 ; i++) {                  for (int i = 0 ; i < 128 ; i++) {
6275                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
6276                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
6277                  }                  }
6278              }              }
6279    
6280                std::list<Group*>::iterator iter = pGroups->begin();
6281                std::list<Group*>::iterator end  = pGroups->end();
6282                for (; iter != end; ++iter) {
6283                    (*iter)->UpdateChunks(pProgress);
6284                }
6285          }          }
6286    
6287          // update einf chunk          // update einf chunk
# Line 3807  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6300  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6300          // Note that there are several fields with unknown use. These          // Note that there are several fields with unknown use. These
6301          // are set to zero.          // are set to zero.
6302    
6303          int sublen = pSamples->size() / 8 + 49;          int sublen = int(pSamples->size() / 8 + 49);
6304          int einfSize = (Instruments + 1) * sublen;          int einfSize = (Instruments + 1) * sublen;
6305    
6306          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
# Line 3880  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6373  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6373                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6374                  // next 8 bytes unknown                  // next 8 bytes unknown
6375                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6376                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());                  store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
6377                  // next 4 bytes unknown                  // next 4 bytes unknown
6378    
6379                  totnbregions += instrument->Regions;                  totnbregions += instrument->Regions;
# Line 3898  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6391  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6391              store32(&pData[24], totnbloops);              store32(&pData[24], totnbloops);
6392              // next 8 bytes unknown              // next 8 bytes unknown
6393              // next 4 bytes unknown, not always 0              // next 4 bytes unknown, not always 0
6394              store32(&pData[40], pSamples->size());              store32(&pData[40], (uint32_t) pSamples->size());
6395              // next 4 bytes unknown              // next 4 bytes unknown
6396          }          }
6397    
6398          // update 3crc chunk          // update 3crc chunk
6399    
6400          // The 3crc chunk contains CRC-32 checksums for the          // The 3crc chunk contains CRC-32 checksums for the
6401          // samples. The actual checksum values will be filled in          // samples. When saving a gig file to disk, we first update the 3CRC
6402          // later, by Sample::Write.          // chunk here (in RAM) with the old crc values which we read from the
6403            // 3CRC chunk when we opened the file (available with gig::Sample::crc
6404            // member variable). This step is required, because samples might have
6405            // been deleted by the user since the file was opened, which in turn
6406            // changes the order of the (i.e. old) checksums within the 3crc chunk.
6407            // If a sample was conciously modified by the user (that is if
6408            // Sample::Write() was called later on) then Sample::Write() will just
6409            // update the respective individual checksum(s) directly on disk and
6410            // leaves all other sample checksums untouched.
6411    
6412          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6413          if (_3crc) {          if (_3crc) {
6414              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
6415          } else if (newFile) {          } else /*if (newFile)*/ {
6416              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
             _3crc->LoadChunkData();  
   
6417              // 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
6418              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6419          }          }
6420            { // must be performed in RAM here ...
6421                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6422                if (pData) {
6423                    File::SampleList::iterator iter = pSamples->begin();
6424                    File::SampleList::iterator end  = pSamples->end();
6425                    for (int index = 0; iter != end; ++iter, ++index) {
6426                        gig::Sample* pSample = (gig::Sample*) *iter;
6427                        pData[index*2]   = 1; // always 1
6428                        pData[index*2+1] = pSample->crc;
6429                    }
6430                }
6431            }
6432        }
6433        
6434        void File::UpdateFileOffsets() {
6435            DLS::File::UpdateFileOffsets();
6436    
6437            for (Instrument* instrument = GetFirstInstrument(); instrument;
6438                 instrument = GetNextInstrument())
6439            {
6440                instrument->UpdateScriptFileOffsets();
6441            }
6442      }      }
6443    
6444      /**      /**
# Line 3952  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6473  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6473  // *************** Exception ***************  // *************** Exception ***************
6474  // *  // *
6475    
6476      Exception::Exception(String Message) : DLS::Exception(Message) {      Exception::Exception() : DLS::Exception() {
6477        }
6478    
6479        Exception::Exception(String format, ...) : DLS::Exception() {
6480            va_list arg;
6481            va_start(arg, format);
6482            Message = assemble(format, arg);
6483            va_end(arg);
6484        }
6485    
6486        Exception::Exception(String format, va_list arg) : DLS::Exception() {
6487            Message = assemble(format, arg);
6488      }      }
6489    
6490      void Exception::PrintMessage() {      void Exception::PrintMessage() {

Legend:
Removed from v.1869  
changed lines
  Added in v.3198

  ViewVC Help
Powered by ViewVC