/[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 1050 by schoenebeck, Fri Mar 2 01:04:45 2007 UTC revision 2985 by schoenebeck, Tue Sep 20 22:13:37 2016 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file access library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2007 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2016 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 25  Line 25 
25    
26  #include "helper.h"  #include "helper.h"
27    
28    #include <algorithm>
29  #include <math.h>  #include <math.h>
30  #include <iostream>  #include <iostream>
31    #include <assert.h>
32    
33    /// libgig's current file format version (for extending the original Giga file
34    /// format with libgig's own custom data / custom features).
35    #define GIG_FILE_EXT_VERSION    2
36    
37  /// Initial size of the sample buffer which is used for decompression of  /// Initial size of the sample buffer which is used for decompression of
38  /// compressed sample wave streams - this value should always be bigger than  /// compressed sample wave streams - this value should always be bigger than
# Line 51  Line 57 
57    
58  namespace gig {  namespace gig {
59    
 // *************** progress_t ***************  
 // *  
   
     progress_t::progress_t() {  
         callback    = NULL;  
         custom      = NULL;  
         __range_min = 0.0f;  
         __range_max = 1.0f;  
     }  
   
     // private helper function to convert progress of a subprocess into the global progress  
     static void __notify_progress(progress_t* pProgress, float subprogress) {  
         if (pProgress && pProgress->callback) {  
             const float totalrange    = pProgress->__range_max - pProgress->__range_min;  
             const float totalprogress = pProgress->__range_min + subprogress * totalrange;  
             pProgress->factor         = totalprogress;  
             pProgress->callback(pProgress); // now actually notify about the progress  
         }  
     }  
   
     // private helper function to divide a progress into subprogresses  
     static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {  
         if (pParentProgress && pParentProgress->callback) {  
             const float totalrange    = pParentProgress->__range_max - pParentProgress->__range_min;  
             pSubProgress->callback    = pParentProgress->callback;  
             pSubProgress->custom      = pParentProgress->custom;  
             pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;  
             pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;  
         }  
     }  
   
   
60  // *************** Internal functions for sample decompression ***************  // *************** Internal functions for sample decompression ***************
61  // *  // *
62    
# Line 121  namespace { Line 95  namespace {
95      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
96                        int srcStep, int dstStep,                        int srcStep, int dstStep,
97                        const unsigned char* pSrc, int16_t* pDst,                        const unsigned char* pSrc, int16_t* pDst,
98                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
99                        unsigned long copysamples)                        file_offset_t copysamples)
100      {      {
101          switch (compressionmode) {          switch (compressionmode) {
102              case 0: // 16 bit uncompressed              case 0: // 16 bit uncompressed
# Line 158  namespace { Line 132  namespace {
132    
133      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
134                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,
135                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
136                        unsigned long copysamples, int truncatedBits)                        file_offset_t copysamples, int truncatedBits)
137      {      {
138          int y, dy, ddy, dddy;          int y, dy, ddy, dddy;
139    
# Line 254  namespace { Line 228  namespace {
228  }  }
229    
230    
231    
232    // *************** Internal CRC-32 (Cyclic Redundancy Check) functions  ***************
233    // *
234    
235        static uint32_t* __initCRCTable() {
236            static uint32_t res[256];
237    
238            for (int i = 0 ; i < 256 ; i++) {
239                uint32_t c = i;
240                for (int j = 0 ; j < 8 ; j++) {
241                    c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
242                }
243                res[i] = c;
244            }
245            return res;
246        }
247    
248        static const uint32_t* __CRCTable = __initCRCTable();
249    
250        /**
251         * Initialize a CRC variable.
252         *
253         * @param crc - variable to be initialized
254         */
255        inline static void __resetCRC(uint32_t& crc) {
256            crc = 0xffffffff;
257        }
258    
259        /**
260         * Used to calculate checksums of the sample data in a gig file. The
261         * checksums are stored in the 3crc chunk of the gig file and
262         * automatically updated when a sample is written with Sample::Write().
263         *
264         * One should call __resetCRC() to initialize the CRC variable to be
265         * used before calling this function the first time.
266         *
267         * After initializing the CRC variable one can call this function
268         * arbitrary times, i.e. to split the overall CRC calculation into
269         * steps.
270         *
271         * Once the whole data was processed by __calculateCRC(), one should
272         * call __encodeCRC() to get the final CRC result.
273         *
274         * @param buf     - pointer to data the CRC shall be calculated of
275         * @param bufSize - size of the data to be processed
276         * @param crc     - variable the CRC sum shall be stored to
277         */
278        static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
279            for (int i = 0 ; i < bufSize ; i++) {
280                crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
281            }
282        }
283    
284        /**
285         * Returns the final CRC result.
286         *
287         * @param crc - variable previously passed to __calculateCRC()
288         */
289        inline static uint32_t __encodeCRC(const uint32_t& crc) {
290            return crc ^ 0xffffffff;
291        }
292    
293    
294    
295    // *************** Other Internal functions  ***************
296    // *
297    
298        static split_type_t __resolveSplitType(dimension_t dimension) {
299            return (
300                dimension == dimension_layer ||
301                dimension == dimension_samplechannel ||
302                dimension == dimension_releasetrigger ||
303                dimension == dimension_keyboard ||
304                dimension == dimension_roundrobin ||
305                dimension == dimension_random ||
306                dimension == dimension_smartmidi ||
307                dimension == dimension_roundrobinkeyboard
308            ) ? split_type_bit : split_type_normal;
309        }
310    
311        static int __resolveZoneSize(dimension_def_t& dimension_definition) {
312            return (dimension_definition.split_type == split_type_normal)
313            ? int(128.0 / dimension_definition.zones) : 0;
314        }
315    
316    
317    
318  // *************** Sample ***************  // *************** Sample ***************
319  // *  // *
320    
321      unsigned int Sample::Instances = 0;      size_t       Sample::Instances = 0;
322      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
323    
324      /** @brief Constructor.      /** @brief Constructor.
# Line 278  namespace { Line 339  namespace {
339       * @param fileNo         - number of an extension file where this sample       * @param fileNo         - number of an extension file where this sample
340       *                         is located, 0 otherwise       *                         is located, 0 otherwise
341       */       */
342      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
343          pInfo->UseFixedLengthStrings = true;          static const DLS::Info::string_length_t fixedStringLengths[] = {
344                { CHUNK_ID_INAM, 64 },
345                { 0, 0 }
346            };
347            pInfo->SetFixedStringLengths(fixedStringLengths);
348          Instances++;          Instances++;
349          FileNo = fileNo;          FileNo = fileNo;
350    
351            __resetCRC(crc);
352    
353          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
354          if (pCk3gix) {          if (pCk3gix) {
355              uint16_t iSampleGroup = pCk3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
# Line 314  namespace { Line 381  namespace {
381              Manufacturer  = 0;              Manufacturer  = 0;
382              Product       = 0;              Product       = 0;
383              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
384              MIDIUnityNote = 64;              MIDIUnityNote = 60;
385              FineTune      = 0;              FineTune      = 0;
386                SMPTEFormat   = smpte_format_no_offset;
387              SMPTEOffset   = 0;              SMPTEOffset   = 0;
388              Loops         = 0;              Loops         = 0;
389              LoopID        = 0;              LoopID        = 0;
390                LoopType      = loop_type_normal;
391              LoopStart     = 0;              LoopStart     = 0;
392              LoopEnd       = 0;              LoopEnd       = 0;
393              LoopFraction  = 0;              LoopFraction  = 0;
# Line 358  namespace { Line 427  namespace {
427      }      }
428    
429      /**      /**
430         * Make a (semi) deep copy of the Sample object given by @a orig (without
431         * the actual waveform data) and assign it to this object.
432         *
433         * Discussion: copying .gig samples is a bit tricky. It requires three
434         * steps:
435         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
436         *    its new sample waveform data size.
437         * 2. Saving the file (done by File::Save()) so that it gains correct size
438         *    and layout for writing the actual wave form data directly to disc
439         *    in next step.
440         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
441         *
442         * @param orig - original Sample object to be copied from
443         */
444        void Sample::CopyAssignMeta(const Sample* orig) {
445            // handle base classes
446            DLS::Sample::CopyAssignCore(orig);
447            
448            // handle actual own attributes of this class
449            Manufacturer = orig->Manufacturer;
450            Product = orig->Product;
451            SamplePeriod = orig->SamplePeriod;
452            MIDIUnityNote = orig->MIDIUnityNote;
453            FineTune = orig->FineTune;
454            SMPTEFormat = orig->SMPTEFormat;
455            SMPTEOffset = orig->SMPTEOffset;
456            Loops = orig->Loops;
457            LoopID = orig->LoopID;
458            LoopType = orig->LoopType;
459            LoopStart = orig->LoopStart;
460            LoopEnd = orig->LoopEnd;
461            LoopSize = orig->LoopSize;
462            LoopFraction = orig->LoopFraction;
463            LoopPlayCount = orig->LoopPlayCount;
464            
465            // schedule resizing this sample to the given sample's size
466            Resize(orig->GetSize());
467        }
468    
469        /**
470         * Should be called after CopyAssignMeta() and File::Save() sequence.
471         * Read more about it in the discussion of CopyAssignMeta(). This method
472         * copies the actual waveform data by disk streaming.
473         *
474         * @e CAUTION: this method is currently not thread safe! During this
475         * operation the sample must not be used for other purposes by other
476         * threads!
477         *
478         * @param orig - original Sample object to be copied from
479         */
480        void Sample::CopyAssignWave(const Sample* orig) {
481            const int iReadAtOnce = 32*1024;
482            char* buf = new char[iReadAtOnce * orig->FrameSize];
483            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
484            file_offset_t restorePos = pOrig->GetPos();
485            pOrig->SetPos(0);
486            SetPos(0);
487            for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
488                               n = pOrig->Read(buf, iReadAtOnce))
489            {
490                Write(buf, n);
491            }
492            pOrig->SetPos(restorePos);
493            delete [] buf;
494        }
495    
496        /**
497       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
498       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
499       *       *
500       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
501       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
502       *       *
503         * @param pProgress - callback function for progress notification
504       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
505       *                        was provided yet       *                        was provided yet
506       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
507       */       */
508      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
509          // first update base class's chunks          // first update base class's chunks
510          DLS::Sample::UpdateChunks();          DLS::Sample::UpdateChunks(pProgress);
511    
512          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
513          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
514          if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);          if (!pCkSmpl) {
515                pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
516                memset(pCkSmpl->LoadChunkData(), 0, 60);
517            }
518          // update 'smpl' chunk          // update 'smpl' chunk
519          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
520          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
521          memcpy(&pData[0], &Manufacturer, 4);          store32(&pData[0], Manufacturer);
522          memcpy(&pData[4], &Product, 4);          store32(&pData[4], Product);
523          memcpy(&pData[8], &SamplePeriod, 4);          store32(&pData[8], SamplePeriod);
524          memcpy(&pData[12], &MIDIUnityNote, 4);          store32(&pData[12], MIDIUnityNote);
525          memcpy(&pData[16], &FineTune, 4);          store32(&pData[16], FineTune);
526          memcpy(&pData[20], &SMPTEFormat, 4);          store32(&pData[20], SMPTEFormat);
527          memcpy(&pData[24], &SMPTEOffset, 4);          store32(&pData[24], SMPTEOffset);
528          memcpy(&pData[28], &Loops, 4);          store32(&pData[28], Loops);
529    
530          // we skip 'manufByt' for now (4 bytes)          // we skip 'manufByt' for now (4 bytes)
531    
532          memcpy(&pData[36], &LoopID, 4);          store32(&pData[36], LoopID);
533          memcpy(&pData[40], &LoopType, 4);          store32(&pData[40], LoopType);
534          memcpy(&pData[44], &LoopStart, 4);          store32(&pData[44], LoopStart);
535          memcpy(&pData[48], &LoopEnd, 4);          store32(&pData[48], LoopEnd);
536          memcpy(&pData[52], &LoopFraction, 4);          store32(&pData[52], LoopFraction);
537          memcpy(&pData[56], &LoopPlayCount, 4);          store32(&pData[56], LoopPlayCount);
538    
539          // make sure '3gix' chunk exists          // make sure '3gix' chunk exists
540          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
# Line 414  namespace { Line 554  namespace {
554          }          }
555          // update '3gix' chunk          // update '3gix' chunk
556          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
557          memcpy(&pData[0], &iSampleGroup, 2);          store16(&pData[0], iSampleGroup);
558    
559            // if the library user toggled the "Compressed" attribute from true to
560            // false, then the EWAV chunk associated with compressed samples needs
561            // to be deleted
562            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
563            if (ewav && !Compressed) {
564                pWaveList->DeleteSubChunk(ewav);
565            }
566      }      }
567    
568      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
569      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
570          //TODO: we have to add some more scans here (e.g. determine compression rate)          //TODO: we have to add some more scans here (e.g. determine compression rate)
571          this->SamplesTotal = 0;          this->SamplesTotal = 0;
572          std::list<unsigned long> frameOffsets;          std::list<file_offset_t> frameOffsets;
573    
574          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
575          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
# Line 437  namespace { Line 585  namespace {
585                  const int mode_l = pCkData->ReadUint8();                  const int mode_l = pCkData->ReadUint8();
586                  const int mode_r = pCkData->ReadUint8();                  const int mode_r = pCkData->ReadUint8();
587                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
588                  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];                  const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
589    
590                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
591                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 456  namespace { Line 604  namespace {
604    
605                  const int mode = pCkData->ReadUint8();                  const int mode = pCkData->ReadUint8();
606                  if (mode > 5) throw gig::Exception("Unknown compression mode");                  if (mode > 5) throw gig::Exception("Unknown compression mode");
607                  const unsigned long frameSize = bytesPerFrame[mode];                  const file_offset_t frameSize = bytesPerFrame[mode];
608    
609                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
610                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 472  namespace { Line 620  namespace {
620    
621          // Build the frames table (which is used for fast resolving of a frame's chunk offset)          // Build the frames table (which is used for fast resolving of a frame's chunk offset)
622          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
623          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new file_offset_t[frameOffsets.size()];
624          std::list<unsigned long>::iterator end  = frameOffsets.end();          std::list<file_offset_t>::iterator end  = frameOffsets.end();
625          std::list<unsigned long>::iterator iter = frameOffsets.begin();          std::list<file_offset_t>::iterator iter = frameOffsets.begin();
626          for (int i = 0; iter != end; i++, iter++) {          for (int i = 0; iter != end; i++, iter++) {
627              FrameTable[i] = *iter;              FrameTable[i] = *iter;
628          }          }
# Line 515  namespace { Line 663  namespace {
663       *                      the cached sample data in bytes       *                      the cached sample data in bytes
664       * @see                 ReleaseSampleData(), Read(), SetPos()       * @see                 ReleaseSampleData(), Read(), SetPos()
665       */       */
666      buffer_t Sample::LoadSampleData(unsigned long SampleCount) {      buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
667          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
668      }      }
669    
# Line 574  namespace { Line 722  namespace {
722       *                           size of the cached sample data in bytes       *                           size of the cached sample data in bytes
723       * @see                      ReleaseSampleData(), Read(), SetPos()       * @see                      ReleaseSampleData(), Read(), SetPos()
724       */       */
725      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
726          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
727          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
728          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
729            SetPos(0); // reset read position to begin of sample
730          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
731          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
732          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 615  namespace { Line 764  namespace {
764          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
765          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
766          RAMCache.Size   = 0;          RAMCache.Size   = 0;
767            RAMCache.NullExtensionSize = 0;
768      }      }
769    
770      /** @brief Resize sample.      /** @brief Resize sample.
# Line 639  namespace { Line 789  namespace {
789       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
790       * other formats will fail!       * other formats will fail!
791       *       *
792       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
793       *                   greater than zero)       *                  greater than zero)
794       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
795       *                         or if \a iNewSize is less than 1       * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
796       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
797       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
798       *      DLS::Sample::FormatTag, File::Save()       *      DLS::Sample::FormatTag, File::Save()
799       */       */
800      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
801          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)");
802          DLS::Sample::Resize(iNewSize);          DLS::Sample::Resize(NewSize);
803      }      }
804    
805      /**      /**
# Line 673  namespace { Line 823  namespace {
823       * @returns            the new sample position       * @returns            the new sample position
824       * @see                Read()       * @see                Read()
825       */       */
826      unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {      file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) {
827          if (Compressed) {          if (Compressed) {
828              switch (Whence) {              switch (Whence) {
829                  case RIFF::stream_curpos:                  case RIFF::stream_curpos:
# Line 691  namespace { Line 841  namespace {
841              }              }
842              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
843    
844              unsigned long frame = this->SamplePos / 2048; // to which frame to jump              file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
845              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame
846              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame
847              return this->SamplePos;              return this->SamplePos;
848          }          }
849          else { // not compressed          else { // not compressed
850              unsigned long orderedBytes = SampleCount * this->FrameSize;              file_offset_t orderedBytes = SampleCount * this->FrameSize;
851              unsigned long result = pCkData->SetPos(orderedBytes, Whence);              file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
852              return (result == orderedBytes) ? SampleCount              return (result == orderedBytes) ? SampleCount
853                                              : result / this->FrameSize;                                              : result / this->FrameSize;
854          }          }
# Line 707  namespace { Line 857  namespace {
857      /**      /**
858       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
859       */       */
860      unsigned long Sample::GetPos() {      file_offset_t Sample::GetPos() const {
861          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
862          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
863      }      }
# Line 746  namespace { Line 896  namespace {
896       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
897       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
898       */       */
899      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,      file_offset_t Sample::ReadAndLoop(void* pBuffer, file_offset_t SampleCount, playback_state_t* pPlaybackState,
900                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
901          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
902          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
903    
904          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
# Line 786  namespace { Line 936  namespace {
936                                  // reading, swap all sample frames so it reflects                                  // reading, swap all sample frames so it reflects
937                                  // backward playback                                  // backward playback
938    
939                                  unsigned long swapareastart       = totalreadsamples;                                  file_offset_t swapareastart       = totalreadsamples;
940                                  unsigned long loopoffset          = GetPos() - loop.LoopStart;                                  file_offset_t loopoffset          = GetPos() - loop.LoopStart;
941                                  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                  file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
942                                  unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                  file_offset_t reverseplaybackend  = GetPos() - samplestoreadinloop;
943    
944                                  SetPos(reverseplaybackend);                                  SetPos(reverseplaybackend);
945    
# Line 809  namespace { Line 959  namespace {
959                                  }                                  }
960    
961                                  // reverse the sample frames for backward playback                                  // reverse the sample frames for backward playback
962                                  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!
963                                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
964                              }                              }
965                          } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
966                          break;                          break;
# Line 836  namespace { Line 987  namespace {
987                          // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
988                          // backward playback                          // backward playback
989    
990                          unsigned long swapareastart       = totalreadsamples;                          file_offset_t swapareastart       = totalreadsamples;
991                          unsigned long loopoffset          = GetPos() - loop.LoopStart;                          file_offset_t loopoffset          = GetPos() - loop.LoopStart;
992                          unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)                          file_offset_t samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
993                                                                                    : samplestoread;                                                                                    : samplestoread;
994                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);                          file_offset_t reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
995    
996                          SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
997    
# Line 920  namespace { Line 1071  namespace {
1071       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1072       * @see                SetPos(), CreateDecompressionBuffer()       * @see                SetPos(), CreateDecompressionBuffer()
1073       */       */
1074      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {      file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount, buffer_t* pExternalDecompressionBuffer) {
1075          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1076          if (!Compressed) {          if (!Compressed) {
1077              if (BitDepth == 24) {              if (BitDepth == 24) {
# Line 935  namespace { Line 1086  namespace {
1086          else {          else {
1087              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1088              //TODO: efficiency: maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1089              unsigned long assumedsize      = GuessSize(SampleCount),              file_offset_t assumedsize      = GuessSize(SampleCount),
1090                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1091                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1092                            copysamples, skipsamples,                            copysamples, skipsamples,
# Line 958  namespace { Line 1109  namespace {
1109              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1110    
1111              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
1112                  unsigned long framesamples = SamplesPerFrame;                  file_offset_t framesamples = SamplesPerFrame;
1113                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;                  file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1114    
1115                  int mode_l = *pSrc++, mode_r = 0;                  int mode_l = *pSrc++, mode_r = 0;
1116    
# Line 1099  namespace { Line 1250  namespace {
1250       *       *
1251       * Note: there is currently no support for writing compressed samples.       * Note: there is currently no support for writing compressed samples.
1252       *       *
1253         * For 16 bit samples, the data in the source buffer should be
1254         * int16_t (using native endianness). For 24 bit, the buffer
1255         * should contain three bytes per sample, little-endian.
1256         *
1257       * @param pBuffer     - source buffer       * @param pBuffer     - source buffer
1258       * @param SampleCount - number of sample points to write       * @param SampleCount - number of sample points to write
1259       * @throws DLS::Exception if current sample size is too small       * @throws DLS::Exception if current sample size is too small
1260       * @throws gig::Exception if sample is compressed       * @throws gig::Exception if sample is compressed
1261       * @see DLS::LoadSampleData()       * @see DLS::LoadSampleData()
1262       */       */
1263      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1264          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1265          return DLS::Sample::Write(pBuffer, SampleCount);  
1266            // if this is the first write in this sample, reset the
1267            // checksum calculator
1268            if (pCkData->GetPos() == 0) {
1269                __resetCRC(crc);
1270            }
1271            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1272            file_offset_t res;
1273            if (BitDepth == 24) {
1274                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1275            } else { // 16 bit
1276                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1277                                    : pCkData->Write(pBuffer, SampleCount, 2);
1278            }
1279            __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1280    
1281            // if this is the last write, update the checksum chunk in the
1282            // file
1283            if (pCkData->GetPos() == pCkData->GetSize()) {
1284                File* pFile = static_cast<File*>(GetParent());
1285                pFile->SetSampleChecksum(this, __encodeCRC(crc));
1286            }
1287            return res;
1288      }      }
1289    
1290      /**      /**
# Line 1126  namespace { Line 1303  namespace {
1303       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1304       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1305       */       */
1306      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1307          buffer_t result;          buffer_t result;
1308          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1309                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1310          result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);          result.Size              = (file_offset_t) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1311          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1312          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1313          return result;          return result;
# Line 1164  namespace { Line 1341  namespace {
1341          return pGroup;          return pGroup;
1342      }      }
1343    
1344        /**
1345         * Checks the integrity of this sample's raw audio wave data. Whenever a
1346         * Sample's raw wave data is intentionally modified (i.e. by calling
1347         * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1348         * is calculated and stored/updated for this sample, along to the sample's
1349         * meta informations.
1350         *
1351         * Now by calling this method the current raw audio wave data is checked
1352         * against the already stored CRC32 check sum in order to check whether the
1353         * sample data had been damaged unintentionally for some reason. Since by
1354         * calling this method always the entire raw audio wave data has to be
1355         * read, verifying all samples this way may take a long time accordingly.
1356         * And that's also the reason why the sample integrity is not checked by
1357         * default whenever a gig file is loaded. So this method must be called
1358         * explicitly to fulfill this task.
1359         *
1360         * @returns true if sample is OK or false if the sample is damaged
1361         * @throws Exception if no checksum had been stored to disk for this
1362         *         sample yet, or on I/O issues
1363         */
1364        bool Sample::VerifyWaveData() {
1365            File* pFile = static_cast<File*>(GetParent());
1366            const uint32_t referenceCRC = pFile->GetSampleChecksum(this);
1367            uint32_t crc = CalculateWaveDataChecksum();
1368            return crc == referenceCRC;
1369        }
1370    
1371        uint32_t Sample::CalculateWaveDataChecksum() {
1372            const size_t sz = 20*1024; // 20kB buffer size
1373            std::vector<uint8_t> buffer(sz);
1374            buffer.resize(sz);
1375    
1376            const size_t n = sz / FrameSize;
1377            SetPos(0);
1378            uint32_t crc = 0;
1379            __resetCRC(crc);
1380            while (true) {
1381                file_offset_t nRead = Read(&buffer[0], n);
1382                if (nRead <= 0) break;
1383                __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1384            }
1385            __encodeCRC(crc);
1386            return crc;
1387        }
1388    
1389      Sample::~Sample() {      Sample::~Sample() {
1390          Instances--;          Instances--;
1391          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1180  namespace { Line 1402  namespace {
1402  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1403  // *  // *
1404    
1405      uint                               DimensionRegion::Instances       = 0;      size_t                             DimensionRegion::Instances       = 0;
1406      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1407    
1408      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1409          Instances++;          Instances++;
1410    
1411          pSample = NULL;          pSample = NULL;
1412            pRegion = pParent;
1413    
1414            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1415            else memset(&Crossfade, 0, 4);
1416    
         memcpy(&Crossfade, &SamplerOptions, 4);  
1417          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1418    
1419          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
# Line 1302  namespace { Line 1527  namespace {
1527                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1528              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1529              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1530                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1531              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1532              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1533              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1338  namespace { Line 1563  namespace {
1563                  if (lfo3ctrl & 0x40) // bit 6                  if (lfo3ctrl & 0x40) // bit 6
1564                      VCFType = vcf_type_lowpassturbo;                      VCFType = vcf_type_lowpassturbo;
1565              }              }
1566                if (_3ewa->RemainingBytes() >= 8) {
1567                    _3ewa->Read(DimensionUpperLimits, 1, 8);
1568                } else {
1569                    memset(DimensionUpperLimits, 0, 8);
1570                }
1571          } else { // '3ewa' chunk does not exist yet          } else { // '3ewa' chunk does not exist yet
1572              // use default values              // use default values
1573              LFO3Frequency                   = 1.0;              LFO3Frequency                   = 1.0;
# Line 1347  namespace { Line 1577  namespace {
1577              LFO1ControlDepth                = 0;              LFO1ControlDepth                = 0;
1578              LFO3ControlDepth                = 0;              LFO3ControlDepth                = 0;
1579              EG1Attack                       = 0.0;              EG1Attack                       = 0.0;
1580              EG1Decay1                       = 0.0;              EG1Decay1                       = 0.005;
1581              EG1Sustain                      = 0;              EG1Sustain                      = 1000;
1582              EG1Release                      = 0.0;              EG1Release                      = 0.3;
1583              EG1Controller.type              = eg1_ctrl_t::type_none;              EG1Controller.type              = eg1_ctrl_t::type_none;
1584              EG1Controller.controller_number = 0;              EG1Controller.controller_number = 0;
1585              EG1ControllerInvert             = false;              EG1ControllerInvert             = false;
# Line 1364  namespace { Line 1594  namespace {
1594              EG2ControllerReleaseInfluence   = 0;              EG2ControllerReleaseInfluence   = 0;
1595              LFO1Frequency                   = 1.0;              LFO1Frequency                   = 1.0;
1596              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1597              EG2Decay1                       = 0.0;              EG2Decay1                       = 0.005;
1598              EG2Sustain                      = 0;              EG2Sustain                      = 1000;
1599              EG2Release                      = 0.0;              EG2Release                      = 0.3;
1600              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1601              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1602              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
1603              EG1Decay2                       = 0.0;              EG1Decay2                       = 0.0;
1604              EG1InfiniteSustain              = false;              EG1InfiniteSustain              = true;
1605              EG1PreAttack                    = 1000;              EG1PreAttack                    = 0;
1606              EG2Decay2                       = 0.0;              EG2Decay2                       = 0.0;
1607              EG2InfiniteSustain              = false;              EG2InfiniteSustain              = true;
1608              EG2PreAttack                    = 1000;              EG2PreAttack                    = 0;
1609              VelocityResponseCurve           = curve_type_nonlinear;              VelocityResponseCurve           = curve_type_nonlinear;
1610              VelocityResponseDepth           = 3;              VelocityResponseDepth           = 3;
1611              ReleaseVelocityResponseCurve    = curve_type_nonlinear;              ReleaseVelocityResponseCurve    = curve_type_nonlinear;
# Line 1418  namespace { Line 1648  namespace {
1648              VCFVelocityDynamicRange         = 0x04;              VCFVelocityDynamicRange         = 0x04;
1649              VCFVelocityCurve                = curve_type_linear;              VCFVelocityCurve                = curve_type_linear;
1650              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1651                memset(DimensionUpperLimits, 127, 8);
1652          }          }
1653    
1654          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1655                                                       VelocityResponseDepth,                                                       VelocityResponseDepth,
1656                                                       VelocityResponseCurveScaling);                                                       VelocityResponseCurveScaling);
1657    
1658          curve_type_t curveType = ReleaseVelocityResponseCurve;          pVelocityReleaseTable = GetReleaseVelocityTable(
1659          uint8_t depth = ReleaseVelocityResponseDepth;                                      ReleaseVelocityResponseCurve,
1660                                        ReleaseVelocityResponseDepth
1661                                    );
1662    
1663            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1664                                                          VCFVelocityDynamicRange,
1665                                                          VCFVelocityScale,
1666                                                          VCFCutoffController);
1667    
1668          // this models a strange behaviour or bug in GSt: two of the          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1669          // velocity response curves for release time are not used even          VelocityTable = 0;
1670          // if specified, instead another curve is chosen.      }
         if ((curveType == curve_type_nonlinear && depth == 0) ||  
             (curveType == curve_type_special   && depth == 4)) {  
             curveType = curve_type_nonlinear;  
             depth = 3;  
         }  
         pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);  
1671    
1672          curveType = VCFVelocityCurve;      /*
1673          depth = VCFVelocityDynamicRange;       * Constructs a DimensionRegion by copying all parameters from
1674         * another DimensionRegion
1675         */
1676        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1677            Instances++;
1678            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1679            *this = src; // default memberwise shallow copy of all parameters
1680            pParentList = _3ewl; // restore the chunk pointer
1681    
1682            // deep copy of owned structures
1683            if (src.VelocityTable) {
1684                VelocityTable = new uint8_t[128];
1685                for (int k = 0 ; k < 128 ; k++)
1686                    VelocityTable[k] = src.VelocityTable[k];
1687            }
1688            if (src.pSampleLoops) {
1689                pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1690                for (int k = 0 ; k < src.SampleLoops ; k++)
1691                    pSampleLoops[k] = src.pSampleLoops[k];
1692            }
1693        }
1694        
1695        /**
1696         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1697         * and assign it to this object.
1698         *
1699         * Note that all sample pointers referenced by @a orig are simply copied as
1700         * memory address. Thus the respective samples are shared, not duplicated!
1701         *
1702         * @param orig - original DimensionRegion object to be copied from
1703         */
1704        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1705            CopyAssign(orig, NULL);
1706        }
1707    
1708          // even stranger GSt: two of the velocity response curves for      /**
1709          // filter cutoff are not used, instead another special curve       * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1710          // is chosen. This curve is not used anywhere else.       * and assign it to this object.
1711          if ((curveType == curve_type_nonlinear && depth == 0) ||       *
1712              (curveType == curve_type_special   && depth == 4)) {       * @param orig - original DimensionRegion object to be copied from
1713              curveType = curve_type_special;       * @param mSamples - crosslink map between the foreign file's samples and
1714              depth = 5;       *                   this file's samples
1715         */
1716        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1717            // delete all allocated data first
1718            if (VelocityTable) delete [] VelocityTable;
1719            if (pSampleLoops) delete [] pSampleLoops;
1720            
1721            // backup parent list pointer
1722            RIFF::List* p = pParentList;
1723            
1724            gig::Sample* pOriginalSample = pSample;
1725            gig::Region* pOriginalRegion = pRegion;
1726            
1727            //NOTE: copy code copied from assignment constructor above, see comment there as well
1728            
1729            *this = *orig; // default memberwise shallow copy of all parameters
1730            
1731            // restore members that shall not be altered
1732            pParentList = p; // restore the chunk pointer
1733            pRegion = pOriginalRegion;
1734            
1735            // only take the raw sample reference reference if the
1736            // two DimensionRegion objects are part of the same file
1737            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1738                pSample = pOriginalSample;
1739            }
1740            
1741            if (mSamples && mSamples->count(orig->pSample)) {
1742                pSample = mSamples->find(orig->pSample)->second;
1743            }
1744    
1745            // deep copy of owned structures
1746            if (orig->VelocityTable) {
1747                VelocityTable = new uint8_t[128];
1748                for (int k = 0 ; k < 128 ; k++)
1749                    VelocityTable[k] = orig->VelocityTable[k];
1750            }
1751            if (orig->pSampleLoops) {
1752                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1753                for (int k = 0 ; k < orig->SampleLoops ; k++)
1754                    pSampleLoops[k] = orig->pSampleLoops[k];
1755          }          }
1756          pVelocityCutoffTable = GetVelocityTable(curveType, depth,      }
                                                 VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);  
1757    
1758        /**
1759         * Updates the respective member variable and updates @c SampleAttenuation
1760         * which depends on this value.
1761         */
1762        void DimensionRegion::SetGain(int32_t gain) {
1763            DLS::Sampler::SetGain(gain);
1764          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
         VelocityTable = 0;  
1765      }      }
1766    
1767      /**      /**
# Line 1461  namespace { Line 1770  namespace {
1770       *       *
1771       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
1772       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
1773         *
1774         * @param pProgress - callback function for progress notification
1775       */       */
1776      void DimensionRegion::UpdateChunks() {      void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1777          // first update base class's chunk          // first update base class's chunk
1778          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks(pProgress);
1779    
1780            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1781            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1782            pData[12] = Crossfade.in_start;
1783            pData[13] = Crossfade.in_end;
1784            pData[14] = Crossfade.out_start;
1785            pData[15] = Crossfade.out_end;
1786    
1787          // make sure '3ewa' chunk exists          // make sure '3ewa' chunk exists
1788          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1789          if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);          if (!_3ewa) {
1790          uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();              File* pFile = (File*) GetParent()->GetParent()->GetParent();
1791                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1792                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1793            }
1794            pData = (uint8_t*) _3ewa->LoadChunkData();
1795    
1796          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1797    
1798          const uint32_t unknown = _3ewa->GetSize(); // unknown, always chunk size ?          const uint32_t chunksize = _3ewa->GetNewSize();
1799          memcpy(&pData[0], &unknown, 4);          store32(&pData[0], chunksize); // unknown, always chunk size?
1800    
1801          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1802          memcpy(&pData[4], &lfo3freq, 4);          store32(&pData[4], lfo3freq);
1803    
1804          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1805          memcpy(&pData[8], &eg3attack, 4);          store32(&pData[8], eg3attack);
1806    
1807          // next 2 bytes unknown          // next 2 bytes unknown
1808    
1809          memcpy(&pData[14], &LFO1InternalDepth, 2);          store16(&pData[14], LFO1InternalDepth);
1810    
1811          // next 2 bytes unknown          // next 2 bytes unknown
1812    
1813          memcpy(&pData[18], &LFO3InternalDepth, 2);          store16(&pData[18], LFO3InternalDepth);
1814    
1815          // next 2 bytes unknown          // next 2 bytes unknown
1816    
1817          memcpy(&pData[22], &LFO1ControlDepth, 2);          store16(&pData[22], LFO1ControlDepth);
1818    
1819          // next 2 bytes unknown          // next 2 bytes unknown
1820    
1821          memcpy(&pData[26], &LFO3ControlDepth, 2);          store16(&pData[26], LFO3ControlDepth);
1822    
1823          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1824          memcpy(&pData[28], &eg1attack, 4);          store32(&pData[28], eg1attack);
1825    
1826          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1827          memcpy(&pData[32], &eg1decay1, 4);          store32(&pData[32], eg1decay1);
1828    
1829          // next 2 bytes unknown          // next 2 bytes unknown
1830    
1831          memcpy(&pData[38], &EG1Sustain, 2);          store16(&pData[38], EG1Sustain);
1832    
1833          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1834          memcpy(&pData[40], &eg1release, 4);          store32(&pData[40], eg1release);
1835    
1836          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1837          memcpy(&pData[44], &eg1ctl, 1);          pData[44] = eg1ctl;
1838    
1839          const uint8_t eg1ctrloptions =          const uint8_t eg1ctrloptions =
1840              (EG1ControllerInvert) ? 0x01 : 0x00 |              (EG1ControllerInvert ? 0x01 : 0x00) |
1841              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1842              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1843              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1844          memcpy(&pData[45], &eg1ctrloptions, 1);          pData[45] = eg1ctrloptions;
1845    
1846          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1847          memcpy(&pData[46], &eg2ctl, 1);          pData[46] = eg2ctl;
1848    
1849          const uint8_t eg2ctrloptions =          const uint8_t eg2ctrloptions =
1850              (EG2ControllerInvert) ? 0x01 : 0x00 |              (EG2ControllerInvert ? 0x01 : 0x00) |
1851              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1852              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1853              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1854          memcpy(&pData[47], &eg2ctrloptions, 1);          pData[47] = eg2ctrloptions;
1855    
1856          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1857          memcpy(&pData[48], &lfo1freq, 4);          store32(&pData[48], lfo1freq);
1858    
1859          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1860          memcpy(&pData[52], &eg2attack, 4);          store32(&pData[52], eg2attack);
1861    
1862          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1863          memcpy(&pData[56], &eg2decay1, 4);          store32(&pData[56], eg2decay1);
1864    
1865          // next 2 bytes unknown          // next 2 bytes unknown
1866    
1867          memcpy(&pData[62], &EG2Sustain, 2);          store16(&pData[62], EG2Sustain);
1868    
1869          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1870          memcpy(&pData[64], &eg2release, 4);          store32(&pData[64], eg2release);
1871    
1872          // next 2 bytes unknown          // next 2 bytes unknown
1873    
1874          memcpy(&pData[70], &LFO2ControlDepth, 2);          store16(&pData[70], LFO2ControlDepth);
1875    
1876          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1877          memcpy(&pData[72], &lfo2freq, 4);          store32(&pData[72], lfo2freq);
1878    
1879          // next 2 bytes unknown          // next 2 bytes unknown
1880    
1881          memcpy(&pData[78], &LFO2InternalDepth, 2);          store16(&pData[78], LFO2InternalDepth);
1882    
1883          const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);          const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1884          memcpy(&pData[80], &eg1decay2, 4);          store32(&pData[80], eg1decay2);
1885    
1886          // next 2 bytes unknown          // next 2 bytes unknown
1887    
1888          memcpy(&pData[86], &EG1PreAttack, 2);          store16(&pData[86], EG1PreAttack);
1889    
1890          const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);          const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1891          memcpy(&pData[88], &eg2decay2, 4);          store32(&pData[88], eg2decay2);
1892    
1893          // next 2 bytes unknown          // next 2 bytes unknown
1894    
1895          memcpy(&pData[94], &EG2PreAttack, 2);          store16(&pData[94], EG2PreAttack);
1896    
1897          {          {
1898              if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");              if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
# Line 1588  namespace { Line 1910  namespace {
1910                  default:                  default:
1911                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1912              }              }
1913              memcpy(&pData[96], &velocityresponse, 1);              pData[96] = velocityresponse;
1914          }          }
1915    
1916          {          {
# Line 1607  namespace { Line 1929  namespace {
1929                  default:                  default:
1930                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1931              }              }
1932              memcpy(&pData[97], &releasevelocityresponse, 1);              pData[97] = releasevelocityresponse;
1933          }          }
1934    
1935          memcpy(&pData[98], &VelocityResponseCurveScaling, 1);          pData[98] = VelocityResponseCurveScaling;
1936    
1937          memcpy(&pData[99], &AttenuationControllerThreshold, 1);          pData[99] = AttenuationControllerThreshold;
1938    
1939          // next 4 bytes unknown          // next 4 bytes unknown
1940    
1941          memcpy(&pData[104], &SampleStartOffset, 2);          store16(&pData[104], SampleStartOffset);
1942    
1943          // next 2 bytes unknown          // next 2 bytes unknown
1944    
# Line 1635  namespace { Line 1957  namespace {
1957                  default:                  default:
1958                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1959              }              }
1960              memcpy(&pData[108], &pitchTrackDimensionBypass, 1);              pData[108] = pitchTrackDimensionBypass;
1961          }          }
1962    
1963          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1964          memcpy(&pData[109], &pan, 1);          pData[109] = pan;
1965    
1966          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1967          memcpy(&pData[110], &selfmask, 1);          pData[110] = selfmask;
1968    
1969          // next byte unknown          // next byte unknown
1970    
# Line 1651  namespace { Line 1973  namespace {
1973              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1974              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1975              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1976              memcpy(&pData[112], &lfo3ctrl, 1);              pData[112] = lfo3ctrl;
1977          }          }
1978    
1979          const uint8_t attenctl = EncodeLeverageController(AttenuationController);          const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1980          memcpy(&pData[113], &attenctl, 1);          pData[113] = attenctl;
1981    
1982          {          {
1983              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1984              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1985              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1986              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1987              memcpy(&pData[114], &lfo2ctrl, 1);              pData[114] = lfo2ctrl;
1988          }          }
1989    
1990          {          {
# Line 1671  namespace { Line 1993  namespace {
1993              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1994              if (VCFResonanceController != vcf_res_ctrl_none)              if (VCFResonanceController != vcf_res_ctrl_none)
1995                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1996              memcpy(&pData[115], &lfo1ctrl, 1);              pData[115] = lfo1ctrl;
1997          }          }
1998    
1999          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
2000                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
2001          memcpy(&pData[116], &eg3depth, 1);          store16(&pData[116], eg3depth);
2002    
2003          // next 2 bytes unknown          // next 2 bytes unknown
2004    
2005          const uint8_t channeloffset = ChannelOffset * 4;          const uint8_t channeloffset = ChannelOffset * 4;
2006          memcpy(&pData[120], &channeloffset, 1);          pData[120] = channeloffset;
2007    
2008          {          {
2009              uint8_t regoptions = 0;              uint8_t regoptions = 0;
2010              if (MSDecode)      regoptions |= 0x01; // bit 0              if (MSDecode)      regoptions |= 0x01; // bit 0
2011              if (SustainDefeat) regoptions |= 0x02; // bit 1              if (SustainDefeat) regoptions |= 0x02; // bit 1
2012              memcpy(&pData[121], &regoptions, 1);              pData[121] = regoptions;
2013          }          }
2014    
2015          // next 2 bytes unknown          // next 2 bytes unknown
2016    
2017          memcpy(&pData[124], &VelocityUpperLimit, 1);          pData[124] = VelocityUpperLimit;
2018    
2019          // next 3 bytes unknown          // next 3 bytes unknown
2020    
2021          memcpy(&pData[128], &ReleaseTriggerDecay, 1);          pData[128] = ReleaseTriggerDecay;
2022    
2023          // next 2 bytes unknown          // next 2 bytes unknown
2024    
2025          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2026          memcpy(&pData[131], &eg1hold, 1);          pData[131] = eg1hold;
2027    
2028          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */          const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
2029                                    (VCFCutoff & 0x7f);   /* lower 7 bits */                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
2030          memcpy(&pData[132], &vcfcutoff, 1);          pData[132] = vcfcutoff;
2031    
2032          memcpy(&pData[133], &VCFCutoffController, 1);          pData[133] = VCFCutoffController;
2033    
2034          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2035                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
2036          memcpy(&pData[134], &vcfvelscale, 1);          pData[134] = vcfvelscale;
2037    
2038          // next byte unknown          // next byte unknown
2039    
2040          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */          const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2041                                       (VCFResonance & 0x7f); /* lower 7 bits */                                       (VCFResonance & 0x7f); /* lower 7 bits */
2042          memcpy(&pData[136], &vcfresonance, 1);          pData[136] = vcfresonance;
2043    
2044          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2045                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2046          memcpy(&pData[137], &vcfbreakpoint, 1);          pData[137] = vcfbreakpoint;
2047    
2048          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2049                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2050          memcpy(&pData[138], &vcfvelocity, 1);          pData[138] = vcfvelocity;
2051    
2052          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2053          memcpy(&pData[139], &vcftype, 1);          pData[139] = vcftype;
2054    
2055            if (chunksize >= 148) {
2056                memcpy(&pData[140], DimensionUpperLimits, 8);
2057            }
2058        }
2059    
2060        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2061            curve_type_t curveType = releaseVelocityResponseCurve;
2062            uint8_t depth = releaseVelocityResponseDepth;
2063            // this models a strange behaviour or bug in GSt: two of the
2064            // velocity response curves for release time are not used even
2065            // if specified, instead another curve is chosen.
2066            if ((curveType == curve_type_nonlinear && depth == 0) ||
2067                (curveType == curve_type_special   && depth == 4)) {
2068                curveType = curve_type_nonlinear;
2069                depth = 3;
2070            }
2071            return GetVelocityTable(curveType, depth, 0);
2072        }
2073    
2074        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2075                                                        uint8_t vcfVelocityDynamicRange,
2076                                                        uint8_t vcfVelocityScale,
2077                                                        vcf_cutoff_ctrl_t vcfCutoffController)
2078        {
2079            curve_type_t curveType = vcfVelocityCurve;
2080            uint8_t depth = vcfVelocityDynamicRange;
2081            // even stranger GSt: two of the velocity response curves for
2082            // filter cutoff are not used, instead another special curve
2083            // is chosen. This curve is not used anywhere else.
2084            if ((curveType == curve_type_nonlinear && depth == 0) ||
2085                (curveType == curve_type_special   && depth == 4)) {
2086                curveType = curve_type_special;
2087                depth = 5;
2088            }
2089            return GetVelocityTable(curveType, depth,
2090                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2091                                        ? vcfVelocityScale : 0);
2092      }      }
2093    
2094      // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet      // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
# Line 1746  namespace { Line 2106  namespace {
2106          return table;          return table;
2107      }      }
2108    
2109        Region* DimensionRegion::GetParent() const {
2110            return pRegion;
2111        }
2112    
2113    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2114    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2115    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2116    //#pragma GCC diagnostic push
2117    //#pragma GCC diagnostic error "-Wswitch"
2118    
2119      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2120          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2121          switch (EncodedController) {          switch (EncodedController) {
# Line 1857  namespace { Line 2227  namespace {
2227                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2228                  break;                  break;
2229    
2230                // format extension (these controllers are so far only supported by
2231                // LinuxSampler & gigedit) they will *NOT* work with
2232                // Gigasampler/GigaStudio !
2233                case _lev_ctrl_CC3_EXT:
2234                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2235                    decodedcontroller.controller_number = 3;
2236                    break;
2237                case _lev_ctrl_CC6_EXT:
2238                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2239                    decodedcontroller.controller_number = 6;
2240                    break;
2241                case _lev_ctrl_CC7_EXT:
2242                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2243                    decodedcontroller.controller_number = 7;
2244                    break;
2245                case _lev_ctrl_CC8_EXT:
2246                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2247                    decodedcontroller.controller_number = 8;
2248                    break;
2249                case _lev_ctrl_CC9_EXT:
2250                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2251                    decodedcontroller.controller_number = 9;
2252                    break;
2253                case _lev_ctrl_CC10_EXT:
2254                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2255                    decodedcontroller.controller_number = 10;
2256                    break;
2257                case _lev_ctrl_CC11_EXT:
2258                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2259                    decodedcontroller.controller_number = 11;
2260                    break;
2261                case _lev_ctrl_CC14_EXT:
2262                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2263                    decodedcontroller.controller_number = 14;
2264                    break;
2265                case _lev_ctrl_CC15_EXT:
2266                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2267                    decodedcontroller.controller_number = 15;
2268                    break;
2269                case _lev_ctrl_CC20_EXT:
2270                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2271                    decodedcontroller.controller_number = 20;
2272                    break;
2273                case _lev_ctrl_CC21_EXT:
2274                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2275                    decodedcontroller.controller_number = 21;
2276                    break;
2277                case _lev_ctrl_CC22_EXT:
2278                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2279                    decodedcontroller.controller_number = 22;
2280                    break;
2281                case _lev_ctrl_CC23_EXT:
2282                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2283                    decodedcontroller.controller_number = 23;
2284                    break;
2285                case _lev_ctrl_CC24_EXT:
2286                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2287                    decodedcontroller.controller_number = 24;
2288                    break;
2289                case _lev_ctrl_CC25_EXT:
2290                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2291                    decodedcontroller.controller_number = 25;
2292                    break;
2293                case _lev_ctrl_CC26_EXT:
2294                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2295                    decodedcontroller.controller_number = 26;
2296                    break;
2297                case _lev_ctrl_CC27_EXT:
2298                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2299                    decodedcontroller.controller_number = 27;
2300                    break;
2301                case _lev_ctrl_CC28_EXT:
2302                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2303                    decodedcontroller.controller_number = 28;
2304                    break;
2305                case _lev_ctrl_CC29_EXT:
2306                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2307                    decodedcontroller.controller_number = 29;
2308                    break;
2309                case _lev_ctrl_CC30_EXT:
2310                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2311                    decodedcontroller.controller_number = 30;
2312                    break;
2313                case _lev_ctrl_CC31_EXT:
2314                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2315                    decodedcontroller.controller_number = 31;
2316                    break;
2317                case _lev_ctrl_CC68_EXT:
2318                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2319                    decodedcontroller.controller_number = 68;
2320                    break;
2321                case _lev_ctrl_CC69_EXT:
2322                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2323                    decodedcontroller.controller_number = 69;
2324                    break;
2325                case _lev_ctrl_CC70_EXT:
2326                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2327                    decodedcontroller.controller_number = 70;
2328                    break;
2329                case _lev_ctrl_CC71_EXT:
2330                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2331                    decodedcontroller.controller_number = 71;
2332                    break;
2333                case _lev_ctrl_CC72_EXT:
2334                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2335                    decodedcontroller.controller_number = 72;
2336                    break;
2337                case _lev_ctrl_CC73_EXT:
2338                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2339                    decodedcontroller.controller_number = 73;
2340                    break;
2341                case _lev_ctrl_CC74_EXT:
2342                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2343                    decodedcontroller.controller_number = 74;
2344                    break;
2345                case _lev_ctrl_CC75_EXT:
2346                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2347                    decodedcontroller.controller_number = 75;
2348                    break;
2349                case _lev_ctrl_CC76_EXT:
2350                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2351                    decodedcontroller.controller_number = 76;
2352                    break;
2353                case _lev_ctrl_CC77_EXT:
2354                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2355                    decodedcontroller.controller_number = 77;
2356                    break;
2357                case _lev_ctrl_CC78_EXT:
2358                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2359                    decodedcontroller.controller_number = 78;
2360                    break;
2361                case _lev_ctrl_CC79_EXT:
2362                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2363                    decodedcontroller.controller_number = 79;
2364                    break;
2365                case _lev_ctrl_CC84_EXT:
2366                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2367                    decodedcontroller.controller_number = 84;
2368                    break;
2369                case _lev_ctrl_CC85_EXT:
2370                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2371                    decodedcontroller.controller_number = 85;
2372                    break;
2373                case _lev_ctrl_CC86_EXT:
2374                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2375                    decodedcontroller.controller_number = 86;
2376                    break;
2377                case _lev_ctrl_CC87_EXT:
2378                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2379                    decodedcontroller.controller_number = 87;
2380                    break;
2381                case _lev_ctrl_CC89_EXT:
2382                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2383                    decodedcontroller.controller_number = 89;
2384                    break;
2385                case _lev_ctrl_CC90_EXT:
2386                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2387                    decodedcontroller.controller_number = 90;
2388                    break;
2389                case _lev_ctrl_CC96_EXT:
2390                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2391                    decodedcontroller.controller_number = 96;
2392                    break;
2393                case _lev_ctrl_CC97_EXT:
2394                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2395                    decodedcontroller.controller_number = 97;
2396                    break;
2397                case _lev_ctrl_CC102_EXT:
2398                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2399                    decodedcontroller.controller_number = 102;
2400                    break;
2401                case _lev_ctrl_CC103_EXT:
2402                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2403                    decodedcontroller.controller_number = 103;
2404                    break;
2405                case _lev_ctrl_CC104_EXT:
2406                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2407                    decodedcontroller.controller_number = 104;
2408                    break;
2409                case _lev_ctrl_CC105_EXT:
2410                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2411                    decodedcontroller.controller_number = 105;
2412                    break;
2413                case _lev_ctrl_CC106_EXT:
2414                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2415                    decodedcontroller.controller_number = 106;
2416                    break;
2417                case _lev_ctrl_CC107_EXT:
2418                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2419                    decodedcontroller.controller_number = 107;
2420                    break;
2421                case _lev_ctrl_CC108_EXT:
2422                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2423                    decodedcontroller.controller_number = 108;
2424                    break;
2425                case _lev_ctrl_CC109_EXT:
2426                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2427                    decodedcontroller.controller_number = 109;
2428                    break;
2429                case _lev_ctrl_CC110_EXT:
2430                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2431                    decodedcontroller.controller_number = 110;
2432                    break;
2433                case _lev_ctrl_CC111_EXT:
2434                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2435                    decodedcontroller.controller_number = 111;
2436                    break;
2437                case _lev_ctrl_CC112_EXT:
2438                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2439                    decodedcontroller.controller_number = 112;
2440                    break;
2441                case _lev_ctrl_CC113_EXT:
2442                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2443                    decodedcontroller.controller_number = 113;
2444                    break;
2445                case _lev_ctrl_CC114_EXT:
2446                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2447                    decodedcontroller.controller_number = 114;
2448                    break;
2449                case _lev_ctrl_CC115_EXT:
2450                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2451                    decodedcontroller.controller_number = 115;
2452                    break;
2453                case _lev_ctrl_CC116_EXT:
2454                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2455                    decodedcontroller.controller_number = 116;
2456                    break;
2457                case _lev_ctrl_CC117_EXT:
2458                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2459                    decodedcontroller.controller_number = 117;
2460                    break;
2461                case _lev_ctrl_CC118_EXT:
2462                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2463                    decodedcontroller.controller_number = 118;
2464                    break;
2465                case _lev_ctrl_CC119_EXT:
2466                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2467                    decodedcontroller.controller_number = 119;
2468                    break;
2469    
2470              // unknown controller type              // unknown controller type
2471              default:              default:
2472                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2473          }          }
2474          return decodedcontroller;          return decodedcontroller;
2475      }      }
2476        
2477    // see above (diagnostic push not supported prior GCC 4.6)
2478    //#pragma GCC diagnostic pop
2479    
2480      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2481          _lev_ctrl_t encodedcontroller;          _lev_ctrl_t encodedcontroller;
# Line 1950  namespace { Line 2563  namespace {
2563                      case 95:                      case 95:
2564                          encodedcontroller = _lev_ctrl_effect5depth;                          encodedcontroller = _lev_ctrl_effect5depth;
2565                          break;                          break;
2566    
2567                        // format extension (these controllers are so far only
2568                        // supported by LinuxSampler & gigedit) they will *NOT*
2569                        // work with Gigasampler/GigaStudio !
2570                        case 3:
2571                            encodedcontroller = _lev_ctrl_CC3_EXT;
2572                            break;
2573                        case 6:
2574                            encodedcontroller = _lev_ctrl_CC6_EXT;
2575                            break;
2576                        case 7:
2577                            encodedcontroller = _lev_ctrl_CC7_EXT;
2578                            break;
2579                        case 8:
2580                            encodedcontroller = _lev_ctrl_CC8_EXT;
2581                            break;
2582                        case 9:
2583                            encodedcontroller = _lev_ctrl_CC9_EXT;
2584                            break;
2585                        case 10:
2586                            encodedcontroller = _lev_ctrl_CC10_EXT;
2587                            break;
2588                        case 11:
2589                            encodedcontroller = _lev_ctrl_CC11_EXT;
2590                            break;
2591                        case 14:
2592                            encodedcontroller = _lev_ctrl_CC14_EXT;
2593                            break;
2594                        case 15:
2595                            encodedcontroller = _lev_ctrl_CC15_EXT;
2596                            break;
2597                        case 20:
2598                            encodedcontroller = _lev_ctrl_CC20_EXT;
2599                            break;
2600                        case 21:
2601                            encodedcontroller = _lev_ctrl_CC21_EXT;
2602                            break;
2603                        case 22:
2604                            encodedcontroller = _lev_ctrl_CC22_EXT;
2605                            break;
2606                        case 23:
2607                            encodedcontroller = _lev_ctrl_CC23_EXT;
2608                            break;
2609                        case 24:
2610                            encodedcontroller = _lev_ctrl_CC24_EXT;
2611                            break;
2612                        case 25:
2613                            encodedcontroller = _lev_ctrl_CC25_EXT;
2614                            break;
2615                        case 26:
2616                            encodedcontroller = _lev_ctrl_CC26_EXT;
2617                            break;
2618                        case 27:
2619                            encodedcontroller = _lev_ctrl_CC27_EXT;
2620                            break;
2621                        case 28:
2622                            encodedcontroller = _lev_ctrl_CC28_EXT;
2623                            break;
2624                        case 29:
2625                            encodedcontroller = _lev_ctrl_CC29_EXT;
2626                            break;
2627                        case 30:
2628                            encodedcontroller = _lev_ctrl_CC30_EXT;
2629                            break;
2630                        case 31:
2631                            encodedcontroller = _lev_ctrl_CC31_EXT;
2632                            break;
2633                        case 68:
2634                            encodedcontroller = _lev_ctrl_CC68_EXT;
2635                            break;
2636                        case 69:
2637                            encodedcontroller = _lev_ctrl_CC69_EXT;
2638                            break;
2639                        case 70:
2640                            encodedcontroller = _lev_ctrl_CC70_EXT;
2641                            break;
2642                        case 71:
2643                            encodedcontroller = _lev_ctrl_CC71_EXT;
2644                            break;
2645                        case 72:
2646                            encodedcontroller = _lev_ctrl_CC72_EXT;
2647                            break;
2648                        case 73:
2649                            encodedcontroller = _lev_ctrl_CC73_EXT;
2650                            break;
2651                        case 74:
2652                            encodedcontroller = _lev_ctrl_CC74_EXT;
2653                            break;
2654                        case 75:
2655                            encodedcontroller = _lev_ctrl_CC75_EXT;
2656                            break;
2657                        case 76:
2658                            encodedcontroller = _lev_ctrl_CC76_EXT;
2659                            break;
2660                        case 77:
2661                            encodedcontroller = _lev_ctrl_CC77_EXT;
2662                            break;
2663                        case 78:
2664                            encodedcontroller = _lev_ctrl_CC78_EXT;
2665                            break;
2666                        case 79:
2667                            encodedcontroller = _lev_ctrl_CC79_EXT;
2668                            break;
2669                        case 84:
2670                            encodedcontroller = _lev_ctrl_CC84_EXT;
2671                            break;
2672                        case 85:
2673                            encodedcontroller = _lev_ctrl_CC85_EXT;
2674                            break;
2675                        case 86:
2676                            encodedcontroller = _lev_ctrl_CC86_EXT;
2677                            break;
2678                        case 87:
2679                            encodedcontroller = _lev_ctrl_CC87_EXT;
2680                            break;
2681                        case 89:
2682                            encodedcontroller = _lev_ctrl_CC89_EXT;
2683                            break;
2684                        case 90:
2685                            encodedcontroller = _lev_ctrl_CC90_EXT;
2686                            break;
2687                        case 96:
2688                            encodedcontroller = _lev_ctrl_CC96_EXT;
2689                            break;
2690                        case 97:
2691                            encodedcontroller = _lev_ctrl_CC97_EXT;
2692                            break;
2693                        case 102:
2694                            encodedcontroller = _lev_ctrl_CC102_EXT;
2695                            break;
2696                        case 103:
2697                            encodedcontroller = _lev_ctrl_CC103_EXT;
2698                            break;
2699                        case 104:
2700                            encodedcontroller = _lev_ctrl_CC104_EXT;
2701                            break;
2702                        case 105:
2703                            encodedcontroller = _lev_ctrl_CC105_EXT;
2704                            break;
2705                        case 106:
2706                            encodedcontroller = _lev_ctrl_CC106_EXT;
2707                            break;
2708                        case 107:
2709                            encodedcontroller = _lev_ctrl_CC107_EXT;
2710                            break;
2711                        case 108:
2712                            encodedcontroller = _lev_ctrl_CC108_EXT;
2713                            break;
2714                        case 109:
2715                            encodedcontroller = _lev_ctrl_CC109_EXT;
2716                            break;
2717                        case 110:
2718                            encodedcontroller = _lev_ctrl_CC110_EXT;
2719                            break;
2720                        case 111:
2721                            encodedcontroller = _lev_ctrl_CC111_EXT;
2722                            break;
2723                        case 112:
2724                            encodedcontroller = _lev_ctrl_CC112_EXT;
2725                            break;
2726                        case 113:
2727                            encodedcontroller = _lev_ctrl_CC113_EXT;
2728                            break;
2729                        case 114:
2730                            encodedcontroller = _lev_ctrl_CC114_EXT;
2731                            break;
2732                        case 115:
2733                            encodedcontroller = _lev_ctrl_CC115_EXT;
2734                            break;
2735                        case 116:
2736                            encodedcontroller = _lev_ctrl_CC116_EXT;
2737                            break;
2738                        case 117:
2739                            encodedcontroller = _lev_ctrl_CC117_EXT;
2740                            break;
2741                        case 118:
2742                            encodedcontroller = _lev_ctrl_CC118_EXT;
2743                            break;
2744                        case 119:
2745                            encodedcontroller = _lev_ctrl_CC119_EXT;
2746                            break;
2747    
2748                      default:                      default:
2749                          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");
2750                  }                  }
2751                    break;
2752              default:              default:
2753                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2754          }          }
# Line 1998  namespace { Line 2794  namespace {
2794          return pVelocityCutoffTable[MIDIKeyVelocity];          return pVelocityCutoffTable[MIDIKeyVelocity];
2795      }      }
2796    
2797        /**
2798         * Updates the respective member variable and the lookup table / cache
2799         * that depends on this value.
2800         */
2801        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2802            pVelocityAttenuationTable =
2803                GetVelocityTable(
2804                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2805                );
2806            VelocityResponseCurve = curve;
2807        }
2808    
2809        /**
2810         * Updates the respective member variable and the lookup table / cache
2811         * that depends on this value.
2812         */
2813        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2814            pVelocityAttenuationTable =
2815                GetVelocityTable(
2816                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2817                );
2818            VelocityResponseDepth = depth;
2819        }
2820    
2821        /**
2822         * Updates the respective member variable and the lookup table / cache
2823         * that depends on this value.
2824         */
2825        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2826            pVelocityAttenuationTable =
2827                GetVelocityTable(
2828                    VelocityResponseCurve, VelocityResponseDepth, scaling
2829                );
2830            VelocityResponseCurveScaling = scaling;
2831        }
2832    
2833        /**
2834         * Updates the respective member variable and the lookup table / cache
2835         * that depends on this value.
2836         */
2837        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2838            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2839            ReleaseVelocityResponseCurve = curve;
2840        }
2841    
2842        /**
2843         * Updates the respective member variable and the lookup table / cache
2844         * that depends on this value.
2845         */
2846        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2847            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2848            ReleaseVelocityResponseDepth = depth;
2849        }
2850    
2851        /**
2852         * Updates the respective member variable and the lookup table / cache
2853         * that depends on this value.
2854         */
2855        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2856            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2857            VCFCutoffController = controller;
2858        }
2859    
2860        /**
2861         * Updates the respective member variable and the lookup table / cache
2862         * that depends on this value.
2863         */
2864        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2865            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2866            VCFVelocityCurve = curve;
2867        }
2868    
2869        /**
2870         * Updates the respective member variable and the lookup table / cache
2871         * that depends on this value.
2872         */
2873        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2874            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2875            VCFVelocityDynamicRange = range;
2876        }
2877    
2878        /**
2879         * Updates the respective member variable and the lookup table / cache
2880         * that depends on this value.
2881         */
2882        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2883            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2884            VCFVelocityScale = scaling;
2885        }
2886    
2887      double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {      double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
2888    
2889          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 2070  namespace { Line 2956  namespace {
2956  // *  // *
2957    
2958      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
         pInfo->UseFixedLengthStrings = true;  
   
2959          // Initialization          // Initialization
2960          Dimensions = 0;          Dimensions = 0;
2961          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
# Line 2083  namespace { Line 2967  namespace {
2967    
2968          // Actual Loading          // Actual Loading
2969    
2970            if (!file->GetAutoLoad()) return;
2971    
2972          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2973    
2974          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2091  namespace { Line 2977  namespace {
2977              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2978                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2979                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2980                  _3lnk->ReadUint8(); // probably the position of the dimension                  _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2981                  _3lnk->ReadUint8(); // unknown                  _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2982                  uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)                  uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2983                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2984                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
# Line 2105  namespace { Line 2991  namespace {
2991                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2992                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2993                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2994                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2995                                                             dimension == dimension_samplechannel ||                      pDimensionDefinitions[i].zone_size  = __resolveZoneSize(pDimensionDefinitions[i]);
                                                            dimension == dimension_releasetrigger ||  
                                                            dimension == dimension_keyboard ||  
                                                            dimension == dimension_roundrobin ||  
                                                            dimension == dimension_random) ? split_type_bit  
                                                                                           : split_type_normal;  
                     pDimensionDefinitions[i].zone_size  =  
                         (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones  
                                                                                    : 0;  
2996                      Dimensions++;                      Dimensions++;
2997    
2998                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
# Line 2134  namespace { Line 3012  namespace {
3012              else              else
3013                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
3014    
3015              // load sample references              // load sample references (if auto loading is enabled)
3016              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
3017                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
3018                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
3019                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
3020                    }
3021                    GetSample(); // load global region sample reference
3022                }
3023            } else {
3024                DimensionRegions = 0;
3025                for (int i = 0 ; i < 8 ; i++) {
3026                    pDimensionDefinitions[i].dimension  = dimension_none;
3027                    pDimensionDefinitions[i].bits       = 0;
3028                    pDimensionDefinitions[i].zones      = 0;
3029              }              }
             GetSample(); // load global region sample reference  
3030          }          }
3031    
3032          // make sure there is at least one dimension region          // make sure there is at least one dimension region
# Line 2147  namespace { Line 3034  namespace {
3034              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
3035              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
3036              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
3037              pDimensionRegions[0] = new DimensionRegion(_3ewl);              pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
3038              DimensionRegions = 1;              DimensionRegions = 1;
3039          }          }
3040      }      }
# Line 2159  namespace { Line 3046  namespace {
3046       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
3047       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
3048       *       *
3049         * @param pProgress - callback function for progress notification
3050       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3051       */       */
3052      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
3053            // in the gig format we don't care about the Region's sample reference
3054            // but we still have to provide some existing one to not corrupt the
3055            // file, so to avoid the latter we simply always assign the sample of
3056            // the first dimension region of this region
3057            pSample = pDimensionRegions[0]->pSample;
3058    
3059          // first update base class's chunks          // first update base class's chunks
3060          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks(pProgress);
3061    
3062          // update dimension region's chunks          // update dimension region's chunks
3063          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
3064              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks(pProgress);
3065          }          }
3066    
3067          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
3068          const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;          bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
3069          const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;          const int iMaxDimensions =  version3 ? 8 : 5;
3070            const int iMaxDimensionRegions = version3 ? 256 : 32;
3071    
3072          // make sure '3lnk' chunk exists          // make sure '3lnk' chunk exists
3073          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
3074          if (!_3lnk) {          if (!_3lnk) {
3075              const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;              const int _3lnkChunkSize = version3 ? 1092 : 172;
3076              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3077                memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3078    
3079                // move 3prg to last position
3080                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3081          }          }
3082    
3083          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
3084          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
3085          memcpy(&pData[0], &DimensionRegions, 4);          store32(&pData[0], DimensionRegions);
3086            int shift = 0;
3087          for (int i = 0; i < iMaxDimensions; i++) {          for (int i = 0; i < iMaxDimensions; i++) {
3088              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3089              pData[5 + i * 8] = pDimensionDefinitions[i].bits;              pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3090              // next 2 bytes unknown              pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3091                pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3092              pData[8 + i * 8] = pDimensionDefinitions[i].zones;              pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3093              // next 3 bytes unknown              // next 3 bytes unknown, always zero?
3094    
3095                shift += pDimensionDefinitions[i].bits;
3096          }          }
3097    
3098          // update wave pool table in '3lnk' chunk          // update wave pool table in '3lnk' chunk
3099          const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;          const int iWavePoolOffset = version3 ? 68 : 44;
3100          for (uint i = 0; i < iMaxDimensionRegions; i++) {          for (uint i = 0; i < iMaxDimensionRegions; i++) {
3101              int iWaveIndex = -1;              int iWaveIndex = -1;
3102              if (i < DimensionRegions) {              if (i < DimensionRegions) {
# Line 2206  namespace { Line 3109  namespace {
3109                          break;                          break;
3110                      }                      }
3111                  }                  }
                 if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");  
3112              }              }
3113              memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3114          }          }
3115      }      }
3116    
# Line 2219  namespace { Line 3121  namespace {
3121              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
3122              while (_3ewl) {              while (_3ewl) {
3123                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3124                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3125                      dimensionRegionNr++;                      dimensionRegionNr++;
3126                  }                  }
3127                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 2228  namespace { Line 3130  namespace {
3130          }          }
3131      }      }
3132    
3133        void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3134            // update KeyRange struct and make sure regions are in correct order
3135            DLS::Region::SetKeyRange(Low, High);
3136            // update Region key table for fast lookup
3137            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3138        }
3139    
3140      void Region::UpdateVelocityTable() {      void Region::UpdateVelocityTable() {
3141          // get velocity dimension's index          // get velocity dimension's index
3142          int veldim = -1;          int veldim = -1;
# Line 2242  namespace { Line 3151  namespace {
3151          int step = 1;          int step = 1;
3152          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3153          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3154    
3155          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3156          int dim[8] = { 0 };          int dim[8] = { 0 };
3157          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3158                const int end = i + step * pDimensionDefinitions[veldim].zones;
3159    
3160              if (pDimensionRegions[i]->VelocityUpperLimit) {              // create a velocity table for all cases where the velocity zone is zero
3161                if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3162                    pDimensionRegions[i]->VelocityUpperLimit) {
3163                  // create the velocity table                  // create the velocity table
3164                  uint8_t* table = pDimensionRegions[i]->VelocityTable;                  uint8_t* table = pDimensionRegions[i]->VelocityTable;
3165                  if (!table) {                  if (!table) {
# Line 2257  namespace { Line 3168  namespace {
3168                  }                  }
3169                  int tableidx = 0;                  int tableidx = 0;
3170                  int velocityZone = 0;                  int velocityZone = 0;
3171                  for (int k = i ; k < end ; k += step) {                  if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
3172                      DimensionRegion *d = pDimensionRegions[k];                      for (int k = i ; k < end ; k += step) {
3173                      for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;                          DimensionRegion *d = pDimensionRegions[k];
3174                      velocityZone++;                          for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
3175                            velocityZone++;
3176                        }
3177                    } else { // gig2
3178                        for (int k = i ; k < end ; k += step) {
3179                            DimensionRegion *d = pDimensionRegions[k];
3180                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
3181                            velocityZone++;
3182                        }
3183                  }                  }
3184              } else {              } else {
3185                  if (pDimensionRegions[i]->VelocityTable) {                  if (pDimensionRegions[i]->VelocityTable) {
# Line 2269  namespace { Line 3188  namespace {
3188                  }                  }
3189              }              }
3190    
3191                // jump to the next case where the velocity zone is zero
3192              int j;              int j;
3193              int shift = 0;              int shift = 0;
3194              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 2305  namespace { Line 3225  namespace {
3225       *                        dimension bits limit is violated       *                        dimension bits limit is violated
3226       */       */
3227      void Region::AddDimension(dimension_def_t* pDimDef) {      void Region::AddDimension(dimension_def_t* pDimDef) {
3228            // some initial sanity checks of the given dimension definition
3229            if (pDimDef->zones < 2)
3230                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3231            if (pDimDef->bits < 1)
3232                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3233            if (pDimDef->dimension == dimension_samplechannel) {
3234                if (pDimDef->zones != 2)
3235                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3236                if (pDimDef->bits != 1)
3237                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3238            }
3239    
3240          // check if max. amount of dimensions reached          // check if max. amount of dimensions reached
3241          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3242          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
# Line 2324  namespace { Line 3256  namespace {
3256              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3257                  throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");                  throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
3258    
3259            // pos is where the new dimension should be placed, normally
3260            // last in list, except for the samplechannel dimension which
3261            // has to be first in list
3262            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3263            int bitpos = 0;
3264            for (int i = 0 ; i < pos ; i++)
3265                bitpos += pDimensionDefinitions[i].bits;
3266    
3267            // make room for the new dimension
3268            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3269            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3270                for (int j = Dimensions ; j > pos ; j--) {
3271                    pDimensionRegions[i]->DimensionUpperLimits[j] =
3272                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
3273                }
3274            }
3275    
3276          // assign definition of new dimension          // assign definition of new dimension
3277          pDimensionDefinitions[Dimensions] = *pDimDef;          pDimensionDefinitions[pos] = *pDimDef;
3278    
3279          // create new dimension region(s) for this new dimension          // auto correct certain dimension definition fields (where possible)
3280          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {          pDimensionDefinitions[pos].split_type  =
3281              //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values              __resolveSplitType(pDimensionDefinitions[pos].dimension);
3282              RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);          pDimensionDefinitions[pos].zone_size =
3283              pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);              __resolveZoneSize(pDimensionDefinitions[pos]);
3284              DimensionRegions++;  
3285            // create new dimension region(s) for this new dimension, and make
3286            // sure that the dimension regions are placed correctly in both the
3287            // RIFF list and the pDimensionRegions array
3288            RIFF::Chunk* moveTo = NULL;
3289            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3290            for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3291                for (int k = 0 ; k < (1 << bitpos) ; k++) {
3292                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3293                }
3294                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3295                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
3296                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3297                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3298                        // create a new dimension region and copy all parameter values from
3299                        // an existing dimension region
3300                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3301                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3302    
3303                        DimensionRegions++;
3304                    }
3305                }
3306                moveTo = pDimensionRegions[i]->pParentList;
3307            }
3308    
3309            // initialize the upper limits for this dimension
3310            int mask = (1 << bitpos) - 1;
3311            for (int z = 0 ; z < pDimDef->zones ; z++) {
3312                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3313                for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3314                    pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3315                                      (z << bitpos) |
3316                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3317                }
3318          }          }
3319    
3320          Dimensions++;          Dimensions++;
# Line 2375  namespace { Line 3357  namespace {
3357          for (int i = iDimensionNr + 1; i < Dimensions; i++)          for (int i = iDimensionNr + 1; i < Dimensions; i++)
3358              iUpperBits += pDimensionDefinitions[i].bits;              iUpperBits += pDimensionDefinitions[i].bits;
3359    
3360            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3361    
3362          // delete dimension regions which belong to the given dimension          // delete dimension regions which belong to the given dimension
3363          // (that is where the dimension's bit > 0)          // (that is where the dimension's bit > 0)
3364          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
# Line 2383  namespace { Line 3367  namespace {
3367                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3368                                      iObsoleteBit << iLowerBits |                                      iObsoleteBit << iLowerBits |
3369                                      iLowerBit;                                      iLowerBit;
3370    
3371                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3372                      delete pDimensionRegions[iToDelete];                      delete pDimensionRegions[iToDelete];
3373                      pDimensionRegions[iToDelete] = NULL;                      pDimensionRegions[iToDelete] = NULL;
3374                      DimensionRegions--;                      DimensionRegions--;
# Line 2403  namespace { Line 3389  namespace {
3389              }              }
3390          }          }
3391    
3392            // remove the this dimension from the upper limits arrays
3393            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3394                DimensionRegion* d = pDimensionRegions[j];
3395                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3396                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
3397                }
3398                d->DimensionUpperLimits[Dimensions - 1] = 127;
3399            }
3400    
3401          // 'remove' dimension definition          // 'remove' dimension definition
3402          for (int i = iDimensionNr + 1; i < Dimensions; i++) {          for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3403              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
# Line 2417  namespace { Line 3412  namespace {
3412          if (pDimDef->dimension == dimension_layer) Layers = 1;          if (pDimDef->dimension == dimension_layer) Layers = 1;
3413      }      }
3414    
3415        /** @brief Delete one split zone of a dimension (decrement zone amount).
3416         *
3417         * Instead of deleting an entire dimensions, this method will only delete
3418         * one particular split zone given by @a zone of the Region's dimension
3419         * given by @a type. So this method will simply decrement the amount of
3420         * zones by one of the dimension in question. To be able to do that, the
3421         * respective dimension must exist on this Region and it must have at least
3422         * 3 zones. All DimensionRegion objects associated with the zone will be
3423         * deleted.
3424         *
3425         * @param type - identifies the dimension where a zone shall be deleted
3426         * @param zone - index of the dimension split zone that shall be deleted
3427         * @throws gig::Exception if requested zone could not be deleted
3428         */
3429        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3430            dimension_def_t* oldDef = GetDimensionDefinition(type);
3431            if (!oldDef)
3432                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3433            if (oldDef->zones <= 2)
3434                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3435            if (zone < 0 || zone >= oldDef->zones)
3436                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3437    
3438            const int newZoneSize = oldDef->zones - 1;
3439    
3440            // create a temporary Region which just acts as a temporary copy
3441            // container and will be deleted at the end of this function and will
3442            // also not be visible through the API during this process
3443            gig::Region* tempRgn = NULL;
3444            {
3445                // adding these temporary chunks is probably not even necessary
3446                Instrument* instr = static_cast<Instrument*>(GetParent());
3447                RIFF::List* pCkInstrument = instr->pCkInstrument;
3448                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3449                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3450                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3451                tempRgn = new Region(instr, rgn);
3452            }
3453    
3454            // copy this region's dimensions (with already the dimension split size
3455            // requested by the arguments of this method call) to the temporary
3456            // region, and don't use Region::CopyAssign() here for this task, since
3457            // it would also alter fast lookup helper variables here and there
3458            dimension_def_t newDef;
3459            for (int i = 0; i < Dimensions; ++i) {
3460                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3461                // is this the dimension requested by the method arguments? ...
3462                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3463                    def.zones = newZoneSize;
3464                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3465                    newDef = def;
3466                }
3467                tempRgn->AddDimension(&def);
3468            }
3469    
3470            // find the dimension index in the tempRegion which is the dimension
3471            // type passed to this method (paranoidly expecting different order)
3472            int tempReducedDimensionIndex = -1;
3473            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3474                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3475                    tempReducedDimensionIndex = d;
3476                    break;
3477                }
3478            }
3479    
3480            // copy dimension regions from this region to the temporary region
3481            for (int iDst = 0; iDst < 256; ++iDst) {
3482                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3483                if (!dstDimRgn) continue;
3484                std::map<dimension_t,int> dimCase;
3485                bool isValidZone = true;
3486                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3487                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3488                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3489                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3490                    baseBits += dstBits;
3491                    // there are also DimensionRegion objects of unused zones, skip them
3492                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3493                        isValidZone = false;
3494                        break;
3495                    }
3496                }
3497                if (!isValidZone) continue;
3498                // a bit paranoid: cope with the chance that the dimensions would
3499                // have different order in source and destination regions
3500                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3501                if (dimCase[type] >= zone) dimCase[type]++;
3502                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3503                dstDimRgn->CopyAssign(srcDimRgn);
3504                // if this is the upper most zone of the dimension passed to this
3505                // method, then correct (raise) its upper limit to 127
3506                if (newDef.split_type == split_type_normal && isLastZone)
3507                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3508            }
3509    
3510            // now tempRegion's dimensions and DimensionRegions basically reflect
3511            // what we wanted to get for this actual Region here, so we now just
3512            // delete and recreate the dimension in question with the new amount
3513            // zones and then copy back from tempRegion      
3514            DeleteDimension(oldDef);
3515            AddDimension(&newDef);
3516            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3517                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3518                if (!srcDimRgn) continue;
3519                std::map<dimension_t,int> dimCase;
3520                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3521                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3522                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3523                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3524                    baseBits += srcBits;
3525                }
3526                // a bit paranoid: cope with the chance that the dimensions would
3527                // have different order in source and destination regions
3528                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3529                if (!dstDimRgn) continue;
3530                dstDimRgn->CopyAssign(srcDimRgn);
3531            }
3532    
3533            // delete temporary region
3534            delete tempRgn;
3535    
3536            UpdateVelocityTable();
3537        }
3538    
3539        /** @brief Divide split zone of a dimension in two (increment zone amount).
3540         *
3541         * This will increment the amount of zones for the dimension (given by
3542         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3543         * in the middle of its zone range in two. So the two zones resulting from
3544         * the zone being splitted, will be an equivalent copy regarding all their
3545         * articulation informations and sample reference. The two zones will only
3546         * differ in their zone's upper limit
3547         * (DimensionRegion::DimensionUpperLimits).
3548         *
3549         * @param type - identifies the dimension where a zone shall be splitted
3550         * @param zone - index of the dimension split zone that shall be splitted
3551         * @throws gig::Exception if requested zone could not be splitted
3552         */
3553        void Region::SplitDimensionZone(dimension_t type, int zone) {
3554            dimension_def_t* oldDef = GetDimensionDefinition(type);
3555            if (!oldDef)
3556                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3557            if (zone < 0 || zone >= oldDef->zones)
3558                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3559    
3560            const int newZoneSize = oldDef->zones + 1;
3561    
3562            // create a temporary Region which just acts as a temporary copy
3563            // container and will be deleted at the end of this function and will
3564            // also not be visible through the API during this process
3565            gig::Region* tempRgn = NULL;
3566            {
3567                // adding these temporary chunks is probably not even necessary
3568                Instrument* instr = static_cast<Instrument*>(GetParent());
3569                RIFF::List* pCkInstrument = instr->pCkInstrument;
3570                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3571                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3572                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3573                tempRgn = new Region(instr, rgn);
3574            }
3575    
3576            // copy this region's dimensions (with already the dimension split size
3577            // requested by the arguments of this method call) to the temporary
3578            // region, and don't use Region::CopyAssign() here for this task, since
3579            // it would also alter fast lookup helper variables here and there
3580            dimension_def_t newDef;
3581            for (int i = 0; i < Dimensions; ++i) {
3582                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3583                // is this the dimension requested by the method arguments? ...
3584                if (def.dimension == type) { // ... if yes, increment zone amount by one
3585                    def.zones = newZoneSize;
3586                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3587                    newDef = def;
3588                }
3589                tempRgn->AddDimension(&def);
3590            }
3591    
3592            // find the dimension index in the tempRegion which is the dimension
3593            // type passed to this method (paranoidly expecting different order)
3594            int tempIncreasedDimensionIndex = -1;
3595            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3596                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3597                    tempIncreasedDimensionIndex = d;
3598                    break;
3599                }
3600            }
3601    
3602            // copy dimension regions from this region to the temporary region
3603            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3604                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3605                if (!srcDimRgn) continue;
3606                std::map<dimension_t,int> dimCase;
3607                bool isValidZone = true;
3608                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3609                    const int srcBits = pDimensionDefinitions[d].bits;
3610                    dimCase[pDimensionDefinitions[d].dimension] =
3611                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3612                    // there are also DimensionRegion objects for unused zones, skip them
3613                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3614                        isValidZone = false;
3615                        break;
3616                    }
3617                    baseBits += srcBits;
3618                }
3619                if (!isValidZone) continue;
3620                // a bit paranoid: cope with the chance that the dimensions would
3621                // have different order in source and destination regions            
3622                if (dimCase[type] > zone) dimCase[type]++;
3623                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3624                dstDimRgn->CopyAssign(srcDimRgn);
3625                // if this is the requested zone to be splitted, then also copy
3626                // the source DimensionRegion to the newly created target zone
3627                // and set the old zones upper limit lower
3628                if (dimCase[type] == zone) {
3629                    // lower old zones upper limit
3630                    if (newDef.split_type == split_type_normal) {
3631                        const int high =
3632                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3633                        int low = 0;
3634                        if (zone > 0) {
3635                            std::map<dimension_t,int> lowerCase = dimCase;
3636                            lowerCase[type]--;
3637                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3638                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3639                        }
3640                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3641                    }
3642                    // fill the newly created zone of the divided zone as well
3643                    dimCase[type]++;
3644                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3645                    dstDimRgn->CopyAssign(srcDimRgn);
3646                }
3647            }
3648    
3649            // now tempRegion's dimensions and DimensionRegions basically reflect
3650            // what we wanted to get for this actual Region here, so we now just
3651            // delete and recreate the dimension in question with the new amount
3652            // zones and then copy back from tempRegion      
3653            DeleteDimension(oldDef);
3654            AddDimension(&newDef);
3655            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3656                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3657                if (!srcDimRgn) continue;
3658                std::map<dimension_t,int> dimCase;
3659                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3660                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3661                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3662                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3663                    baseBits += srcBits;
3664                }
3665                // a bit paranoid: cope with the chance that the dimensions would
3666                // have different order in source and destination regions
3667                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3668                if (!dstDimRgn) continue;
3669                dstDimRgn->CopyAssign(srcDimRgn);
3670            }
3671    
3672            // delete temporary region
3673            delete tempRgn;
3674    
3675            UpdateVelocityTable();
3676        }
3677    
3678        /** @brief Change type of an existing dimension.
3679         *
3680         * Alters the dimension type of a dimension already existing on this
3681         * region. If there is currently no dimension on this Region with type
3682         * @a oldType, then this call with throw an Exception. Likewise there are
3683         * cases where the requested dimension type cannot be performed. For example
3684         * if the new dimension type shall be gig::dimension_samplechannel, and the
3685         * current dimension has more than 2 zones. In such cases an Exception is
3686         * thrown as well.
3687         *
3688         * @param oldType - identifies the existing dimension to be changed
3689         * @param newType - to which dimension type it should be changed to
3690         * @throws gig::Exception if requested change cannot be performed
3691         */
3692        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3693            if (oldType == newType) return;
3694            dimension_def_t* def = GetDimensionDefinition(oldType);
3695            if (!def)
3696                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3697            if (newType == dimension_samplechannel && def->zones != 2)
3698                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3699            if (GetDimensionDefinition(newType))
3700                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3701            def->dimension  = newType;
3702            def->split_type = __resolveSplitType(newType);
3703        }
3704    
3705        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3706            uint8_t bits[8] = {};
3707            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3708                 it != DimCase.end(); ++it)
3709            {
3710                for (int d = 0; d < Dimensions; ++d) {
3711                    if (pDimensionDefinitions[d].dimension == it->first) {
3712                        bits[d] = it->second;
3713                        goto nextDimCaseSlice;
3714                    }
3715                }
3716                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3717                nextDimCaseSlice:
3718                ; // noop
3719            }
3720            return GetDimensionRegionByBit(bits);
3721        }
3722    
3723        /**
3724         * Searches in the current Region for a dimension of the given dimension
3725         * type and returns the precise configuration of that dimension in this
3726         * Region.
3727         *
3728         * @param type - dimension type of the sought dimension
3729         * @returns dimension definition or NULL if there is no dimension with
3730         *          sought type in this Region.
3731         */
3732        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3733            for (int i = 0; i < Dimensions; ++i)
3734                if (pDimensionDefinitions[i].dimension == type)
3735                    return &pDimensionDefinitions[i];
3736            return NULL;
3737        }
3738    
3739      Region::~Region() {      Region::~Region() {
3740          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
3741              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
# Line 2455  namespace { Line 3774  namespace {
3774              } else {              } else {
3775                  switch (pDimensionDefinitions[i].split_type) {                  switch (pDimensionDefinitions[i].split_type) {
3776                      case split_type_normal:                      case split_type_normal:
3777                          bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3778                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3779                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3780                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3781                                }
3782                            } else {
3783                                // gig2: evenly sized zones
3784                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3785                            }
3786                          break;                          break;
3787                      case split_type_bit: // the value is already the sought dimension bit number                      case split_type_bit: // the value is already the sought dimension bit number
3788                          const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                          const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
# Line 2466  namespace { Line 3793  namespace {
3793              }              }
3794              bitpos += pDimensionDefinitions[i].bits;              bitpos += pDimensionDefinitions[i].bits;
3795          }          }
3796          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3797            if (!dimreg) return NULL;
3798          if (veldim != -1) {          if (veldim != -1) {
3799              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3800              if (dimreg->VelocityUpperLimit) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3801                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3802              else // normal split type              else // normal split type
3803                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3804    
3805              dimregidx |= bits << velbitpos;              const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3806              dimreg = pDimensionRegions[dimregidx];              dimregidx |= (bits & limiter_mask) << velbitpos;
3807                dimreg = pDimensionRegions[dimregidx & 255];
3808          }          }
3809          return dimreg;          return dimreg;
3810      }      }
3811    
3812        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3813            uint8_t bits;
3814            int veldim = -1;
3815            int velbitpos;
3816            int bitpos = 0;
3817            int dimregidx = 0;
3818            for (uint i = 0; i < Dimensions; i++) {
3819                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3820                    // the velocity dimension must be handled after the other dimensions
3821                    veldim = i;
3822                    velbitpos = bitpos;
3823                } else {
3824                    switch (pDimensionDefinitions[i].split_type) {
3825                        case split_type_normal:
3826                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3827                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3828                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3829                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3830                                }
3831                            } else {
3832                                // gig2: evenly sized zones
3833                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3834                            }
3835                            break;
3836                        case split_type_bit: // the value is already the sought dimension bit number
3837                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3838                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3839                            break;
3840                    }
3841                    dimregidx |= bits << bitpos;
3842                }
3843                bitpos += pDimensionDefinitions[i].bits;
3844            }
3845            dimregidx &= 255;
3846            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3847            if (!dimreg) return -1;
3848            if (veldim != -1) {
3849                // (dimreg is now the dimension region for the lowest velocity)
3850                if (dimreg->VelocityTable) // custom defined zone ranges
3851                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3852                else // normal split type
3853                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3854    
3855                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3856                dimregidx |= (bits & limiter_mask) << velbitpos;
3857                dimregidx &= 255;
3858            }
3859            return dimregidx;
3860        }
3861    
3862      /**      /**
3863       * Returns the appropriate DimensionRegion for the given dimension bit       * Returns the appropriate DimensionRegion for the given dimension bit
3864       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
# Line 2518  namespace { Line 3897  namespace {
3897          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
3898          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3899          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
3900          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
3901          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
3902          Sample* sample = file->GetFirstSample(pProgress);              // use 64 bit wave pool offsets (treating this as large file)
3903          while (sample) {              uint64_t soughtoffset =
3904              if (sample->ulWavePoolOffset == soughtoffset &&                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
3905                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
3906              sample = file->GetNextSample();              Sample* sample = file->GetFirstSample(pProgress);
3907                while (sample) {
3908                    if (sample->ullWavePoolOffset == soughtoffset)
3909                        return static_cast<gig::Sample*>(sample);
3910                    sample = file->GetNextSample();
3911                }
3912            } else {
3913                // use extension files and 32 bit wave pool offsets
3914                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3915                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3916                Sample* sample = file->GetFirstSample(pProgress);
3917                while (sample) {
3918                    if (sample->ullWavePoolOffset == soughtoffset &&
3919                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3920                    sample = file->GetNextSample();
3921                }
3922          }          }
3923          return NULL;          return NULL;
3924      }      }
3925        
3926        /**
3927         * Make a (semi) deep copy of the Region object given by @a orig
3928         * and assign it to this object.
3929         *
3930         * Note that all sample pointers referenced by @a orig are simply copied as
3931         * memory address. Thus the respective samples are shared, not duplicated!
3932         *
3933         * @param orig - original Region object to be copied from
3934         */
3935        void Region::CopyAssign(const Region* orig) {
3936            CopyAssign(orig, NULL);
3937        }
3938        
3939        /**
3940         * Make a (semi) deep copy of the Region object given by @a orig and
3941         * assign it to this object
3942         *
3943         * @param mSamples - crosslink map between the foreign file's samples and
3944         *                   this file's samples
3945         */
3946        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3947            // handle base classes
3948            DLS::Region::CopyAssign(orig);
3949            
3950            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3951                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3952            }
3953            
3954            // handle own member variables
3955            for (int i = Dimensions - 1; i >= 0; --i) {
3956                DeleteDimension(&pDimensionDefinitions[i]);
3957            }
3958            Layers = 0; // just to be sure
3959            for (int i = 0; i < orig->Dimensions; i++) {
3960                // we need to copy the dim definition here, to avoid the compiler
3961                // complaining about const-ness issue
3962                dimension_def_t def = orig->pDimensionDefinitions[i];
3963                AddDimension(&def);
3964            }
3965            for (int i = 0; i < 256; i++) {
3966                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3967                    pDimensionRegions[i]->CopyAssign(
3968                        orig->pDimensionRegions[i],
3969                        mSamples
3970                    );
3971                }
3972            }
3973            Layers = orig->Layers;
3974        }
3975    
3976    
3977    // *************** MidiRule ***************
3978    // *
3979    
3980        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3981            _3ewg->SetPos(36);
3982            Triggers = _3ewg->ReadUint8();
3983            _3ewg->SetPos(40);
3984            ControllerNumber = _3ewg->ReadUint8();
3985            _3ewg->SetPos(46);
3986            for (int i = 0 ; i < Triggers ; i++) {
3987                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3988                pTriggers[i].Descending = _3ewg->ReadUint8();
3989                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3990                pTriggers[i].Key = _3ewg->ReadUint8();
3991                pTriggers[i].NoteOff = _3ewg->ReadUint8();
3992                pTriggers[i].Velocity = _3ewg->ReadUint8();
3993                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3994                _3ewg->ReadUint8();
3995            }
3996        }
3997    
3998        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3999            ControllerNumber(0),
4000            Triggers(0) {
4001        }
4002    
4003        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
4004            pData[32] = 4;
4005            pData[33] = 16;
4006            pData[36] = Triggers;
4007            pData[40] = ControllerNumber;
4008            for (int i = 0 ; i < Triggers ; i++) {
4009                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
4010                pData[47 + i * 8] = pTriggers[i].Descending;
4011                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
4012                pData[49 + i * 8] = pTriggers[i].Key;
4013                pData[50 + i * 8] = pTriggers[i].NoteOff;
4014                pData[51 + i * 8] = pTriggers[i].Velocity;
4015                pData[52 + i * 8] = pTriggers[i].OverridePedal;
4016            }
4017        }
4018    
4019        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
4020            _3ewg->SetPos(36);
4021            LegatoSamples = _3ewg->ReadUint8(); // always 12
4022            _3ewg->SetPos(40);
4023            BypassUseController = _3ewg->ReadUint8();
4024            BypassKey = _3ewg->ReadUint8();
4025            BypassController = _3ewg->ReadUint8();
4026            ThresholdTime = _3ewg->ReadUint16();
4027            _3ewg->ReadInt16();
4028            ReleaseTime = _3ewg->ReadUint16();
4029            _3ewg->ReadInt16();
4030            KeyRange.low = _3ewg->ReadUint8();
4031            KeyRange.high = _3ewg->ReadUint8();
4032            _3ewg->SetPos(64);
4033            ReleaseTriggerKey = _3ewg->ReadUint8();
4034            AltSustain1Key = _3ewg->ReadUint8();
4035            AltSustain2Key = _3ewg->ReadUint8();
4036        }
4037    
4038        MidiRuleLegato::MidiRuleLegato() :
4039            LegatoSamples(12),
4040            BypassUseController(false),
4041            BypassKey(0),
4042            BypassController(1),
4043            ThresholdTime(20),
4044            ReleaseTime(20),
4045            ReleaseTriggerKey(0),
4046            AltSustain1Key(0),
4047            AltSustain2Key(0)
4048        {
4049            KeyRange.low = KeyRange.high = 0;
4050        }
4051    
4052        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
4053            pData[32] = 0;
4054            pData[33] = 16;
4055            pData[36] = LegatoSamples;
4056            pData[40] = BypassUseController;
4057            pData[41] = BypassKey;
4058            pData[42] = BypassController;
4059            store16(&pData[43], ThresholdTime);
4060            store16(&pData[47], ReleaseTime);
4061            pData[51] = KeyRange.low;
4062            pData[52] = KeyRange.high;
4063            pData[64] = ReleaseTriggerKey;
4064            pData[65] = AltSustain1Key;
4065            pData[66] = AltSustain2Key;
4066        }
4067    
4068        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4069            _3ewg->SetPos(36);
4070            Articulations = _3ewg->ReadUint8();
4071            int flags = _3ewg->ReadUint8();
4072            Polyphonic = flags & 8;
4073            Chained = flags & 4;
4074            Selector = (flags & 2) ? selector_controller :
4075                (flags & 1) ? selector_key_switch : selector_none;
4076            Patterns = _3ewg->ReadUint8();
4077            _3ewg->ReadUint8(); // chosen row
4078            _3ewg->ReadUint8(); // unknown
4079            _3ewg->ReadUint8(); // unknown
4080            _3ewg->ReadUint8(); // unknown
4081            KeySwitchRange.low = _3ewg->ReadUint8();
4082            KeySwitchRange.high = _3ewg->ReadUint8();
4083            Controller = _3ewg->ReadUint8();
4084            PlayRange.low = _3ewg->ReadUint8();
4085            PlayRange.high = _3ewg->ReadUint8();
4086    
4087            int n = std::min(int(Articulations), 32);
4088            for (int i = 0 ; i < n ; i++) {
4089                _3ewg->ReadString(pArticulations[i], 32);
4090            }
4091            _3ewg->SetPos(1072);
4092            n = std::min(int(Patterns), 32);
4093            for (int i = 0 ; i < n ; i++) {
4094                _3ewg->ReadString(pPatterns[i].Name, 16);
4095                pPatterns[i].Size = _3ewg->ReadUint8();
4096                _3ewg->Read(&pPatterns[i][0], 1, 32);
4097            }
4098        }
4099    
4100        MidiRuleAlternator::MidiRuleAlternator() :
4101            Articulations(0),
4102            Patterns(0),
4103            Selector(selector_none),
4104            Controller(0),
4105            Polyphonic(false),
4106            Chained(false)
4107        {
4108            PlayRange.low = PlayRange.high = 0;
4109            KeySwitchRange.low = KeySwitchRange.high = 0;
4110        }
4111    
4112        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4113            pData[32] = 3;
4114            pData[33] = 16;
4115            pData[36] = Articulations;
4116            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4117                (Selector == selector_controller ? 2 :
4118                 (Selector == selector_key_switch ? 1 : 0));
4119            pData[38] = Patterns;
4120    
4121            pData[43] = KeySwitchRange.low;
4122            pData[44] = KeySwitchRange.high;
4123            pData[45] = Controller;
4124            pData[46] = PlayRange.low;
4125            pData[47] = PlayRange.high;
4126    
4127            char* str = reinterpret_cast<char*>(pData);
4128            int pos = 48;
4129            int n = std::min(int(Articulations), 32);
4130            for (int i = 0 ; i < n ; i++, pos += 32) {
4131                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4132            }
4133    
4134            pos = 1072;
4135            n = std::min(int(Patterns), 32);
4136            for (int i = 0 ; i < n ; i++, pos += 49) {
4137                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4138                pData[pos + 16] = pPatterns[i].Size;
4139                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4140            }
4141        }
4142    
4143    // *************** Script ***************
4144    // *
4145    
4146        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4147            pGroup = group;
4148            pChunk = ckScri;
4149            if (ckScri) { // object is loaded from file ...
4150                // read header
4151                uint32_t headerSize = ckScri->ReadUint32();
4152                Compression = (Compression_t) ckScri->ReadUint32();
4153                Encoding    = (Encoding_t) ckScri->ReadUint32();
4154                Language    = (Language_t) ckScri->ReadUint32();
4155                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4156                crc         = ckScri->ReadUint32();
4157                uint32_t nameSize = ckScri->ReadUint32();
4158                Name.resize(nameSize, ' ');
4159                for (int i = 0; i < nameSize; ++i)
4160                    Name[i] = ckScri->ReadUint8();
4161                // to handle potential future extensions of the header
4162                ckScri->SetPos(sizeof(int32_t) + headerSize);
4163                // read actual script data
4164                uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();
4165                data.resize(scriptSize);
4166                for (int i = 0; i < scriptSize; ++i)
4167                    data[i] = ckScri->ReadUint8();
4168            } else { // this is a new script object, so just initialize it as such ...
4169                Compression = COMPRESSION_NONE;
4170                Encoding = ENCODING_ASCII;
4171                Language = LANGUAGE_NKSP;
4172                Bypass   = false;
4173                crc      = 0;
4174                Name     = "Unnamed Script";
4175            }
4176        }
4177    
4178        Script::~Script() {
4179        }
4180    
4181        /**
4182         * Returns the current script (i.e. as source code) in text format.
4183         */
4184        String Script::GetScriptAsText() {
4185            String s;
4186            s.resize(data.size(), ' ');
4187            memcpy(&s[0], &data[0], data.size());
4188            return s;
4189        }
4190    
4191        /**
4192         * Replaces the current script with the new script source code text given
4193         * by @a text.
4194         *
4195         * @param text - new script source code
4196         */
4197        void Script::SetScriptAsText(const String& text) {
4198            data.resize(text.size());
4199            memcpy(&data[0], &text[0], text.size());
4200        }
4201    
4202        /**
4203         * Apply this script to the respective RIFF chunks. You have to call
4204         * File::Save() to make changes persistent.
4205         *
4206         * Usually there is absolutely no need to call this method explicitly.
4207         * It will be called automatically when File::Save() was called.
4208         *
4209         * @param pProgress - callback function for progress notification
4210         */
4211        void Script::UpdateChunks(progress_t* pProgress) {
4212            // recalculate CRC32 check sum
4213            __resetCRC(crc);
4214            __calculateCRC(&data[0], data.size(), crc);
4215            __encodeCRC(crc);
4216            // make sure chunk exists and has the required size
4217            const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size();
4218            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4219            else pChunk->Resize(chunkSize);
4220            // fill the chunk data to be written to disk
4221            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4222            int pos = 0;
4223            store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size
4224            pos += sizeof(int32_t);
4225            store32(&pData[pos], Compression);
4226            pos += sizeof(int32_t);
4227            store32(&pData[pos], Encoding);
4228            pos += sizeof(int32_t);
4229            store32(&pData[pos], Language);
4230            pos += sizeof(int32_t);
4231            store32(&pData[pos], Bypass ? 1 : 0);
4232            pos += sizeof(int32_t);
4233            store32(&pData[pos], crc);
4234            pos += sizeof(int32_t);
4235            store32(&pData[pos], Name.size());
4236            pos += sizeof(int32_t);
4237            for (int i = 0; i < Name.size(); ++i, ++pos)
4238                pData[pos] = Name[i];
4239            for (int i = 0; i < data.size(); ++i, ++pos)
4240                pData[pos] = data[i];
4241        }
4242    
4243        /**
4244         * Move this script from its current ScriptGroup to another ScriptGroup
4245         * given by @a pGroup.
4246         *
4247         * @param pGroup - script's new group
4248         */
4249        void Script::SetGroup(ScriptGroup* pGroup) {
4250            if (this->pGroup == pGroup) return;
4251            if (pChunk)
4252                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4253            this->pGroup = pGroup;
4254        }
4255    
4256        /**
4257         * Returns the script group this script currently belongs to. Each script
4258         * is a member of exactly one ScriptGroup.
4259         *
4260         * @returns current script group
4261         */
4262        ScriptGroup* Script::GetGroup() const {
4263            return pGroup;
4264        }
4265    
4266        void Script::RemoveAllScriptReferences() {
4267            File* pFile = pGroup->pFile;
4268            for (int i = 0; pFile->GetInstrument(i); ++i) {
4269                Instrument* instr = pFile->GetInstrument(i);
4270                instr->RemoveScript(this);
4271            }
4272        }
4273    
4274    // *************** ScriptGroup ***************
4275    // *
4276    
4277        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4278            pFile = file;
4279            pList = lstRTIS;
4280            pScripts = NULL;
4281            if (lstRTIS) {
4282                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4283                ::LoadString(ckName, Name);
4284            } else {
4285                Name = "Default Group";
4286            }
4287        }
4288    
4289        ScriptGroup::~ScriptGroup() {
4290            if (pScripts) {
4291                std::list<Script*>::iterator iter = pScripts->begin();
4292                std::list<Script*>::iterator end  = pScripts->end();
4293                while (iter != end) {
4294                    delete *iter;
4295                    ++iter;
4296                }
4297                delete pScripts;
4298            }
4299        }
4300    
4301        /**
4302         * Apply this script group to the respective RIFF chunks. You have to call
4303         * File::Save() to make changes persistent.
4304         *
4305         * Usually there is absolutely no need to call this method explicitly.
4306         * It will be called automatically when File::Save() was called.
4307         *
4308         * @param pProgress - callback function for progress notification
4309         */
4310        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4311            if (pScripts) {
4312                if (!pList)
4313                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4314    
4315                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4316                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4317    
4318                for (std::list<Script*>::iterator it = pScripts->begin();
4319                     it != pScripts->end(); ++it)
4320                {
4321                    (*it)->UpdateChunks(pProgress);
4322                }
4323            }
4324        }
4325    
4326        /** @brief Get instrument script.
4327         *
4328         * Returns the real-time instrument script with the given index.
4329         *
4330         * @param index - number of the sought script (0..n)
4331         * @returns sought script or NULL if there's no such script
4332         */
4333        Script* ScriptGroup::GetScript(uint index) {
4334            if (!pScripts) LoadScripts();
4335            std::list<Script*>::iterator it = pScripts->begin();
4336            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4337                if (i == index) return *it;
4338            return NULL;
4339        }
4340    
4341        /** @brief Add new instrument script.
4342         *
4343         * Adds a new real-time instrument script to the file. The script is not
4344         * actually used / executed unless it is referenced by an instrument to be
4345         * used. This is similar to samples, which you can add to a file, without
4346         * an instrument necessarily actually using it.
4347         *
4348         * You have to call Save() to make this persistent to the file.
4349         *
4350         * @return new empty script object
4351         */
4352        Script* ScriptGroup::AddScript() {
4353            if (!pScripts) LoadScripts();
4354            Script* pScript = new Script(this, NULL);
4355            pScripts->push_back(pScript);
4356            return pScript;
4357        }
4358    
4359        /** @brief Delete an instrument script.
4360         *
4361         * This will delete the given real-time instrument script. References of
4362         * instruments that are using that script will be removed accordingly.
4363         *
4364         * You have to call Save() to make this persistent to the file.
4365         *
4366         * @param pScript - script to delete
4367         * @throws gig::Exception if given script could not be found
4368         */
4369        void ScriptGroup::DeleteScript(Script* pScript) {
4370            if (!pScripts) LoadScripts();
4371            std::list<Script*>::iterator iter =
4372                find(pScripts->begin(), pScripts->end(), pScript);
4373            if (iter == pScripts->end())
4374                throw gig::Exception("Could not delete script, could not find given script");
4375            pScripts->erase(iter);
4376            pScript->RemoveAllScriptReferences();
4377            if (pScript->pChunk)
4378                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4379            delete pScript;
4380        }
4381    
4382        void ScriptGroup::LoadScripts() {
4383            if (pScripts) return;
4384            pScripts = new std::list<Script*>;
4385            if (!pList) return;
4386    
4387            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4388                 ck = pList->GetNextSubChunk())
4389            {
4390                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4391                    pScripts->push_back(new Script(this, ck));
4392                }
4393            }
4394        }
4395    
4396  // *************** Instrument ***************  // *************** Instrument ***************
4397  // *  // *
4398    
4399      Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {      Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
4400          pInfo->UseFixedLengthStrings = true;          static const DLS::Info::string_length_t fixedStringLengths[] = {
4401                { CHUNK_ID_INAM, 64 },
4402                { CHUNK_ID_ISFT, 12 },
4403                { 0, 0 }
4404            };
4405            pInfo->SetFixedStringLengths(fixedStringLengths);
4406    
4407          // Initialization          // Initialization
4408          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4409            EffectSend = 0;
4410            Attenuation = 0;
4411            FineTune = 0;
4412            PitchbendRange = 0;
4413            PianoReleaseMode = false;
4414            DimensionKeyRange.low = 0;
4415            DimensionKeyRange.high = 0;
4416            pMidiRules = new MidiRule*[3];
4417            pMidiRules[0] = NULL;
4418            pScriptRefs = NULL;
4419    
4420          // Loading          // Loading
4421          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2553  namespace { Line 4430  namespace {
4430                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
4431                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
4432                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
4433    
4434                    if (_3ewg->GetSize() > 32) {
4435                        // read MIDI rules
4436                        int i = 0;
4437                        _3ewg->SetPos(32);
4438                        uint8_t id1 = _3ewg->ReadUint8();
4439                        uint8_t id2 = _3ewg->ReadUint8();
4440    
4441                        if (id2 == 16) {
4442                            if (id1 == 4) {
4443                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4444                            } else if (id1 == 0) {
4445                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4446                            } else if (id1 == 3) {
4447                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4448                            } else {
4449                                pMidiRules[i++] = new MidiRuleUnknown;
4450                            }
4451                        }
4452                        else if (id1 != 0 || id2 != 0) {
4453                            pMidiRules[i++] = new MidiRuleUnknown;
4454                        }
4455                        //TODO: all the other types of rules
4456    
4457                        pMidiRules[i] = NULL;
4458                    }
4459              }              }
4460          }          }
4461    
4462          if (!pRegions) pRegions = new RegionList;          if (pFile->GetAutoLoad()) {
4463          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);              if (!pRegions) pRegions = new RegionList;
4464          if (lrgn) {              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4465              RIFF::List* rgn = lrgn->GetFirstSubList();              if (lrgn) {
4466              while (rgn) {                  RIFF::List* rgn = lrgn->GetFirstSubList();
4467                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  while (rgn) {
4468                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                      if (rgn->GetListType() == LIST_TYPE_RGN) {
4469                      pRegions->push_back(new Region(this, rgn));                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4470                            pRegions->push_back(new Region(this, rgn));
4471                        }
4472                        rgn = lrgn->GetNextSubList();
4473                    }
4474                    // Creating Region Key Table for fast lookup
4475                    UpdateRegionKeyTable();
4476                }
4477            }
4478    
4479            // own gig format extensions
4480            RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4481            if (lst3LS) {
4482                RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4483                if (ckSCSL) {
4484                    int headerSize = ckSCSL->ReadUint32();
4485                    int slotCount  = ckSCSL->ReadUint32();
4486                    if (slotCount) {
4487                        int slotSize  = ckSCSL->ReadUint32();
4488                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4489                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4490                        for (int i = 0; i < slotCount; ++i) {
4491                            _ScriptPooolEntry e;
4492                            e.fileOffset = ckSCSL->ReadUint32();
4493                            e.bypass     = ckSCSL->ReadUint32() & 1;
4494                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4495                            scriptPoolFileOffsets.push_back(e);
4496                        }
4497                  }                  }
                 rgn = lrgn->GetNextSubList();  
4498              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
4499          }          }
4500    
4501          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4502      }      }
4503    
4504      void Instrument::UpdateRegionKeyTable() {      void Instrument::UpdateRegionKeyTable() {
4505            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4506          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
4507          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
4508          for (; iter != end; ++iter) {          for (; iter != end; ++iter) {
# Line 2586  namespace { Line 4514  namespace {
4514      }      }
4515    
4516      Instrument::~Instrument() {      Instrument::~Instrument() {
4517            for (int i = 0 ; pMidiRules[i] ; i++) {
4518                delete pMidiRules[i];
4519            }
4520            delete[] pMidiRules;
4521            if (pScriptRefs) delete pScriptRefs;
4522      }      }
4523    
4524      /**      /**
# Line 2595  namespace { Line 4528  namespace {
4528       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
4529       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
4530       *       *
4531         * @param pProgress - callback function for progress notification
4532       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
4533       */       */
4534      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
4535          // first update base classes' chunks          // first update base classes' chunks
4536          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks(pProgress);
4537    
4538          // update Regions' chunks          // update Regions' chunks
4539          {          {
4540              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
4541              RegionList::iterator end  = pRegions->end();              RegionList::iterator end  = pRegions->end();
4542              for (; iter != end; ++iter)              for (; iter != end; ++iter)
4543                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
4544          }          }
4545    
4546          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
# Line 2614  namespace { Line 4548  namespace {
4548          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
4549          // make sure '3ewg' RIFF chunk exists          // make sure '3ewg' RIFF chunk exists
4550          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4551          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);          if (!_3ewg)  {
4552                File* pFile = (File*) GetParent();
4553    
4554                // 3ewg is bigger in gig3, as it includes the iMIDI rules
4555                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
4556                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
4557                memset(_3ewg->LoadChunkData(), 0, size);
4558            }
4559          // update '3ewg' RIFF chunk          // update '3ewg' RIFF chunk
4560          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
4561          memcpy(&pData[0], &EffectSend, 2);          store16(&pData[0], EffectSend);
4562          memcpy(&pData[2], &Attenuation, 4);          store32(&pData[2], Attenuation);
4563          memcpy(&pData[6], &FineTune, 2);          store16(&pData[6], FineTune);
4564          memcpy(&pData[8], &PitchbendRange, 2);          store16(&pData[8], PitchbendRange);
4565          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |          const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
4566                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
4567          memcpy(&pData[10], &dimkeystart, 1);          pData[10] = dimkeystart;
4568          memcpy(&pData[11], &DimensionKeyRange.high, 1);          pData[11] = DimensionKeyRange.high;
4569    
4570            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4571                pData[32] = 0;
4572                pData[33] = 0;
4573            } else {
4574                for (int i = 0 ; pMidiRules[i] ; i++) {
4575                    pMidiRules[i]->UpdateChunks(pData);
4576                }
4577            }
4578    
4579            // own gig format extensions
4580           if (ScriptSlotCount()) {
4581               // make sure we have converted the original loaded script file
4582               // offsets into valid Script object pointers
4583               LoadScripts();
4584    
4585               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4586               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4587               const int slotCount = pScriptRefs->size();
4588               const int headerSize = 3 * sizeof(uint32_t);
4589               const int slotSize  = 2 * sizeof(uint32_t);
4590               const int totalChunkSize = headerSize + slotCount * slotSize;
4591               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4592               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4593               else ckSCSL->Resize(totalChunkSize);
4594               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4595               int pos = 0;
4596               store32(&pData[pos], headerSize);
4597               pos += sizeof(uint32_t);
4598               store32(&pData[pos], slotCount);
4599               pos += sizeof(uint32_t);
4600               store32(&pData[pos], slotSize);
4601               pos += sizeof(uint32_t);
4602               for (int i = 0; i < slotCount; ++i) {
4603                   // arbitrary value, the actual file offset will be updated in
4604                   // UpdateScriptFileOffsets() after the file has been resized
4605                   int bogusFileOffset = 0;
4606                   store32(&pData[pos], bogusFileOffset);
4607                   pos += sizeof(uint32_t);
4608                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4609                   pos += sizeof(uint32_t);
4610               }
4611           } else {
4612               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4613               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4614               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4615           }
4616        }
4617    
4618        void Instrument::UpdateScriptFileOffsets() {
4619           // own gig format extensions
4620           if (pScriptRefs && pScriptRefs->size() > 0) {
4621               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4622               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4623               const int slotCount = pScriptRefs->size();
4624               const int headerSize = 3 * sizeof(uint32_t);
4625               ckSCSL->SetPos(headerSize);
4626               for (int i = 0; i < slotCount; ++i) {
4627                   uint32_t fileOffset =
4628                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4629                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4630                        CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize());
4631                   ckSCSL->WriteUint32(&fileOffset);
4632                   // jump over flags entry (containing the bypass flag)
4633                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4634               }
4635           }        
4636      }      }
4637    
4638      /**      /**
# Line 2635  namespace { Line 4643  namespace {
4643       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
4644       */       */
4645      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
4646          if (!pRegions || !pRegions->size() || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
4647          return RegionKeyTable[Key];          return RegionKeyTable[Key];
4648    
4649          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
# Line 2693  namespace { Line 4701  namespace {
4701          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4702      }      }
4703    
4704        /**
4705         * Move this instrument at the position before @arg dst.
4706         *
4707         * This method can be used to reorder the sequence of instruments in a
4708         * .gig file. This might be helpful especially on large .gig files which
4709         * contain a large number of instruments within the same .gig file. So
4710         * grouping such instruments to similar ones, can help to keep track of them
4711         * when working with such complex .gig files.
4712         *
4713         * When calling this method, this instrument will be removed from in its
4714         * current position in the instruments list and moved to the requested
4715         * target position provided by @param dst. You may also pass NULL as
4716         * argument to this method, in that case this intrument will be moved to the
4717         * very end of the .gig file's instrument list.
4718         *
4719         * You have to call Save() to make the order change persistent to the .gig
4720         * file.
4721         *
4722         * Currently this method is limited to moving the instrument within the same
4723         * .gig file. Trying to move it to another .gig file by calling this method
4724         * will throw an exception.
4725         *
4726         * @param dst - destination instrument at which this instrument will be
4727         *              moved to, or pass NULL for moving to end of list
4728         * @throw gig::Exception if this instrument and target instrument are not
4729         *                       part of the same file
4730         */
4731        void Instrument::MoveTo(Instrument* dst) {
4732            if (dst && GetParent() != dst->GetParent())
4733                throw Exception(
4734                    "gig::Instrument::MoveTo() can only be used for moving within "
4735                    "the same gig file."
4736                );
4737    
4738            File* pFile = (File*) GetParent();
4739    
4740            // move this instrument within the instrument list
4741            {
4742                File::InstrumentList& list = *pFile->pInstruments;
4743    
4744                File::InstrumentList::iterator itFrom =
4745                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4746    
4747                File::InstrumentList::iterator itTo =
4748                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4749    
4750                list.splice(itTo, list, itFrom);
4751            }
4752    
4753            // move the instrument's actual list RIFF chunk appropriately
4754            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4755            lstCkInstruments->MoveSubChunk(
4756                this->pCkInstrument,
4757                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4758            );
4759        }
4760    
4761        /**
4762         * Returns a MIDI rule of the instrument.
4763         *
4764         * The list of MIDI rules, at least in gig v3, always contains at
4765         * most two rules. The second rule can only be the DEF filter
4766         * (which currently isn't supported by libgig).
4767         *
4768         * @param i - MIDI rule number
4769         * @returns   pointer address to MIDI rule number i or NULL if there is none
4770         */
4771        MidiRule* Instrument::GetMidiRule(int i) {
4772            return pMidiRules[i];
4773        }
4774    
4775        /**
4776         * Adds the "controller trigger" MIDI rule to the instrument.
4777         *
4778         * @returns the new MIDI rule
4779         */
4780        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4781            delete pMidiRules[0];
4782            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4783            pMidiRules[0] = r;
4784            pMidiRules[1] = 0;
4785            return r;
4786        }
4787    
4788        /**
4789         * Adds the legato MIDI rule to the instrument.
4790         *
4791         * @returns the new MIDI rule
4792         */
4793        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4794            delete pMidiRules[0];
4795            MidiRuleLegato* r = new MidiRuleLegato;
4796            pMidiRules[0] = r;
4797            pMidiRules[1] = 0;
4798            return r;
4799        }
4800    
4801        /**
4802         * Adds the alternator MIDI rule to the instrument.
4803         *
4804         * @returns the new MIDI rule
4805         */
4806        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4807            delete pMidiRules[0];
4808            MidiRuleAlternator* r = new MidiRuleAlternator;
4809            pMidiRules[0] = r;
4810            pMidiRules[1] = 0;
4811            return r;
4812        }
4813    
4814        /**
4815         * Deletes a MIDI rule from the instrument.
4816         *
4817         * @param i - MIDI rule number
4818         */
4819        void Instrument::DeleteMidiRule(int i) {
4820            delete pMidiRules[i];
4821            pMidiRules[i] = 0;
4822        }
4823    
4824        void Instrument::LoadScripts() {
4825            if (pScriptRefs) return;
4826            pScriptRefs = new std::vector<_ScriptPooolRef>;
4827            if (scriptPoolFileOffsets.empty()) return;
4828            File* pFile = (File*) GetParent();
4829            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4830                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4831                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4832                    ScriptGroup* group = pFile->GetScriptGroup(i);
4833                    for (uint s = 0; group->GetScript(s); ++s) {
4834                        Script* script = group->GetScript(s);
4835                        if (script->pChunk) {
4836                            uint32_t offset = script->pChunk->GetFilePos() -
4837                                              script->pChunk->GetPos() -
4838                                              CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize());
4839                            if (offset == soughtOffset)
4840                            {
4841                                _ScriptPooolRef ref;
4842                                ref.script = script;
4843                                ref.bypass = scriptPoolFileOffsets[k].bypass;
4844                                pScriptRefs->push_back(ref);
4845                                break;
4846                            }
4847                        }
4848                    }
4849                }
4850            }
4851            // we don't need that anymore
4852            scriptPoolFileOffsets.clear();
4853        }
4854    
4855        /** @brief Get instrument script (gig format extension).
4856         *
4857         * Returns the real-time instrument script of instrument script slot
4858         * @a index.
4859         *
4860         * @note This is an own format extension which did not exist i.e. in the
4861         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4862         * gigedit.
4863         *
4864         * @param index - instrument script slot index
4865         * @returns script or NULL if index is out of bounds
4866         */
4867        Script* Instrument::GetScriptOfSlot(uint index) {
4868            LoadScripts();
4869            if (index >= pScriptRefs->size()) return NULL;
4870            return pScriptRefs->at(index).script;
4871        }
4872    
4873        /** @brief Add new instrument script slot (gig format extension).
4874         *
4875         * Add the given real-time instrument script reference to this instrument,
4876         * which shall be executed by the sampler for for this instrument. The
4877         * script will be added to the end of the script list of this instrument.
4878         * The positions of the scripts in the Instrument's Script list are
4879         * relevant, because they define in which order they shall be executed by
4880         * the sampler. For this reason it is also legal to add the same script
4881         * twice to an instrument, for example you might have a script called
4882         * "MyFilter" which performs an event filter task, and you might have
4883         * another script called "MyNoteTrigger" which triggers new notes, then you
4884         * might for example have the following list of scripts on the instrument:
4885         *
4886         * 1. Script "MyFilter"
4887         * 2. Script "MyNoteTrigger"
4888         * 3. Script "MyFilter"
4889         *
4890         * Which would make sense, because the 2nd script launched new events, which
4891         * you might need to filter as well.
4892         *
4893         * There are two ways to disable / "bypass" scripts. You can either disable
4894         * a script locally for the respective script slot on an instrument (i.e. by
4895         * passing @c false to the 2nd argument of this method, or by calling
4896         * SetScriptBypassed()). Or you can disable a script globally for all slots
4897         * and all instruments by setting Script::Bypass.
4898         *
4899         * @note This is an own format extension which did not exist i.e. in the
4900         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4901         * gigedit.
4902         *
4903         * @param pScript - script that shall be executed for this instrument
4904         * @param bypass  - if enabled, the sampler shall skip executing this
4905         *                  script (in the respective list position)
4906         * @see SetScriptBypassed()
4907         */
4908        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4909            LoadScripts();
4910            _ScriptPooolRef ref = { pScript, bypass };
4911            pScriptRefs->push_back(ref);
4912        }
4913    
4914        /** @brief Flip two script slots with each other (gig format extension).
4915         *
4916         * Swaps the position of the two given scripts in the Instrument's Script
4917         * list. The positions of the scripts in the Instrument's Script list are
4918         * relevant, because they define in which order they shall be executed by
4919         * the sampler.
4920         *
4921         * @note This is an own format extension which did not exist i.e. in the
4922         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4923         * gigedit.
4924         *
4925         * @param index1 - index of the first script slot to swap
4926         * @param index2 - index of the second script slot to swap
4927         */
4928        void Instrument::SwapScriptSlots(uint index1, uint index2) {
4929            LoadScripts();
4930            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4931                return;
4932            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4933            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4934            (*pScriptRefs)[index2] = tmp;
4935        }
4936    
4937        /** @brief Remove script slot.
4938         *
4939         * Removes the script slot with the given slot index.
4940         *
4941         * @param index - index of script slot to remove
4942         */
4943        void Instrument::RemoveScriptSlot(uint index) {
4944            LoadScripts();
4945            if (index >= pScriptRefs->size()) return;
4946            pScriptRefs->erase( pScriptRefs->begin() + index );
4947        }
4948    
4949        /** @brief Remove reference to given Script (gig format extension).
4950         *
4951         * This will remove all script slots on the instrument which are referencing
4952         * the given script.
4953         *
4954         * @note This is an own format extension which did not exist i.e. in the
4955         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4956         * gigedit.
4957         *
4958         * @param pScript - script reference to remove from this instrument
4959         * @see RemoveScriptSlot()
4960         */
4961        void Instrument::RemoveScript(Script* pScript) {
4962            LoadScripts();
4963            for (int i = pScriptRefs->size() - 1; i >= 0; --i) {
4964                if ((*pScriptRefs)[i].script == pScript) {
4965                    pScriptRefs->erase( pScriptRefs->begin() + i );
4966                }
4967            }
4968        }
4969    
4970        /** @brief Instrument's amount of script slots.
4971         *
4972         * This method returns the amount of script slots this instrument currently
4973         * uses.
4974         *
4975         * A script slot is a reference of a real-time instrument script to be
4976         * executed by the sampler. The scripts will be executed by the sampler in
4977         * sequence of the slots. One (same) script may be referenced multiple
4978         * times in different slots.
4979         *
4980         * @note This is an own format extension which did not exist i.e. in the
4981         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4982         * gigedit.
4983         */
4984        uint Instrument::ScriptSlotCount() const {
4985            return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
4986        }
4987    
4988        /** @brief Whether script execution shall be skipped.
4989         *
4990         * Defines locally for the Script reference slot in the Instrument's Script
4991         * list, whether the script shall be skipped by the sampler regarding
4992         * execution.
4993         *
4994         * It is also possible to ignore exeuction of the script globally, for all
4995         * slots and for all instruments by setting Script::Bypass.
4996         *
4997         * @note This is an own format extension which did not exist i.e. in the
4998         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4999         * gigedit.
5000         *
5001         * @param index - index of the script slot on this instrument
5002         * @see Script::Bypass
5003         */
5004        bool Instrument::IsScriptSlotBypassed(uint index) {
5005            if (index >= ScriptSlotCount()) return false;
5006            return pScriptRefs ? pScriptRefs->at(index).bypass
5007                               : scriptPoolFileOffsets.at(index).bypass;
5008            
5009        }
5010    
5011        /** @brief Defines whether execution shall be skipped.
5012         *
5013         * You can call this method to define locally whether or whether not the
5014         * given script slot shall be executed by the sampler.
5015         *
5016         * @note This is an own format extension which did not exist i.e. in the
5017         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5018         * gigedit.
5019         *
5020         * @param index - script slot index on this instrument
5021         * @param bBypass - if true, the script slot will be skipped by the sampler
5022         * @see Script::Bypass
5023         */
5024        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
5025            if (index >= ScriptSlotCount()) return;
5026            if (pScriptRefs)
5027                pScriptRefs->at(index).bypass = bBypass;
5028            else
5029                scriptPoolFileOffsets.at(index).bypass = bBypass;
5030        }
5031    
5032        /**
5033         * Make a (semi) deep copy of the Instrument object given by @a orig
5034         * and assign it to this object.
5035         *
5036         * Note that all sample pointers referenced by @a orig are simply copied as
5037         * memory address. Thus the respective samples are shared, not duplicated!
5038         *
5039         * @param orig - original Instrument object to be copied from
5040         */
5041        void Instrument::CopyAssign(const Instrument* orig) {
5042            CopyAssign(orig, NULL);
5043        }
5044            
5045        /**
5046         * Make a (semi) deep copy of the Instrument object given by @a orig
5047         * and assign it to this object.
5048         *
5049         * @param orig - original Instrument object to be copied from
5050         * @param mSamples - crosslink map between the foreign file's samples and
5051         *                   this file's samples
5052         */
5053        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
5054            // handle base class
5055            // (without copying DLS region stuff)
5056            DLS::Instrument::CopyAssignCore(orig);
5057            
5058            // handle own member variables
5059            Attenuation = orig->Attenuation;
5060            EffectSend = orig->EffectSend;
5061            FineTune = orig->FineTune;
5062            PitchbendRange = orig->PitchbendRange;
5063            PianoReleaseMode = orig->PianoReleaseMode;
5064            DimensionKeyRange = orig->DimensionKeyRange;
5065            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5066            pScriptRefs = orig->pScriptRefs;
5067            
5068            // free old midi rules
5069            for (int i = 0 ; pMidiRules[i] ; i++) {
5070                delete pMidiRules[i];
5071            }
5072            //TODO: MIDI rule copying
5073            pMidiRules[0] = NULL;
5074            
5075            // delete all old regions
5076            while (Regions) DeleteRegion(GetFirstRegion());
5077            // create new regions and copy them from original
5078            {
5079                RegionList::const_iterator it = orig->pRegions->begin();
5080                for (int i = 0; i < orig->Regions; ++i, ++it) {
5081                    Region* dstRgn = AddRegion();
5082                    //NOTE: Region does semi-deep copy !
5083                    dstRgn->CopyAssign(
5084                        static_cast<gig::Region*>(*it),
5085                        mSamples
5086                    );
5087                }
5088            }
5089    
5090            UpdateRegionKeyTable();
5091        }
5092    
5093    
5094  // *************** Group ***************  // *************** Group ***************
# Line 2711  namespace { Line 5107  namespace {
5107      }      }
5108    
5109      Group::~Group() {      Group::~Group() {
5110            // remove the chunk associated with this group (if any)
5111            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
5112      }      }
5113    
5114      /** @brief Update chunks with current group settings.      /** @brief Update chunks with current group settings.
5115       *       *
5116       * Apply current Group field values to the respective. You have to call       * Apply current Group field values to the respective chunks. You have
5117       * File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
5118         *
5119         * Usually there is absolutely no need to call this method explicitly.
5120         * It will be called automatically when File::Save() was called.
5121         *
5122         * @param pProgress - callback function for progress notification
5123       */       */
5124      void Group::UpdateChunks() {      void Group::UpdateChunks(progress_t* pProgress) {
5125          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
5126          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5127          if (!_3gri) _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);          if (!_3gri) {
5128                _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
5129                pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5130            }
5131          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5132          if (!_3gnl) _3gnl = pFile->pRIFF->AddSubList(LIST_TYPE_3GNL);          if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5133    
5134            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
5135                // v3 has a fixed list of 128 strings, find a free one
5136                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
5137                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
5138                        pNameChunk = ck;
5139                        break;
5140                    }
5141                }
5142            }
5143    
5144          // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk          // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
5145          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
5146      }      }
# Line 2799  namespace { Line 5216  namespace {
5216  // *************** File ***************  // *************** File ***************
5217  // *  // *
5218    
5219        /// Reflects Gigasampler file format version 2.0 (1998-06-28).
5220        const DLS::version_t File::VERSION_2 = {
5221            0, 2, 19980628 & 0xffff, 19980628 >> 16
5222        };
5223    
5224        /// Reflects Gigasampler file format version 3.0 (2003-03-31).
5225        const DLS::version_t File::VERSION_3 = {
5226            0, 3, 20030331 & 0xffff, 20030331 >> 16
5227        };
5228    
5229        static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
5230            { CHUNK_ID_IARL, 256 },
5231            { CHUNK_ID_IART, 128 },
5232            { CHUNK_ID_ICMS, 128 },
5233            { CHUNK_ID_ICMT, 1024 },
5234            { CHUNK_ID_ICOP, 128 },
5235            { CHUNK_ID_ICRD, 128 },
5236            { CHUNK_ID_IENG, 128 },
5237            { CHUNK_ID_IGNR, 128 },
5238            { CHUNK_ID_IKEY, 128 },
5239            { CHUNK_ID_IMED, 128 },
5240            { CHUNK_ID_INAM, 128 },
5241            { CHUNK_ID_IPRD, 128 },
5242            { CHUNK_ID_ISBJ, 128 },
5243            { CHUNK_ID_ISFT, 128 },
5244            { CHUNK_ID_ISRC, 128 },
5245            { CHUNK_ID_ISRF, 128 },
5246            { CHUNK_ID_ITCH, 128 },
5247            { 0, 0 }
5248        };
5249    
5250      File::File() : DLS::File() {      File::File() : DLS::File() {
5251            bAutoLoad = true;
5252            *pVersion = VERSION_3;
5253          pGroups = NULL;          pGroups = NULL;
5254          pInfo->UseFixedLengthStrings = true;          pScriptGroups = NULL;
5255            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5256            pInfo->ArchivalLocation = String(256, ' ');
5257    
5258            // add some mandatory chunks to get the file chunks in right
5259            // order (INFO chunk will be moved to first position later)
5260            pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
5261            pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
5262            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
5263    
5264            GenerateDLSID();
5265      }      }
5266    
5267      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5268            bAutoLoad = true;
5269          pGroups = NULL;          pGroups = NULL;
5270          pInfo->UseFixedLengthStrings = true;          pScriptGroups = NULL;
5271            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5272      }      }
5273    
5274      File::~File() {      File::~File() {
# Line 2819  namespace { Line 5281  namespace {
5281              }              }
5282              delete pGroups;              delete pGroups;
5283          }          }
5284            if (pScriptGroups) {
5285                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5286                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5287                while (iter != end) {
5288                    delete *iter;
5289                    ++iter;
5290                }
5291                delete pScriptGroups;
5292            }
5293      }      }
5294    
5295      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 2833  namespace { Line 5304  namespace {
5304          SamplesIterator++;          SamplesIterator++;
5305          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5306      }      }
5307        
5308        /**
5309         * Returns Sample object of @a index.
5310         *
5311         * @returns sample object or NULL if index is out of bounds
5312         */
5313        Sample* File::GetSample(uint index) {
5314            if (!pSamples) LoadSamples();
5315            if (!pSamples) return NULL;
5316            DLS::File::SampleList::iterator it = pSamples->begin();
5317            for (int i = 0; i < index; ++i) {
5318                ++it;
5319                if (it == pSamples->end()) return NULL;
5320            }
5321            if (it == pSamples->end()) return NULL;
5322            return static_cast<gig::Sample*>( *it );
5323        }
5324    
5325      /** @brief Add a new sample.      /** @brief Add a new sample.
5326       *       *
# Line 2848  namespace { Line 5336  namespace {
5336         // create new Sample object and its respective 'wave' list chunk         // create new Sample object and its respective 'wave' list chunk
5337         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
5338         Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);         Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
5339    
5340           // add mandatory chunks to get the chunks in right order
5341           wave->AddSubChunk(CHUNK_ID_FMT, 16);
5342           wave->AddSubList(LIST_TYPE_INFO);
5343    
5344         pSamples->push_back(pSample);         pSamples->push_back(pSample);
5345         return pSample;         return pSample;
5346      }      }
5347    
5348      /** @brief Delete a sample.      /** @brief Delete a sample.
5349       *       *
5350       * This will delete the given Sample object from the gig file. You have       * This will delete the given Sample object from the gig file. Any
5351       * to call Save() to make this persistent to the file.       * references to this sample from Regions and DimensionRegions will be
5352         * removed. You have to call Save() to make this persistent to the file.
5353       *       *
5354       * @param pSample - sample to delete       * @param pSample - sample to delete
5355       * @throws gig::Exception if given sample could not be found       * @throws gig::Exception if given sample could not be found
# Line 2864  namespace { Line 5358  namespace {
5358          if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");          if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
5359          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
5360          if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");          if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
5361            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
5362          pSamples->erase(iter);          pSamples->erase(iter);
5363          delete pSample;          delete pSample;
5364    
5365            SampleList::iterator tmp = SamplesIterator;
5366            // remove all references to the sample
5367            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5368                 instrument = GetNextInstrument()) {
5369                for (Region* region = instrument->GetFirstRegion() ; region ;
5370                     region = instrument->GetNextRegion()) {
5371    
5372                    if (region->GetSample() == pSample) region->SetSample(NULL);
5373    
5374                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
5375                        gig::DimensionRegion *d = region->pDimensionRegions[i];
5376                        if (d->pSample == pSample) d->pSample = NULL;
5377                    }
5378                }
5379            }
5380            SamplesIterator = tmp; // restore iterator
5381      }      }
5382    
5383      void File::LoadSamples() {      void File::LoadSamples() {
# Line 2875  namespace { Line 5387  namespace {
5387      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
5388          // Groups must be loaded before samples, because samples will try          // Groups must be loaded before samples, because samples will try
5389          // to resolve the group they belong to          // to resolve the group they belong to
5390          LoadGroups();          if (!pGroups) LoadGroups();
5391    
5392          if (!pSamples) pSamples = new SampleList;          if (!pSamples) pSamples = new SampleList;
5393    
# Line 2886  namespace { Line 5398  namespace {
5398          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5399    
5400          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5401            // (only for old gig files < 2 GB)
5402          int lastFileNo = 0;          int lastFileNo = 0;
5403          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5404              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5405                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5406                }
5407          }          }
5408          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5409          int nameLen = name.length();          int nameLen = name.length();
# Line 2898  namespace { Line 5413  namespace {
5413          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5414              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5415              if (wvpl) {              if (wvpl) {
5416                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5417                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5418                  while (wave) {                  while (wave) {
5419                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 2906  namespace { Line 5421  namespace {
5421                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5422                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5423    
5424                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5425                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
5426    
5427                          iSampleIndex++;                          iSampleIndex++;
# Line 2956  namespace { Line 5471  namespace {
5471              progress_t subprogress;              progress_t subprogress;
5472              __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask              __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
5473              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
5474              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
5475                    GetFirstSample(&subprogress); // now force all samples to be loaded
5476              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
5477    
5478              // instrument loading subtask              // instrument loading subtask
# Line 2989  namespace { Line 5505  namespace {
5505         __ensureMandatoryChunksExist();         __ensureMandatoryChunksExist();
5506         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5507         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
5508    
5509           // add mandatory chunks to get the chunks in right order
5510           lstInstr->AddSubList(LIST_TYPE_INFO);
5511           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
5512    
5513         Instrument* pInstrument = new Instrument(this, lstInstr);         Instrument* pInstrument = new Instrument(this, lstInstr);
5514           pInstrument->GenerateDLSID();
5515    
5516           lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
5517    
5518           // this string is needed for the gig to be loadable in GSt:
5519           pInstrument->pInfo->Software = "Endless Wave";
5520    
5521         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
5522         return pInstrument;         return pInstrument;
5523      }      }
5524        
5525        /** @brief Add a duplicate of an existing instrument.
5526         *
5527         * Duplicates the instrument definition given by @a orig and adds it
5528         * to this file. This allows in an instrument editor application to
5529         * easily create variations of an instrument, which will be stored in
5530         * the same .gig file, sharing i.e. the same samples.
5531         *
5532         * Note that all sample pointers referenced by @a orig are simply copied as
5533         * memory address. Thus the respective samples are shared, not duplicated!
5534         *
5535         * You have to call Save() to make this persistent to the file.
5536         *
5537         * @param orig - original instrument to be copied
5538         * @returns duplicated copy of the given instrument
5539         */
5540        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
5541            Instrument* instr = AddInstrument();
5542            instr->CopyAssign(orig);
5543            return instr;
5544        }
5545        
5546        /** @brief Add content of another existing file.
5547         *
5548         * Duplicates the samples, groups and instruments of the original file
5549         * given by @a pFile and adds them to @c this File. In case @c this File is
5550         * a new one that you haven't saved before, then you have to call
5551         * SetFileName() before calling AddContentOf(), because this method will
5552         * automatically save this file during operation, which is required for
5553         * writing the sample waveform data by disk streaming.
5554         *
5555         * @param pFile - original file whose's content shall be copied from
5556         */
5557        void File::AddContentOf(File* pFile) {
5558            static int iCallCount = -1;
5559            iCallCount++;
5560            std::map<Group*,Group*> mGroups;
5561            std::map<Sample*,Sample*> mSamples;
5562            
5563            // clone sample groups
5564            for (int i = 0; pFile->GetGroup(i); ++i) {
5565                Group* g = AddGroup();
5566                g->Name =
5567                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5568                mGroups[pFile->GetGroup(i)] = g;
5569            }
5570            
5571            // clone samples (not waveform data here yet)
5572            for (int i = 0; pFile->GetSample(i); ++i) {
5573                Sample* s = AddSample();
5574                s->CopyAssignMeta(pFile->GetSample(i));
5575                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5576                mSamples[pFile->GetSample(i)] = s;
5577            }
5578            
5579            //BUG: For some reason this method only works with this additional
5580            //     Save() call in between here.
5581            //
5582            // Important: The correct one of the 2 Save() methods has to be called
5583            // here, depending on whether the file is completely new or has been
5584            // saved to disk already, otherwise it will result in data corruption.
5585            if (pRIFF->IsNew())
5586                Save(GetFileName());
5587            else
5588                Save();
5589            
5590            // clone instruments
5591            // (passing the crosslink table here for the cloned samples)
5592            for (int i = 0; pFile->GetInstrument(i); ++i) {
5593                Instrument* instr = AddInstrument();
5594                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5595            }
5596            
5597            // Mandatory: file needs to be saved to disk at this point, so this
5598            // file has the correct size and data layout for writing the samples'
5599            // waveform data to disk.
5600            Save();
5601            
5602            // clone samples' waveform data
5603            // (using direct read & write disk streaming)
5604            for (int i = 0; pFile->GetSample(i); ++i) {
5605                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5606            }
5607        }
5608    
5609      /** @brief Delete an instrument.      /** @brief Delete an instrument.
5610       *       *
# Line 3000  namespace { Line 5612  namespace {
5612       * have to call Save() to make this persistent to the file.       * have to call Save() to make this persistent to the file.
5613       *       *
5614       * @param pInstrument - instrument to delete       * @param pInstrument - instrument to delete
5615       * @throws gig::Excption if given instrument could not be found       * @throws gig::Exception if given instrument could not be found
5616       */       */
5617      void File::DeleteInstrument(Instrument* pInstrument) {      void File::DeleteInstrument(Instrument* pInstrument) {
5618          if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");          if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
# Line 3040  namespace { Line 5652  namespace {
5652          }          }
5653      }      }
5654    
5655        /// Updates the 3crc chunk with the checksum of a sample. The
5656        /// update is done directly to disk, as this method is called
5657        /// after File::Save()
5658        void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
5659            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5660            if (!_3crc) return;
5661    
5662            // get the index of the sample
5663            int iWaveIndex = GetWaveTableIndexOf(pSample);
5664            if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
5665    
5666            // write the CRC-32 checksum to disk
5667            _3crc->SetPos(iWaveIndex * 8);
5668            uint32_t one = 1;
5669            _3crc->WriteUint32(&one); // always 1
5670            _3crc->WriteUint32(&crc);
5671    
5672            // reload CRC table to RAM to keep it persistent over several subsequent save operations
5673            _3crc->ReleaseChunkData();
5674            _3crc->LoadChunkData();
5675        }
5676    
5677        uint32_t File::GetSampleChecksum(Sample* pSample) {
5678            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5679            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5680            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5681            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5682    
5683            // get the index of the sample
5684            int iWaveIndex = GetWaveTableIndexOf(pSample);
5685            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5686    
5687            // read the CRC-32 checksum directly from disk
5688            size_t pos = iWaveIndex * 8;
5689            if (pos + 8 > _3crc->GetNewSize())
5690                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5691    
5692            uint32_t one = load32(&pData[pos]); // always 1
5693            if (one != 1)
5694                throw gig::Exception("Could not verify sample, because reference checksum table is damaged");
5695    
5696            return load32(&pData[pos+4]);
5697        }
5698        
5699        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5700            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5701            File::SampleList::iterator iter = pSamples->begin();
5702            File::SampleList::iterator end  = pSamples->end();
5703            for (int index = 0; iter != end; ++iter, ++index)
5704                if (*iter == pSample)
5705                    return index;
5706            return -1;
5707        }
5708    
5709        /**
5710         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5711         * the CRC32 check sums of all samples' raw wave data.
5712         *
5713         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5714         */
5715        bool File::VerifySampleChecksumTable() {
5716            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5717            if (!_3crc) return false;
5718            if (_3crc->GetNewSize() <= 0) return false;
5719            if (_3crc->GetNewSize() % 8) return false;
5720            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5721            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5722    
5723            const int n = _3crc->GetNewSize() / 8;
5724    
5725            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5726            if (!pData) return false;
5727    
5728            for (int i = 0; i < n; ++i) {
5729                uint32_t one = pData[i*2];
5730                if (one != 1) return false;
5731            }
5732    
5733            return true;
5734        }
5735    
5736        /**
5737         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5738         * file's checksum table with those new checksums. This might usually
5739         * just be necessary if the checksum table was damaged.
5740         *
5741         * @e IMPORTANT: The current implementation of this method only works
5742         * with files that have not been modified since it was loaded, because
5743         * it expects that no externally caused file structure changes are
5744         * required!
5745         *
5746         * Due to the expectation above, this method is currently protected
5747         * and actually only used by the command line tool "gigdump" yet.
5748         *
5749         * @returns true if Save() is required to be called after this call,
5750         *          false if no further action is required
5751         */
5752        bool File::RebuildSampleChecksumTable() {
5753            // make sure sample chunks were scanned
5754            if (!pSamples) GetFirstSample();
5755    
5756            bool bRequiresSave = false;
5757    
5758            // make sure "3CRC" chunk exists with required size
5759            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5760            if (!_3crc) {
5761                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5762                bRequiresSave = true;
5763            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5764                _3crc->Resize(pSamples->size() * 8);
5765                bRequiresSave = true;
5766            }
5767    
5768            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5769                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5770                {
5771                    File::SampleList::iterator iter = pSamples->begin();
5772                    File::SampleList::iterator end  = pSamples->end();
5773                    for (; iter != end; ++iter) {
5774                        gig::Sample* pSample = (gig::Sample*) *iter;
5775                        int index = GetWaveTableIndexOf(pSample);
5776                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5777                        pData[index*2]   = 1; // always 1
5778                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5779                    }
5780                }
5781            } else { // no file structure changes necessary, so directly write to disk and we are done ...
5782                // make sure file is in write mode
5783                pRIFF->SetMode(RIFF::stream_mode_read_write);
5784                {
5785                    File::SampleList::iterator iter = pSamples->begin();
5786                    File::SampleList::iterator end  = pSamples->end();
5787                    for (; iter != end; ++iter) {
5788                        gig::Sample* pSample = (gig::Sample*) *iter;
5789                        int index = GetWaveTableIndexOf(pSample);
5790                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5791                        uint32_t crc = pSample->CalculateWaveDataChecksum();
5792                        SetSampleChecksum(pSample, crc);
5793                    }
5794                }
5795            }
5796    
5797            return bRequiresSave;
5798        }
5799    
5800      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
5801          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5802          // there must always be at least one group          // there must always be at least one group
# Line 3069  namespace { Line 5826  namespace {
5826          return NULL;          return NULL;
5827      }      }
5828    
5829        /**
5830         * Returns the group with the given group name.
5831         *
5832         * Note: group names don't have to be unique in the gig format! So there
5833         * can be multiple groups with the same name. This method will simply
5834         * return the first group found with the given name.
5835         *
5836         * @param name - name of the sought group
5837         * @returns sought group or NULL if there's no group with that name
5838         */
5839        Group* File::GetGroup(String name) {
5840            if (!pGroups) LoadGroups();
5841            GroupsIterator = pGroups->begin();
5842            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
5843                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
5844            return NULL;
5845        }
5846    
5847      Group* File::AddGroup() {      Group* File::AddGroup() {
5848          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5849          // there must always be at least one group          // there must always be at least one group
# Line 3078  namespace { Line 5853  namespace {
5853          return pGroup;          return pGroup;
5854      }      }
5855    
5856        /** @brief Delete a group and its samples.
5857         *
5858         * This will delete the given Group object and all the samples that
5859         * belong to this group from the gig file. You have to call Save() to
5860         * make this persistent to the file.
5861         *
5862         * @param pGroup - group to delete
5863         * @throws gig::Exception if given group could not be found
5864         */
5865      void File::DeleteGroup(Group* pGroup) {      void File::DeleteGroup(Group* pGroup) {
5866          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5867          std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);          std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5868          if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");          if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5869          if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");          if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5870            // delete all members of this group
5871            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
5872                DeleteSample(pSample);
5873            }
5874            // now delete this group object
5875            pGroups->erase(iter);
5876            delete pGroup;
5877        }
5878    
5879        /** @brief Delete a group.
5880         *
5881         * This will delete the given Group object from the gig file. All the
5882         * samples that belong to this group will not be deleted, but instead
5883         * be moved to another group. You have to call Save() to make this
5884         * persistent to the file.
5885         *
5886         * @param pGroup - group to delete
5887         * @throws gig::Exception if given group could not be found
5888         */
5889        void File::DeleteGroupOnly(Group* pGroup) {
5890            if (!pGroups) LoadGroups();
5891            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5892            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5893            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5894          // move all members of this group to another group          // move all members of this group to another group
5895          pGroup->MoveAll();          pGroup->MoveAll();
5896          pGroups->erase(iter);          pGroups->erase(iter);
# Line 3099  namespace { Line 5907  namespace {
5907                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
5908                  while (ck) {                  while (ck) {
5909                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {
5910                            if (pVersion && pVersion->major == 3 &&
5911                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
5912    
5913                          pGroups->push_back(new Group(this, ck));                          pGroups->push_back(new Group(this, ck));
5914                      }                      }
5915                      ck = lst3gnl->GetNextSubChunk();                      ck = lst3gnl->GetNextSubChunk();
# Line 3113  namespace { Line 5924  namespace {
5924          }          }
5925      }      }
5926    
5927        /** @brief Get instrument script group (by index).
5928         *
5929         * Returns the real-time instrument script group with the given index.
5930         *
5931         * @param index - number of the sought group (0..n)
5932         * @returns sought script group or NULL if there's no such group
5933         */
5934        ScriptGroup* File::GetScriptGroup(uint index) {
5935            if (!pScriptGroups) LoadScriptGroups();
5936            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5937            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5938                if (i == index) return *it;
5939            return NULL;
5940        }
5941    
5942        /** @brief Get instrument script group (by name).
5943         *
5944         * Returns the first real-time instrument script group found with the given
5945         * group name. Note that group names may not necessarily be unique.
5946         *
5947         * @param name - name of the sought script group
5948         * @returns sought script group or NULL if there's no such group
5949         */
5950        ScriptGroup* File::GetScriptGroup(const String& name) {
5951            if (!pScriptGroups) LoadScriptGroups();
5952            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5953            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5954                if ((*it)->Name == name) return *it;
5955            return NULL;
5956        }
5957    
5958        /** @brief Add new instrument script group.
5959         *
5960         * Adds a new, empty real-time instrument script group to the file.
5961         *
5962         * You have to call Save() to make this persistent to the file.
5963         *
5964         * @return new empty script group
5965         */
5966        ScriptGroup* File::AddScriptGroup() {
5967            if (!pScriptGroups) LoadScriptGroups();
5968            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
5969            pScriptGroups->push_back(pScriptGroup);
5970            return pScriptGroup;
5971        }
5972    
5973        /** @brief Delete an instrument script group.
5974         *
5975         * This will delete the given real-time instrument script group and all its
5976         * instrument scripts it contains. References inside instruments that are
5977         * using the deleted scripts will be removed from the respective instruments
5978         * accordingly.
5979         *
5980         * You have to call Save() to make this persistent to the file.
5981         *
5982         * @param pScriptGroup - script group to delete
5983         * @throws gig::Exception if given script group could not be found
5984         */
5985        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
5986            if (!pScriptGroups) LoadScriptGroups();
5987            std::list<ScriptGroup*>::iterator iter =
5988                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
5989            if (iter == pScriptGroups->end())
5990                throw gig::Exception("Could not delete script group, could not find given script group");
5991            pScriptGroups->erase(iter);
5992            for (int i = 0; pScriptGroup->GetScript(i); ++i)
5993                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
5994            if (pScriptGroup->pList)
5995                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
5996            delete pScriptGroup;
5997        }
5998    
5999        void File::LoadScriptGroups() {
6000            if (pScriptGroups) return;
6001            pScriptGroups = new std::list<ScriptGroup*>;
6002            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
6003            if (lstLS) {
6004                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
6005                     lst = lstLS->GetNextSubList())
6006                {
6007                    if (lst->GetListType() == LIST_TYPE_RTIS) {
6008                        pScriptGroups->push_back(new ScriptGroup(this, lst));
6009                    }
6010                }
6011            }
6012        }
6013    
6014        /**
6015         * Apply all the gig file's current instruments, samples, groups and settings
6016         * to the respective RIFF chunks. You have to call Save() to make changes
6017         * persistent.
6018         *
6019         * Usually there is absolutely no need to call this method explicitly.
6020         * It will be called automatically when File::Save() was called.
6021         *
6022         * @param pProgress - callback function for progress notification
6023         * @throws Exception - on errors
6024         */
6025        void File::UpdateChunks(progress_t* pProgress) {
6026            bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6027    
6028            // update own gig format extension chunks
6029            // (not part of the GigaStudio 4 format)
6030            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6031            if (!lst3LS) {
6032                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6033            }
6034            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6035            // location of <3LS > is irrelevant, however it should be located
6036            // before  the actual wave data
6037            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6038            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6039    
6040            // This must be performed before writing the chunks for instruments,
6041            // because the instruments' script slots will write the file offsets
6042            // of the respective instrument script chunk as reference.
6043            if (pScriptGroups) {
6044                // Update instrument script (group) chunks.
6045                for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6046                     it != pScriptGroups->end(); ++it)
6047                {
6048                    (*it)->UpdateChunks(pProgress);
6049                }
6050            }
6051    
6052            // in case no libgig custom format data was added, then remove the
6053            // custom "3LS " chunk again
6054            if (!lst3LS->CountSubChunks()) {
6055                pRIFF->DeleteSubChunk(lst3LS);
6056                lst3LS = NULL;
6057            }
6058    
6059            // if there is a 3CRC chunk, make sure it is loaded into RAM, otherwise
6060            // its data might get lost or damaged on file structure changes
6061            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6062            if (_3crc) _3crc->LoadChunkData();
6063    
6064            // first update base class's chunks
6065            DLS::File::UpdateChunks(pProgress);
6066    
6067            if (newFile) {
6068                // INFO was added by Resource::UpdateChunks - make sure it
6069                // is placed first in file
6070                RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
6071                RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
6072                if (first != info) {
6073                    pRIFF->MoveSubChunk(info, first);
6074                }
6075            }
6076    
6077            // update group's chunks
6078            if (pGroups) {
6079                // make sure '3gri' and '3gnl' list chunks exist
6080                // (before updating the Group chunks)
6081                RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
6082                if (!_3gri) {
6083                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
6084                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
6085                }
6086                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
6087                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
6088    
6089                // v3: make sure the file has 128 3gnm chunks
6090                // (before updating the Group chunks)
6091                if (pVersion && pVersion->major == 3) {
6092                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
6093                    for (int i = 0 ; i < 128 ; i++) {
6094                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
6095                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
6096                    }
6097                }
6098    
6099                std::list<Group*>::iterator iter = pGroups->begin();
6100                std::list<Group*>::iterator end  = pGroups->end();
6101                for (; iter != end; ++iter) {
6102                    (*iter)->UpdateChunks(pProgress);
6103                }
6104            }
6105    
6106            // update einf chunk
6107    
6108            // The einf chunk contains statistics about the gig file, such
6109            // as the number of regions and samples used by each
6110            // instrument. It is divided in equally sized parts, where the
6111            // first part contains information about the whole gig file,
6112            // and the rest of the parts map to each instrument in the
6113            // file.
6114            //
6115            // At the end of each part there is a bit map of each sample
6116            // in the file, where a set bit means that the sample is used
6117            // by the file/instrument.
6118            //
6119            // Note that there are several fields with unknown use. These
6120            // are set to zero.
6121    
6122            int sublen = pSamples->size() / 8 + 49;
6123            int einfSize = (Instruments + 1) * sublen;
6124    
6125            RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
6126            if (einf) {
6127                if (einf->GetSize() != einfSize) {
6128                    einf->Resize(einfSize);
6129                    memset(einf->LoadChunkData(), 0, einfSize);
6130                }
6131            } else if (newFile) {
6132                einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
6133            }
6134            if (einf) {
6135                uint8_t* pData = (uint8_t*) einf->LoadChunkData();
6136    
6137                std::map<gig::Sample*,int> sampleMap;
6138                int sampleIdx = 0;
6139                for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
6140                    sampleMap[pSample] = sampleIdx++;
6141                }
6142    
6143                int totnbusedsamples = 0;
6144                int totnbusedchannels = 0;
6145                int totnbregions = 0;
6146                int totnbdimregions = 0;
6147                int totnbloops = 0;
6148                int instrumentIdx = 0;
6149    
6150                memset(&pData[48], 0, sublen - 48);
6151    
6152                for (Instrument* instrument = GetFirstInstrument() ; instrument ;
6153                     instrument = GetNextInstrument()) {
6154                    int nbusedsamples = 0;
6155                    int nbusedchannels = 0;
6156                    int nbdimregions = 0;
6157                    int nbloops = 0;
6158    
6159                    memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
6160    
6161                    for (Region* region = instrument->GetFirstRegion() ; region ;
6162                         region = instrument->GetNextRegion()) {
6163                        for (int i = 0 ; i < region->DimensionRegions ; i++) {
6164                            gig::DimensionRegion *d = region->pDimensionRegions[i];
6165                            if (d->pSample) {
6166                                int sampleIdx = sampleMap[d->pSample];
6167                                int byte = 48 + sampleIdx / 8;
6168                                int bit = 1 << (sampleIdx & 7);
6169                                if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
6170                                    pData[(instrumentIdx + 1) * sublen + byte] |= bit;
6171                                    nbusedsamples++;
6172                                    nbusedchannels += d->pSample->Channels;
6173    
6174                                    if ((pData[byte] & bit) == 0) {
6175                                        pData[byte] |= bit;
6176                                        totnbusedsamples++;
6177                                        totnbusedchannels += d->pSample->Channels;
6178                                    }
6179                                }
6180                            }
6181                            if (d->SampleLoops) nbloops++;
6182                        }
6183                        nbdimregions += region->DimensionRegions;
6184                    }
6185                    // first 4 bytes unknown - sometimes 0, sometimes length of einf part
6186                    // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
6187                    store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
6188                    store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
6189                    store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
6190                    store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
6191                    store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
6192                    store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6193                    // next 8 bytes unknown
6194                    store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6195                    store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
6196                    // next 4 bytes unknown
6197    
6198                    totnbregions += instrument->Regions;
6199                    totnbdimregions += nbdimregions;
6200                    totnbloops += nbloops;
6201                    instrumentIdx++;
6202                }
6203                // first 4 bytes unknown - sometimes 0, sometimes length of einf part
6204                // store32(&pData[0], sublen);
6205                store32(&pData[4], totnbusedchannels);
6206                store32(&pData[8], totnbusedsamples);
6207                store32(&pData[12], Instruments);
6208                store32(&pData[16], totnbregions);
6209                store32(&pData[20], totnbdimregions);
6210                store32(&pData[24], totnbloops);
6211                // next 8 bytes unknown
6212                // next 4 bytes unknown, not always 0
6213                store32(&pData[40], pSamples->size());
6214                // next 4 bytes unknown
6215            }
6216    
6217            // update 3crc chunk
6218    
6219            // The 3crc chunk contains CRC-32 checksums for the
6220            // samples. The actual checksum values will be filled in
6221            // later, by Sample::Write.
6222    
6223            if (_3crc) {
6224                _3crc->Resize(pSamples->size() * 8);
6225            } else if (newFile) {
6226                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
6227                _3crc->LoadChunkData();
6228    
6229                // the order of einf and 3crc is not the same in v2 and v3
6230                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6231            }
6232        }
6233        
6234        void File::UpdateFileOffsets() {
6235            DLS::File::UpdateFileOffsets();
6236    
6237            for (Instrument* instrument = GetFirstInstrument(); instrument;
6238                 instrument = GetNextInstrument())
6239            {
6240                instrument->UpdateScriptFileOffsets();
6241            }
6242        }
6243    
6244        /**
6245         * Enable / disable automatic loading. By default this properyt is
6246         * enabled and all informations are loaded automatically. However
6247         * loading all Regions, DimensionRegions and especially samples might
6248         * take a long time for large .gig files, and sometimes one might only
6249         * be interested in retrieving very superficial informations like the
6250         * amount of instruments and their names. In this case one might disable
6251         * automatic loading to avoid very slow response times.
6252         *
6253         * @e CAUTION: by disabling this property many pointers (i.e. sample
6254         * references) and informations will have invalid or even undefined
6255         * data! This feature is currently only intended for retrieving very
6256         * superficial informations in a very fast way. Don't use it to retrieve
6257         * details like synthesis informations or even to modify .gig files!
6258         */
6259        void File::SetAutoLoad(bool b) {
6260            bAutoLoad = b;
6261        }
6262    
6263        /**
6264         * Returns whether automatic loading is enabled.
6265         * @see SetAutoLoad()
6266         */
6267        bool File::GetAutoLoad() {
6268            return bAutoLoad;
6269        }
6270    
6271    
6272    
6273  // *************** Exception ***************  // *************** Exception ***************

Legend:
Removed from v.1050  
changed lines
  Added in v.2985

  ViewVC Help
Powered by ViewVC