/[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 1070 by persson, Mon Mar 5 17:42:35 2007 UTC revision 2989 by schoenebeck, Sat Sep 24 14:00:46 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 277  namespace { Line 338  namespace {
338       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
339       * @param fileNo         - number of an extension file where this sample       * @param fileNo         - number of an extension file where this sample
340       *                         is located, 0 otherwise       *                         is located, 0 otherwise
341         * @param index          - wave pool index of sample (may be -1 on new sample)
342       */       */
343      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset, unsigned long fileNo, int index)
344          pInfo->UseFixedLengthStrings = true;          : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset)
345        {
346            static const DLS::Info::string_length_t fixedStringLengths[] = {
347                { CHUNK_ID_INAM, 64 },
348                { 0, 0 }
349            };
350            pInfo->SetFixedStringLengths(fixedStringLengths);
351          Instances++;          Instances++;
352          FileNo = fileNo;          FileNo = fileNo;
353    
354            __resetCRC(crc);
355            // if this is not a new sample, try to get the sample's already existing
356            // CRC32 checksum from disk, this checksum will reflect the sample's CRC32
357            // checksum of the time when the sample was consciously modified by the
358            // user for the last time (by calling Sample::Write() that is).
359            if (index >= 0) { // not a new file ...
360                try {
361                    uint32_t crc = pFile->GetSampleChecksumByIndex(index);
362                    this->crc = crc;
363                } catch (...) {}
364            }
365    
366          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
367          if (pCk3gix) {          if (pCk3gix) {
368              uint16_t iSampleGroup = pCk3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
# Line 314  namespace { Line 394  namespace {
394              Manufacturer  = 0;              Manufacturer  = 0;
395              Product       = 0;              Product       = 0;
396              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
397              MIDIUnityNote = 64;              MIDIUnityNote = 60;
398              FineTune      = 0;              FineTune      = 0;
399                SMPTEFormat   = smpte_format_no_offset;
400              SMPTEOffset   = 0;              SMPTEOffset   = 0;
401              Loops         = 0;              Loops         = 0;
402              LoopID        = 0;              LoopID        = 0;
403                LoopType      = loop_type_normal;
404              LoopStart     = 0;              LoopStart     = 0;
405              LoopEnd       = 0;              LoopEnd       = 0;
406              LoopFraction  = 0;              LoopFraction  = 0;
# Line 358  namespace { Line 440  namespace {
440      }      }
441    
442      /**      /**
443         * Make a (semi) deep copy of the Sample object given by @a orig (without
444         * the actual waveform data) and assign it to this object.
445         *
446         * Discussion: copying .gig samples is a bit tricky. It requires three
447         * steps:
448         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
449         *    its new sample waveform data size.
450         * 2. Saving the file (done by File::Save()) so that it gains correct size
451         *    and layout for writing the actual wave form data directly to disc
452         *    in next step.
453         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
454         *
455         * @param orig - original Sample object to be copied from
456         */
457        void Sample::CopyAssignMeta(const Sample* orig) {
458            // handle base classes
459            DLS::Sample::CopyAssignCore(orig);
460            
461            // handle actual own attributes of this class
462            Manufacturer = orig->Manufacturer;
463            Product = orig->Product;
464            SamplePeriod = orig->SamplePeriod;
465            MIDIUnityNote = orig->MIDIUnityNote;
466            FineTune = orig->FineTune;
467            SMPTEFormat = orig->SMPTEFormat;
468            SMPTEOffset = orig->SMPTEOffset;
469            Loops = orig->Loops;
470            LoopID = orig->LoopID;
471            LoopType = orig->LoopType;
472            LoopStart = orig->LoopStart;
473            LoopEnd = orig->LoopEnd;
474            LoopSize = orig->LoopSize;
475            LoopFraction = orig->LoopFraction;
476            LoopPlayCount = orig->LoopPlayCount;
477            
478            // schedule resizing this sample to the given sample's size
479            Resize(orig->GetSize());
480        }
481    
482        /**
483         * Should be called after CopyAssignMeta() and File::Save() sequence.
484         * Read more about it in the discussion of CopyAssignMeta(). This method
485         * copies the actual waveform data by disk streaming.
486         *
487         * @e CAUTION: this method is currently not thread safe! During this
488         * operation the sample must not be used for other purposes by other
489         * threads!
490         *
491         * @param orig - original Sample object to be copied from
492         */
493        void Sample::CopyAssignWave(const Sample* orig) {
494            const int iReadAtOnce = 32*1024;
495            char* buf = new char[iReadAtOnce * orig->FrameSize];
496            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
497            file_offset_t restorePos = pOrig->GetPos();
498            pOrig->SetPos(0);
499            SetPos(0);
500            for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
501                               n = pOrig->Read(buf, iReadAtOnce))
502            {
503                Write(buf, n);
504            }
505            pOrig->SetPos(restorePos);
506            delete [] buf;
507        }
508    
509        /**
510       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
511       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
512       *       *
513       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
514       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
515       *       *
516         * @param pProgress - callback function for progress notification
517       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
518       *                        was provided yet       *                        was provided yet
519       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
520       */       */
521      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
522          // first update base class's chunks          // first update base class's chunks
523          DLS::Sample::UpdateChunks();          DLS::Sample::UpdateChunks(pProgress);
524    
525          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
526          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
527          if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);          if (!pCkSmpl) {
528                pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
529                memset(pCkSmpl->LoadChunkData(), 0, 60);
530            }
531          // update 'smpl' chunk          // update 'smpl' chunk
532          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
533          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
534          memcpy(&pData[0], &Manufacturer, 4);          store32(&pData[0], Manufacturer);
535          memcpy(&pData[4], &Product, 4);          store32(&pData[4], Product);
536          memcpy(&pData[8], &SamplePeriod, 4);          store32(&pData[8], SamplePeriod);
537          memcpy(&pData[12], &MIDIUnityNote, 4);          store32(&pData[12], MIDIUnityNote);
538          memcpy(&pData[16], &FineTune, 4);          store32(&pData[16], FineTune);
539          memcpy(&pData[20], &SMPTEFormat, 4);          store32(&pData[20], SMPTEFormat);
540          memcpy(&pData[24], &SMPTEOffset, 4);          store32(&pData[24], SMPTEOffset);
541          memcpy(&pData[28], &Loops, 4);          store32(&pData[28], Loops);
542    
543          // we skip 'manufByt' for now (4 bytes)          // we skip 'manufByt' for now (4 bytes)
544    
545          memcpy(&pData[36], &LoopID, 4);          store32(&pData[36], LoopID);
546          memcpy(&pData[40], &LoopType, 4);          store32(&pData[40], LoopType);
547          memcpy(&pData[44], &LoopStart, 4);          store32(&pData[44], LoopStart);
548          memcpy(&pData[48], &LoopEnd, 4);          store32(&pData[48], LoopEnd);
549          memcpy(&pData[52], &LoopFraction, 4);          store32(&pData[52], LoopFraction);
550          memcpy(&pData[56], &LoopPlayCount, 4);          store32(&pData[56], LoopPlayCount);
551    
552          // make sure '3gix' chunk exists          // make sure '3gix' chunk exists
553          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
# Line 414  namespace { Line 567  namespace {
567          }          }
568          // update '3gix' chunk          // update '3gix' chunk
569          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
570          memcpy(&pData[0], &iSampleGroup, 2);          store16(&pData[0], iSampleGroup);
571    
572            // if the library user toggled the "Compressed" attribute from true to
573            // false, then the EWAV chunk associated with compressed samples needs
574            // to be deleted
575            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
576            if (ewav && !Compressed) {
577                pWaveList->DeleteSubChunk(ewav);
578            }
579      }      }
580    
581      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
582      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
583          //TODO: we have to add some more scans here (e.g. determine compression rate)          //TODO: we have to add some more scans here (e.g. determine compression rate)
584          this->SamplesTotal = 0;          this->SamplesTotal = 0;
585          std::list<unsigned long> frameOffsets;          std::list<file_offset_t> frameOffsets;
586    
587          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
588          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
# Line 437  namespace { Line 598  namespace {
598                  const int mode_l = pCkData->ReadUint8();                  const int mode_l = pCkData->ReadUint8();
599                  const int mode_r = pCkData->ReadUint8();                  const int mode_r = pCkData->ReadUint8();
600                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
601                  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];                  const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
602    
603                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
604                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 456  namespace { Line 617  namespace {
617    
618                  const int mode = pCkData->ReadUint8();                  const int mode = pCkData->ReadUint8();
619                  if (mode > 5) throw gig::Exception("Unknown compression mode");                  if (mode > 5) throw gig::Exception("Unknown compression mode");
620                  const unsigned long frameSize = bytesPerFrame[mode];                  const file_offset_t frameSize = bytesPerFrame[mode];
621    
622                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
623                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 472  namespace { Line 633  namespace {
633    
634          // Build the frames table (which is used for fast resolving of a frame's chunk offset)          // Build the frames table (which is used for fast resolving of a frame's chunk offset)
635          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
636          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new file_offset_t[frameOffsets.size()];
637          std::list<unsigned long>::iterator end  = frameOffsets.end();          std::list<file_offset_t>::iterator end  = frameOffsets.end();
638          std::list<unsigned long>::iterator iter = frameOffsets.begin();          std::list<file_offset_t>::iterator iter = frameOffsets.begin();
639          for (int i = 0; iter != end; i++, iter++) {          for (int i = 0; iter != end; i++, iter++) {
640              FrameTable[i] = *iter;              FrameTable[i] = *iter;
641          }          }
# Line 515  namespace { Line 676  namespace {
676       *                      the cached sample data in bytes       *                      the cached sample data in bytes
677       * @see                 ReleaseSampleData(), Read(), SetPos()       * @see                 ReleaseSampleData(), Read(), SetPos()
678       */       */
679      buffer_t Sample::LoadSampleData(unsigned long SampleCount) {      buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
680          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
681      }      }
682    
# Line 574  namespace { Line 735  namespace {
735       *                           size of the cached sample data in bytes       *                           size of the cached sample data in bytes
736       * @see                      ReleaseSampleData(), Read(), SetPos()       * @see                      ReleaseSampleData(), Read(), SetPos()
737       */       */
738      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
739          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
740          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
741          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
742            SetPos(0); // reset read position to begin of sample
743          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
744          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
745          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 615  namespace { Line 777  namespace {
777          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
778          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
779          RAMCache.Size   = 0;          RAMCache.Size   = 0;
780            RAMCache.NullExtensionSize = 0;
781      }      }
782    
783      /** @brief Resize sample.      /** @brief Resize sample.
# Line 639  namespace { Line 802  namespace {
802       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
803       * other formats will fail!       * other formats will fail!
804       *       *
805       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
806       *                   greater than zero)       *                  greater than zero)
807       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
808       *                         or if \a iNewSize is less than 1       * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
809       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
810       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
811       *      DLS::Sample::FormatTag, File::Save()       *      DLS::Sample::FormatTag, File::Save()
812       */       */
813      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
814          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
815          DLS::Sample::Resize(iNewSize);          DLS::Sample::Resize(NewSize);
816      }      }
817    
818      /**      /**
# Line 673  namespace { Line 836  namespace {
836       * @returns            the new sample position       * @returns            the new sample position
837       * @see                Read()       * @see                Read()
838       */       */
839      unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {      file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) {
840          if (Compressed) {          if (Compressed) {
841              switch (Whence) {              switch (Whence) {
842                  case RIFF::stream_curpos:                  case RIFF::stream_curpos:
# Line 691  namespace { Line 854  namespace {
854              }              }
855              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
856    
857              unsigned long frame = this->SamplePos / 2048; // to which frame to jump              file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
858              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame
859              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame
860              return this->SamplePos;              return this->SamplePos;
861          }          }
862          else { // not compressed          else { // not compressed
863              unsigned long orderedBytes = SampleCount * this->FrameSize;              file_offset_t orderedBytes = SampleCount * this->FrameSize;
864              unsigned long result = pCkData->SetPos(orderedBytes, Whence);              file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
865              return (result == orderedBytes) ? SampleCount              return (result == orderedBytes) ? SampleCount
866                                              : result / this->FrameSize;                                              : result / this->FrameSize;
867          }          }
# Line 707  namespace { Line 870  namespace {
870      /**      /**
871       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
872       */       */
873      unsigned long Sample::GetPos() {      file_offset_t Sample::GetPos() const {
874          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
875          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
876      }      }
# Line 746  namespace { Line 909  namespace {
909       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
910       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
911       */       */
912      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,      file_offset_t Sample::ReadAndLoop(void* pBuffer, file_offset_t SampleCount, playback_state_t* pPlaybackState,
913                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
914          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
915          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
916    
917          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
# Line 786  namespace { Line 949  namespace {
949                                  // reading, swap all sample frames so it reflects                                  // reading, swap all sample frames so it reflects
950                                  // backward playback                                  // backward playback
951    
952                                  unsigned long swapareastart       = totalreadsamples;                                  file_offset_t swapareastart       = totalreadsamples;
953                                  unsigned long loopoffset          = GetPos() - loop.LoopStart;                                  file_offset_t loopoffset          = GetPos() - loop.LoopStart;
954                                  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                  file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
955                                  unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                  file_offset_t reverseplaybackend  = GetPos() - samplestoreadinloop;
956    
957                                  SetPos(reverseplaybackend);                                  SetPos(reverseplaybackend);
958    
# Line 809  namespace { Line 972  namespace {
972                                  }                                  }
973    
974                                  // reverse the sample frames for backward playback                                  // reverse the sample frames for backward playback
975                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                                  if (totalreadsamples > swapareastart) //FIXME: this if() is just a crash workaround for now (#102), but totalreadsamples <= swapareastart should never be the case, so there's probably still a bug above!
976                                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
977                              }                              }
978                          } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
979                          break;                          break;
# Line 836  namespace { Line 1000  namespace {
1000                          // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
1001                          // backward playback                          // backward playback
1002    
1003                          unsigned long swapareastart       = totalreadsamples;                          file_offset_t swapareastart       = totalreadsamples;
1004                          unsigned long loopoffset          = GetPos() - loop.LoopStart;                          file_offset_t loopoffset          = GetPos() - loop.LoopStart;
1005                          unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)                          file_offset_t samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
1006                                                                                    : samplestoread;                                                                                    : samplestoread;
1007                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);                          file_offset_t reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1008    
1009                          SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
1010    
# Line 920  namespace { Line 1084  namespace {
1084       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1085       * @see                SetPos(), CreateDecompressionBuffer()       * @see                SetPos(), CreateDecompressionBuffer()
1086       */       */
1087      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {      file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount, buffer_t* pExternalDecompressionBuffer) {
1088          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1089          if (!Compressed) {          if (!Compressed) {
1090              if (BitDepth == 24) {              if (BitDepth == 24) {
# Line 935  namespace { Line 1099  namespace {
1099          else {          else {
1100              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1101              //TODO: efficiency: maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1102              unsigned long assumedsize      = GuessSize(SampleCount),              file_offset_t assumedsize      = GuessSize(SampleCount),
1103                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1104                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1105                            copysamples, skipsamples,                            copysamples, skipsamples,
# Line 958  namespace { Line 1122  namespace {
1122              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1123    
1124              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
1125                  unsigned long framesamples = SamplesPerFrame;                  file_offset_t framesamples = SamplesPerFrame;
1126                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;                  file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1127    
1128                  int mode_l = *pSrc++, mode_r = 0;                  int mode_l = *pSrc++, mode_r = 0;
1129    
# Line 1099  namespace { Line 1263  namespace {
1263       *       *
1264       * Note: there is currently no support for writing compressed samples.       * Note: there is currently no support for writing compressed samples.
1265       *       *
1266         * For 16 bit samples, the data in the source buffer should be
1267         * int16_t (using native endianness). For 24 bit, the buffer
1268         * should contain three bytes per sample, little-endian.
1269         *
1270       * @param pBuffer     - source buffer       * @param pBuffer     - source buffer
1271       * @param SampleCount - number of sample points to write       * @param SampleCount - number of sample points to write
1272       * @throws DLS::Exception if current sample size is too small       * @throws DLS::Exception if current sample size is too small
1273       * @throws gig::Exception if sample is compressed       * @throws gig::Exception if sample is compressed
1274       * @see DLS::LoadSampleData()       * @see DLS::LoadSampleData()
1275       */       */
1276      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1277          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1278          return DLS::Sample::Write(pBuffer, SampleCount);  
1279            // if this is the first write in this sample, reset the
1280            // checksum calculator
1281            if (pCkData->GetPos() == 0) {
1282                __resetCRC(crc);
1283            }
1284            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1285            file_offset_t res;
1286            if (BitDepth == 24) {
1287                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1288            } else { // 16 bit
1289                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1290                                    : pCkData->Write(pBuffer, SampleCount, 2);
1291            }
1292            __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1293    
1294            // if this is the last write, update the checksum chunk in the
1295            // file
1296            if (pCkData->GetPos() == pCkData->GetSize()) {
1297                File* pFile = static_cast<File*>(GetParent());
1298                pFile->SetSampleChecksum(this, __encodeCRC(crc));
1299            }
1300            return res;
1301      }      }
1302    
1303      /**      /**
# Line 1126  namespace { Line 1316  namespace {
1316       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1317       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1318       */       */
1319      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1320          buffer_t result;          buffer_t result;
1321          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1322                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1323          result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);          result.Size              = (file_offset_t) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1324          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1325          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1326          return result;          return result;
# Line 1164  namespace { Line 1354  namespace {
1354          return pGroup;          return pGroup;
1355      }      }
1356    
1357        /**
1358         * Returns the CRC-32 checksum of the sample's raw wave form data at the
1359         * time when this sample's wave form data was modified for the last time
1360         * by calling Write(). This checksum only covers the raw wave form data,
1361         * not any meta informations like i.e. bit depth or loop points. Since
1362         * this method just returns the checksum stored for this sample i.e. when
1363         * the gig file was loaded, this method returns immediately. So it does no
1364         * recalcuation of the checksum with the currently available sample wave
1365         * form data.
1366         *
1367         * @see VerifyWaveData()
1368         */
1369        uint32_t Sample::GetWaveDataCRC32Checksum() {
1370            return crc;
1371        }
1372    
1373        /**
1374         * Checks the integrity of this sample's raw audio wave data. Whenever a
1375         * Sample's raw wave data is intentionally modified (i.e. by calling
1376         * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1377         * is calculated and stored/updated for this sample, along to the sample's
1378         * meta informations.
1379         *
1380         * Now by calling this method the current raw audio wave data is checked
1381         * against the already stored CRC32 check sum in order to check whether the
1382         * sample data had been damaged unintentionally for some reason. Since by
1383         * calling this method always the entire raw audio wave data has to be
1384         * read, verifying all samples this way may take a long time accordingly.
1385         * And that's also the reason why the sample integrity is not checked by
1386         * default whenever a gig file is loaded. So this method must be called
1387         * explicitly to fulfill this task.
1388         *
1389         * @param pActually - (optional) if provided, will be set to the actually
1390         *                    calculated checksum of the current raw wave form data,
1391         *                    you can get the expected checksum instead by calling
1392         *                    GetWaveDataCRC32Checksum()
1393         * @returns true if sample is OK or false if the sample is damaged
1394         * @throws Exception if no checksum had been stored to disk for this
1395         *         sample yet, or on I/O issues
1396         * @see GetWaveDataCRC32Checksum()
1397         */
1398        bool Sample::VerifyWaveData(uint32_t* pActually) {
1399            File* pFile = static_cast<File*>(GetParent());
1400            uint32_t crc = CalculateWaveDataChecksum();
1401            if (pActually) *pActually = crc;
1402            return crc == this->crc;
1403        }
1404    
1405        uint32_t Sample::CalculateWaveDataChecksum() {
1406            const size_t sz = 20*1024; // 20kB buffer size
1407            std::vector<uint8_t> buffer(sz);
1408            buffer.resize(sz);
1409    
1410            const size_t n = sz / FrameSize;
1411            SetPos(0);
1412            uint32_t crc = 0;
1413            __resetCRC(crc);
1414            while (true) {
1415                file_offset_t nRead = Read(&buffer[0], n);
1416                if (nRead <= 0) break;
1417                __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1418            }
1419            __encodeCRC(crc);
1420            return crc;
1421        }
1422    
1423      Sample::~Sample() {      Sample::~Sample() {
1424          Instances--;          Instances--;
1425          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1180  namespace { Line 1436  namespace {
1436  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1437  // *  // *
1438    
1439      uint                               DimensionRegion::Instances       = 0;      size_t                             DimensionRegion::Instances       = 0;
1440      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1441    
1442      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1443          Instances++;          Instances++;
1444    
1445          pSample = NULL;          pSample = NULL;
1446            pRegion = pParent;
1447    
1448            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1449            else memset(&Crossfade, 0, 4);
1450    
         memcpy(&Crossfade, &SamplerOptions, 4);  
1451          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1452    
1453          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
# Line 1302  namespace { Line 1561  namespace {
1561                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1562              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1563              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1564                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1565              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1566              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1567              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1352  namespace { Line 1611  namespace {
1611              LFO1ControlDepth                = 0;              LFO1ControlDepth                = 0;
1612              LFO3ControlDepth                = 0;              LFO3ControlDepth                = 0;
1613              EG1Attack                       = 0.0;              EG1Attack                       = 0.0;
1614              EG1Decay1                       = 0.0;              EG1Decay1                       = 0.005;
1615              EG1Sustain                      = 0;              EG1Sustain                      = 1000;
1616              EG1Release                      = 0.0;              EG1Release                      = 0.3;
1617              EG1Controller.type              = eg1_ctrl_t::type_none;              EG1Controller.type              = eg1_ctrl_t::type_none;
1618              EG1Controller.controller_number = 0;              EG1Controller.controller_number = 0;
1619              EG1ControllerInvert             = false;              EG1ControllerInvert             = false;
# Line 1369  namespace { Line 1628  namespace {
1628              EG2ControllerReleaseInfluence   = 0;              EG2ControllerReleaseInfluence   = 0;
1629              LFO1Frequency                   = 1.0;              LFO1Frequency                   = 1.0;
1630              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1631              EG2Decay1                       = 0.0;              EG2Decay1                       = 0.005;
1632              EG2Sustain                      = 0;              EG2Sustain                      = 1000;
1633              EG2Release                      = 0.0;              EG2Release                      = 0.3;
1634              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1635              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1636              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
1637              EG1Decay2                       = 0.0;              EG1Decay2                       = 0.0;
1638              EG1InfiniteSustain              = false;              EG1InfiniteSustain              = true;
1639              EG1PreAttack                    = 1000;              EG1PreAttack                    = 0;
1640              EG2Decay2                       = 0.0;              EG2Decay2                       = 0.0;
1641              EG2InfiniteSustain              = false;              EG2InfiniteSustain              = true;
1642              EG2PreAttack                    = 1000;              EG2PreAttack                    = 0;
1643              VelocityResponseCurve           = curve_type_nonlinear;              VelocityResponseCurve           = curve_type_nonlinear;
1644              VelocityResponseDepth           = 3;              VelocityResponseDepth           = 3;
1645              ReleaseVelocityResponseCurve    = curve_type_nonlinear;              ReleaseVelocityResponseCurve    = curve_type_nonlinear;
# Line 1423  namespace { Line 1682  namespace {
1682              VCFVelocityDynamicRange         = 0x04;              VCFVelocityDynamicRange         = 0x04;
1683              VCFVelocityCurve                = curve_type_linear;              VCFVelocityCurve                = curve_type_linear;
1684              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1685              memset(DimensionUpperLimits, 0, 8);              memset(DimensionUpperLimits, 127, 8);
1686          }          }
1687    
1688          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1689                                                       VelocityResponseDepth,                                                       VelocityResponseDepth,
1690                                                       VelocityResponseCurveScaling);                                                       VelocityResponseCurveScaling);
1691    
1692          curve_type_t curveType = ReleaseVelocityResponseCurve;          pVelocityReleaseTable = GetReleaseVelocityTable(
1693          uint8_t depth = ReleaseVelocityResponseDepth;                                      ReleaseVelocityResponseCurve,
1694                                        ReleaseVelocityResponseDepth
1695                                    );
1696    
1697            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1698                                                          VCFVelocityDynamicRange,
1699                                                          VCFVelocityScale,
1700                                                          VCFCutoffController);
1701    
1702          // this models a strange behaviour or bug in GSt: two of the          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1703          // velocity response curves for release time are not used even          VelocityTable = 0;
1704          // 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);  
1705    
1706          curveType = VCFVelocityCurve;      /*
1707          depth = VCFVelocityDynamicRange;       * Constructs a DimensionRegion by copying all parameters from
1708         * another DimensionRegion
1709         */
1710        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1711            Instances++;
1712            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1713            *this = src; // default memberwise shallow copy of all parameters
1714            pParentList = _3ewl; // restore the chunk pointer
1715    
1716            // deep copy of owned structures
1717            if (src.VelocityTable) {
1718                VelocityTable = new uint8_t[128];
1719                for (int k = 0 ; k < 128 ; k++)
1720                    VelocityTable[k] = src.VelocityTable[k];
1721            }
1722            if (src.pSampleLoops) {
1723                pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1724                for (int k = 0 ; k < src.SampleLoops ; k++)
1725                    pSampleLoops[k] = src.pSampleLoops[k];
1726            }
1727        }
1728        
1729        /**
1730         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1731         * and assign it to this object.
1732         *
1733         * Note that all sample pointers referenced by @a orig are simply copied as
1734         * memory address. Thus the respective samples are shared, not duplicated!
1735         *
1736         * @param orig - original DimensionRegion object to be copied from
1737         */
1738        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1739            CopyAssign(orig, NULL);
1740        }
1741    
1742          // even stranger GSt: two of the velocity response curves for      /**
1743          // filter cutoff are not used, instead another special curve       * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1744          // is chosen. This curve is not used anywhere else.       * and assign it to this object.
1745          if ((curveType == curve_type_nonlinear && depth == 0) ||       *
1746              (curveType == curve_type_special   && depth == 4)) {       * @param orig - original DimensionRegion object to be copied from
1747              curveType = curve_type_special;       * @param mSamples - crosslink map between the foreign file's samples and
1748              depth = 5;       *                   this file's samples
1749         */
1750        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1751            // delete all allocated data first
1752            if (VelocityTable) delete [] VelocityTable;
1753            if (pSampleLoops) delete [] pSampleLoops;
1754            
1755            // backup parent list pointer
1756            RIFF::List* p = pParentList;
1757            
1758            gig::Sample* pOriginalSample = pSample;
1759            gig::Region* pOriginalRegion = pRegion;
1760            
1761            //NOTE: copy code copied from assignment constructor above, see comment there as well
1762            
1763            *this = *orig; // default memberwise shallow copy of all parameters
1764            
1765            // restore members that shall not be altered
1766            pParentList = p; // restore the chunk pointer
1767            pRegion = pOriginalRegion;
1768            
1769            // only take the raw sample reference reference if the
1770            // two DimensionRegion objects are part of the same file
1771            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1772                pSample = pOriginalSample;
1773            }
1774            
1775            if (mSamples && mSamples->count(orig->pSample)) {
1776                pSample = mSamples->find(orig->pSample)->second;
1777            }
1778    
1779            // deep copy of owned structures
1780            if (orig->VelocityTable) {
1781                VelocityTable = new uint8_t[128];
1782                for (int k = 0 ; k < 128 ; k++)
1783                    VelocityTable[k] = orig->VelocityTable[k];
1784            }
1785            if (orig->pSampleLoops) {
1786                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1787                for (int k = 0 ; k < orig->SampleLoops ; k++)
1788                    pSampleLoops[k] = orig->pSampleLoops[k];
1789          }          }
1790          pVelocityCutoffTable = GetVelocityTable(curveType, depth,      }
                                                 VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);  
1791    
1792        /**
1793         * Updates the respective member variable and updates @c SampleAttenuation
1794         * which depends on this value.
1795         */
1796        void DimensionRegion::SetGain(int32_t gain) {
1797            DLS::Sampler::SetGain(gain);
1798          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
         VelocityTable = 0;  
1799      }      }
1800    
1801      /**      /**
# Line 1467  namespace { Line 1804  namespace {
1804       *       *
1805       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
1806       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
1807         *
1808         * @param pProgress - callback function for progress notification
1809       */       */
1810      void DimensionRegion::UpdateChunks() {      void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1811          // first update base class's chunk          // first update base class's chunk
1812          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks(pProgress);
1813    
1814            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1815            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1816            pData[12] = Crossfade.in_start;
1817            pData[13] = Crossfade.in_end;
1818            pData[14] = Crossfade.out_start;
1819            pData[15] = Crossfade.out_end;
1820    
1821          // make sure '3ewa' chunk exists          // make sure '3ewa' chunk exists
1822          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1823          if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);          if (!_3ewa) {
1824          uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();              File* pFile = (File*) GetParent()->GetParent()->GetParent();
1825                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1826                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1827            }
1828            pData = (uint8_t*) _3ewa->LoadChunkData();
1829    
1830          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1831    
1832          const uint32_t chunksize = _3ewa->GetSize();          const uint32_t chunksize = _3ewa->GetNewSize();
1833          memcpy(&pData[0], &chunksize, 4); // unknown, always chunk size?          store32(&pData[0], chunksize); // unknown, always chunk size?
1834    
1835          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1836          memcpy(&pData[4], &lfo3freq, 4);          store32(&pData[4], lfo3freq);
1837    
1838          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1839          memcpy(&pData[8], &eg3attack, 4);          store32(&pData[8], eg3attack);
1840    
1841          // next 2 bytes unknown          // next 2 bytes unknown
1842    
1843          memcpy(&pData[14], &LFO1InternalDepth, 2);          store16(&pData[14], LFO1InternalDepth);
1844    
1845          // next 2 bytes unknown          // next 2 bytes unknown
1846    
1847          memcpy(&pData[18], &LFO3InternalDepth, 2);          store16(&pData[18], LFO3InternalDepth);
1848    
1849          // next 2 bytes unknown          // next 2 bytes unknown
1850    
1851          memcpy(&pData[22], &LFO1ControlDepth, 2);          store16(&pData[22], LFO1ControlDepth);
1852    
1853          // next 2 bytes unknown          // next 2 bytes unknown
1854    
1855          memcpy(&pData[26], &LFO3ControlDepth, 2);          store16(&pData[26], LFO3ControlDepth);
1856    
1857          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1858          memcpy(&pData[28], &eg1attack, 4);          store32(&pData[28], eg1attack);
1859    
1860          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1861          memcpy(&pData[32], &eg1decay1, 4);          store32(&pData[32], eg1decay1);
1862    
1863          // next 2 bytes unknown          // next 2 bytes unknown
1864    
1865          memcpy(&pData[38], &EG1Sustain, 2);          store16(&pData[38], EG1Sustain);
1866    
1867          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1868          memcpy(&pData[40], &eg1release, 4);          store32(&pData[40], eg1release);
1869    
1870          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1871          memcpy(&pData[44], &eg1ctl, 1);          pData[44] = eg1ctl;
1872    
1873          const uint8_t eg1ctrloptions =          const uint8_t eg1ctrloptions =
1874              (EG1ControllerInvert) ? 0x01 : 0x00 |              (EG1ControllerInvert ? 0x01 : 0x00) |
1875              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1876              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1877              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1878          memcpy(&pData[45], &eg1ctrloptions, 1);          pData[45] = eg1ctrloptions;
1879    
1880          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1881          memcpy(&pData[46], &eg2ctl, 1);          pData[46] = eg2ctl;
1882    
1883          const uint8_t eg2ctrloptions =          const uint8_t eg2ctrloptions =
1884              (EG2ControllerInvert) ? 0x01 : 0x00 |              (EG2ControllerInvert ? 0x01 : 0x00) |
1885              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1886              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1887              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1888          memcpy(&pData[47], &eg2ctrloptions, 1);          pData[47] = eg2ctrloptions;
1889    
1890          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1891          memcpy(&pData[48], &lfo1freq, 4);          store32(&pData[48], lfo1freq);
1892    
1893          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1894          memcpy(&pData[52], &eg2attack, 4);          store32(&pData[52], eg2attack);
1895    
1896          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1897          memcpy(&pData[56], &eg2decay1, 4);          store32(&pData[56], eg2decay1);
1898    
1899          // next 2 bytes unknown          // next 2 bytes unknown
1900    
1901          memcpy(&pData[62], &EG2Sustain, 2);          store16(&pData[62], EG2Sustain);
1902    
1903          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1904          memcpy(&pData[64], &eg2release, 4);          store32(&pData[64], eg2release);
1905    
1906          // next 2 bytes unknown          // next 2 bytes unknown
1907    
1908          memcpy(&pData[70], &LFO2ControlDepth, 2);          store16(&pData[70], LFO2ControlDepth);
1909    
1910          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1911          memcpy(&pData[72], &lfo2freq, 4);          store32(&pData[72], lfo2freq);
1912    
1913          // next 2 bytes unknown          // next 2 bytes unknown
1914    
1915          memcpy(&pData[78], &LFO2InternalDepth, 2);          store16(&pData[78], LFO2InternalDepth);
1916    
1917          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);
1918          memcpy(&pData[80], &eg1decay2, 4);          store32(&pData[80], eg1decay2);
1919    
1920          // next 2 bytes unknown          // next 2 bytes unknown
1921    
1922          memcpy(&pData[86], &EG1PreAttack, 2);          store16(&pData[86], EG1PreAttack);
1923    
1924          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);
1925          memcpy(&pData[88], &eg2decay2, 4);          store32(&pData[88], eg2decay2);
1926    
1927          // next 2 bytes unknown          // next 2 bytes unknown
1928    
1929          memcpy(&pData[94], &EG2PreAttack, 2);          store16(&pData[94], EG2PreAttack);
1930    
1931          {          {
1932              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 1594  namespace { Line 1944  namespace {
1944                  default:                  default:
1945                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1946              }              }
1947              memcpy(&pData[96], &velocityresponse, 1);              pData[96] = velocityresponse;
1948          }          }
1949    
1950          {          {
# Line 1613  namespace { Line 1963  namespace {
1963                  default:                  default:
1964                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1965              }              }
1966              memcpy(&pData[97], &releasevelocityresponse, 1);              pData[97] = releasevelocityresponse;
1967          }          }
1968    
1969          memcpy(&pData[98], &VelocityResponseCurveScaling, 1);          pData[98] = VelocityResponseCurveScaling;
1970    
1971          memcpy(&pData[99], &AttenuationControllerThreshold, 1);          pData[99] = AttenuationControllerThreshold;
1972    
1973          // next 4 bytes unknown          // next 4 bytes unknown
1974    
1975          memcpy(&pData[104], &SampleStartOffset, 2);          store16(&pData[104], SampleStartOffset);
1976    
1977          // next 2 bytes unknown          // next 2 bytes unknown
1978    
# Line 1641  namespace { Line 1991  namespace {
1991                  default:                  default:
1992                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1993              }              }
1994              memcpy(&pData[108], &pitchTrackDimensionBypass, 1);              pData[108] = pitchTrackDimensionBypass;
1995          }          }
1996    
1997          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
1998          memcpy(&pData[109], &pan, 1);          pData[109] = pan;
1999    
2000          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
2001          memcpy(&pData[110], &selfmask, 1);          pData[110] = selfmask;
2002    
2003          // next byte unknown          // next byte unknown
2004    
# Line 1657  namespace { Line 2007  namespace {
2007              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
2008              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
2009              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
2010              memcpy(&pData[112], &lfo3ctrl, 1);              pData[112] = lfo3ctrl;
2011          }          }
2012    
2013          const uint8_t attenctl = EncodeLeverageController(AttenuationController);          const uint8_t attenctl = EncodeLeverageController(AttenuationController);
2014          memcpy(&pData[113], &attenctl, 1);          pData[113] = attenctl;
2015    
2016          {          {
2017              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
2018              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
2019              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
2020              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
2021              memcpy(&pData[114], &lfo2ctrl, 1);              pData[114] = lfo2ctrl;
2022          }          }
2023    
2024          {          {
# Line 1677  namespace { Line 2027  namespace {
2027              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
2028              if (VCFResonanceController != vcf_res_ctrl_none)              if (VCFResonanceController != vcf_res_ctrl_none)
2029                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
2030              memcpy(&pData[115], &lfo1ctrl, 1);              pData[115] = lfo1ctrl;
2031          }          }
2032    
2033          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
2034                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
2035          memcpy(&pData[116], &eg3depth, 1);          store16(&pData[116], eg3depth);
2036    
2037          // next 2 bytes unknown          // next 2 bytes unknown
2038    
2039          const uint8_t channeloffset = ChannelOffset * 4;          const uint8_t channeloffset = ChannelOffset * 4;
2040          memcpy(&pData[120], &channeloffset, 1);          pData[120] = channeloffset;
2041    
2042          {          {
2043              uint8_t regoptions = 0;              uint8_t regoptions = 0;
2044              if (MSDecode)      regoptions |= 0x01; // bit 0              if (MSDecode)      regoptions |= 0x01; // bit 0
2045              if (SustainDefeat) regoptions |= 0x02; // bit 1              if (SustainDefeat) regoptions |= 0x02; // bit 1
2046              memcpy(&pData[121], &regoptions, 1);              pData[121] = regoptions;
2047          }          }
2048    
2049          // next 2 bytes unknown          // next 2 bytes unknown
2050    
2051          memcpy(&pData[124], &VelocityUpperLimit, 1);          pData[124] = VelocityUpperLimit;
2052    
2053          // next 3 bytes unknown          // next 3 bytes unknown
2054    
2055          memcpy(&pData[128], &ReleaseTriggerDecay, 1);          pData[128] = ReleaseTriggerDecay;
2056    
2057          // next 2 bytes unknown          // next 2 bytes unknown
2058    
2059          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2060          memcpy(&pData[131], &eg1hold, 1);          pData[131] = eg1hold;
2061    
2062          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */          const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
2063                                    (VCFCutoff & 0x7f);   /* lower 7 bits */                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
2064          memcpy(&pData[132], &vcfcutoff, 1);          pData[132] = vcfcutoff;
2065    
2066          memcpy(&pData[133], &VCFCutoffController, 1);          pData[133] = VCFCutoffController;
2067    
2068          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2069                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
2070          memcpy(&pData[134], &vcfvelscale, 1);          pData[134] = vcfvelscale;
2071    
2072          // next byte unknown          // next byte unknown
2073    
2074          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */          const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2075                                       (VCFResonance & 0x7f); /* lower 7 bits */                                       (VCFResonance & 0x7f); /* lower 7 bits */
2076          memcpy(&pData[136], &vcfresonance, 1);          pData[136] = vcfresonance;
2077    
2078          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2079                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2080          memcpy(&pData[137], &vcfbreakpoint, 1);          pData[137] = vcfbreakpoint;
2081    
2082          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2083                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2084          memcpy(&pData[138], &vcfvelocity, 1);          pData[138] = vcfvelocity;
2085    
2086          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2087          memcpy(&pData[139], &vcftype, 1);          pData[139] = vcftype;
2088    
2089          if (chunksize >= 148) {          if (chunksize >= 148) {
2090              memcpy(&pData[140], DimensionUpperLimits, 8);              memcpy(&pData[140], DimensionUpperLimits, 8);
2091          }          }
2092      }      }
2093    
2094        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2095            curve_type_t curveType = releaseVelocityResponseCurve;
2096            uint8_t depth = releaseVelocityResponseDepth;
2097            // this models a strange behaviour or bug in GSt: two of the
2098            // velocity response curves for release time are not used even
2099            // if specified, instead another curve is chosen.
2100            if ((curveType == curve_type_nonlinear && depth == 0) ||
2101                (curveType == curve_type_special   && depth == 4)) {
2102                curveType = curve_type_nonlinear;
2103                depth = 3;
2104            }
2105            return GetVelocityTable(curveType, depth, 0);
2106        }
2107    
2108        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2109                                                        uint8_t vcfVelocityDynamicRange,
2110                                                        uint8_t vcfVelocityScale,
2111                                                        vcf_cutoff_ctrl_t vcfCutoffController)
2112        {
2113            curve_type_t curveType = vcfVelocityCurve;
2114            uint8_t depth = vcfVelocityDynamicRange;
2115            // even stranger GSt: two of the velocity response curves for
2116            // filter cutoff are not used, instead another special curve
2117            // is chosen. This curve is not used anywhere else.
2118            if ((curveType == curve_type_nonlinear && depth == 0) ||
2119                (curveType == curve_type_special   && depth == 4)) {
2120                curveType = curve_type_special;
2121                depth = 5;
2122            }
2123            return GetVelocityTable(curveType, depth,
2124                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2125                                        ? vcfVelocityScale : 0);
2126        }
2127    
2128      // 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
2129      double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)      double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
2130      {      {
# Line 1756  namespace { Line 2140  namespace {
2140          return table;          return table;
2141      }      }
2142    
2143        Region* DimensionRegion::GetParent() const {
2144            return pRegion;
2145        }
2146    
2147    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2148    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2149    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2150    //#pragma GCC diagnostic push
2151    //#pragma GCC diagnostic error "-Wswitch"
2152    
2153      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2154          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2155          switch (EncodedController) {          switch (EncodedController) {
# Line 1867  namespace { Line 2261  namespace {
2261                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2262                  break;                  break;
2263    
2264                // format extension (these controllers are so far only supported by
2265                // LinuxSampler & gigedit) they will *NOT* work with
2266                // Gigasampler/GigaStudio !
2267                case _lev_ctrl_CC3_EXT:
2268                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2269                    decodedcontroller.controller_number = 3;
2270                    break;
2271                case _lev_ctrl_CC6_EXT:
2272                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2273                    decodedcontroller.controller_number = 6;
2274                    break;
2275                case _lev_ctrl_CC7_EXT:
2276                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2277                    decodedcontroller.controller_number = 7;
2278                    break;
2279                case _lev_ctrl_CC8_EXT:
2280                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2281                    decodedcontroller.controller_number = 8;
2282                    break;
2283                case _lev_ctrl_CC9_EXT:
2284                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2285                    decodedcontroller.controller_number = 9;
2286                    break;
2287                case _lev_ctrl_CC10_EXT:
2288                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2289                    decodedcontroller.controller_number = 10;
2290                    break;
2291                case _lev_ctrl_CC11_EXT:
2292                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2293                    decodedcontroller.controller_number = 11;
2294                    break;
2295                case _lev_ctrl_CC14_EXT:
2296                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2297                    decodedcontroller.controller_number = 14;
2298                    break;
2299                case _lev_ctrl_CC15_EXT:
2300                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2301                    decodedcontroller.controller_number = 15;
2302                    break;
2303                case _lev_ctrl_CC20_EXT:
2304                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2305                    decodedcontroller.controller_number = 20;
2306                    break;
2307                case _lev_ctrl_CC21_EXT:
2308                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2309                    decodedcontroller.controller_number = 21;
2310                    break;
2311                case _lev_ctrl_CC22_EXT:
2312                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2313                    decodedcontroller.controller_number = 22;
2314                    break;
2315                case _lev_ctrl_CC23_EXT:
2316                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2317                    decodedcontroller.controller_number = 23;
2318                    break;
2319                case _lev_ctrl_CC24_EXT:
2320                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2321                    decodedcontroller.controller_number = 24;
2322                    break;
2323                case _lev_ctrl_CC25_EXT:
2324                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2325                    decodedcontroller.controller_number = 25;
2326                    break;
2327                case _lev_ctrl_CC26_EXT:
2328                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2329                    decodedcontroller.controller_number = 26;
2330                    break;
2331                case _lev_ctrl_CC27_EXT:
2332                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2333                    decodedcontroller.controller_number = 27;
2334                    break;
2335                case _lev_ctrl_CC28_EXT:
2336                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2337                    decodedcontroller.controller_number = 28;
2338                    break;
2339                case _lev_ctrl_CC29_EXT:
2340                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2341                    decodedcontroller.controller_number = 29;
2342                    break;
2343                case _lev_ctrl_CC30_EXT:
2344                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2345                    decodedcontroller.controller_number = 30;
2346                    break;
2347                case _lev_ctrl_CC31_EXT:
2348                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2349                    decodedcontroller.controller_number = 31;
2350                    break;
2351                case _lev_ctrl_CC68_EXT:
2352                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2353                    decodedcontroller.controller_number = 68;
2354                    break;
2355                case _lev_ctrl_CC69_EXT:
2356                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2357                    decodedcontroller.controller_number = 69;
2358                    break;
2359                case _lev_ctrl_CC70_EXT:
2360                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2361                    decodedcontroller.controller_number = 70;
2362                    break;
2363                case _lev_ctrl_CC71_EXT:
2364                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2365                    decodedcontroller.controller_number = 71;
2366                    break;
2367                case _lev_ctrl_CC72_EXT:
2368                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2369                    decodedcontroller.controller_number = 72;
2370                    break;
2371                case _lev_ctrl_CC73_EXT:
2372                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2373                    decodedcontroller.controller_number = 73;
2374                    break;
2375                case _lev_ctrl_CC74_EXT:
2376                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2377                    decodedcontroller.controller_number = 74;
2378                    break;
2379                case _lev_ctrl_CC75_EXT:
2380                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2381                    decodedcontroller.controller_number = 75;
2382                    break;
2383                case _lev_ctrl_CC76_EXT:
2384                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2385                    decodedcontroller.controller_number = 76;
2386                    break;
2387                case _lev_ctrl_CC77_EXT:
2388                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2389                    decodedcontroller.controller_number = 77;
2390                    break;
2391                case _lev_ctrl_CC78_EXT:
2392                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2393                    decodedcontroller.controller_number = 78;
2394                    break;
2395                case _lev_ctrl_CC79_EXT:
2396                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2397                    decodedcontroller.controller_number = 79;
2398                    break;
2399                case _lev_ctrl_CC84_EXT:
2400                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2401                    decodedcontroller.controller_number = 84;
2402                    break;
2403                case _lev_ctrl_CC85_EXT:
2404                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2405                    decodedcontroller.controller_number = 85;
2406                    break;
2407                case _lev_ctrl_CC86_EXT:
2408                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2409                    decodedcontroller.controller_number = 86;
2410                    break;
2411                case _lev_ctrl_CC87_EXT:
2412                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2413                    decodedcontroller.controller_number = 87;
2414                    break;
2415                case _lev_ctrl_CC89_EXT:
2416                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2417                    decodedcontroller.controller_number = 89;
2418                    break;
2419                case _lev_ctrl_CC90_EXT:
2420                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2421                    decodedcontroller.controller_number = 90;
2422                    break;
2423                case _lev_ctrl_CC96_EXT:
2424                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2425                    decodedcontroller.controller_number = 96;
2426                    break;
2427                case _lev_ctrl_CC97_EXT:
2428                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2429                    decodedcontroller.controller_number = 97;
2430                    break;
2431                case _lev_ctrl_CC102_EXT:
2432                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2433                    decodedcontroller.controller_number = 102;
2434                    break;
2435                case _lev_ctrl_CC103_EXT:
2436                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2437                    decodedcontroller.controller_number = 103;
2438                    break;
2439                case _lev_ctrl_CC104_EXT:
2440                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2441                    decodedcontroller.controller_number = 104;
2442                    break;
2443                case _lev_ctrl_CC105_EXT:
2444                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2445                    decodedcontroller.controller_number = 105;
2446                    break;
2447                case _lev_ctrl_CC106_EXT:
2448                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2449                    decodedcontroller.controller_number = 106;
2450                    break;
2451                case _lev_ctrl_CC107_EXT:
2452                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2453                    decodedcontroller.controller_number = 107;
2454                    break;
2455                case _lev_ctrl_CC108_EXT:
2456                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2457                    decodedcontroller.controller_number = 108;
2458                    break;
2459                case _lev_ctrl_CC109_EXT:
2460                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2461                    decodedcontroller.controller_number = 109;
2462                    break;
2463                case _lev_ctrl_CC110_EXT:
2464                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2465                    decodedcontroller.controller_number = 110;
2466                    break;
2467                case _lev_ctrl_CC111_EXT:
2468                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2469                    decodedcontroller.controller_number = 111;
2470                    break;
2471                case _lev_ctrl_CC112_EXT:
2472                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2473                    decodedcontroller.controller_number = 112;
2474                    break;
2475                case _lev_ctrl_CC113_EXT:
2476                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2477                    decodedcontroller.controller_number = 113;
2478                    break;
2479                case _lev_ctrl_CC114_EXT:
2480                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2481                    decodedcontroller.controller_number = 114;
2482                    break;
2483                case _lev_ctrl_CC115_EXT:
2484                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2485                    decodedcontroller.controller_number = 115;
2486                    break;
2487                case _lev_ctrl_CC116_EXT:
2488                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2489                    decodedcontroller.controller_number = 116;
2490                    break;
2491                case _lev_ctrl_CC117_EXT:
2492                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2493                    decodedcontroller.controller_number = 117;
2494                    break;
2495                case _lev_ctrl_CC118_EXT:
2496                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2497                    decodedcontroller.controller_number = 118;
2498                    break;
2499                case _lev_ctrl_CC119_EXT:
2500                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2501                    decodedcontroller.controller_number = 119;
2502                    break;
2503    
2504              // unknown controller type              // unknown controller type
2505              default:              default:
2506                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2507          }          }
2508          return decodedcontroller;          return decodedcontroller;
2509      }      }
2510        
2511    // see above (diagnostic push not supported prior GCC 4.6)
2512    //#pragma GCC diagnostic pop
2513    
2514      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2515          _lev_ctrl_t encodedcontroller;          _lev_ctrl_t encodedcontroller;
# Line 1960  namespace { Line 2597  namespace {
2597                      case 95:                      case 95:
2598                          encodedcontroller = _lev_ctrl_effect5depth;                          encodedcontroller = _lev_ctrl_effect5depth;
2599                          break;                          break;
2600    
2601                        // format extension (these controllers are so far only
2602                        // supported by LinuxSampler & gigedit) they will *NOT*
2603                        // work with Gigasampler/GigaStudio !
2604                        case 3:
2605                            encodedcontroller = _lev_ctrl_CC3_EXT;
2606                            break;
2607                        case 6:
2608                            encodedcontroller = _lev_ctrl_CC6_EXT;
2609                            break;
2610                        case 7:
2611                            encodedcontroller = _lev_ctrl_CC7_EXT;
2612                            break;
2613                        case 8:
2614                            encodedcontroller = _lev_ctrl_CC8_EXT;
2615                            break;
2616                        case 9:
2617                            encodedcontroller = _lev_ctrl_CC9_EXT;
2618                            break;
2619                        case 10:
2620                            encodedcontroller = _lev_ctrl_CC10_EXT;
2621                            break;
2622                        case 11:
2623                            encodedcontroller = _lev_ctrl_CC11_EXT;
2624                            break;
2625                        case 14:
2626                            encodedcontroller = _lev_ctrl_CC14_EXT;
2627                            break;
2628                        case 15:
2629                            encodedcontroller = _lev_ctrl_CC15_EXT;
2630                            break;
2631                        case 20:
2632                            encodedcontroller = _lev_ctrl_CC20_EXT;
2633                            break;
2634                        case 21:
2635                            encodedcontroller = _lev_ctrl_CC21_EXT;
2636                            break;
2637                        case 22:
2638                            encodedcontroller = _lev_ctrl_CC22_EXT;
2639                            break;
2640                        case 23:
2641                            encodedcontroller = _lev_ctrl_CC23_EXT;
2642                            break;
2643                        case 24:
2644                            encodedcontroller = _lev_ctrl_CC24_EXT;
2645                            break;
2646                        case 25:
2647                            encodedcontroller = _lev_ctrl_CC25_EXT;
2648                            break;
2649                        case 26:
2650                            encodedcontroller = _lev_ctrl_CC26_EXT;
2651                            break;
2652                        case 27:
2653                            encodedcontroller = _lev_ctrl_CC27_EXT;
2654                            break;
2655                        case 28:
2656                            encodedcontroller = _lev_ctrl_CC28_EXT;
2657                            break;
2658                        case 29:
2659                            encodedcontroller = _lev_ctrl_CC29_EXT;
2660                            break;
2661                        case 30:
2662                            encodedcontroller = _lev_ctrl_CC30_EXT;
2663                            break;
2664                        case 31:
2665                            encodedcontroller = _lev_ctrl_CC31_EXT;
2666                            break;
2667                        case 68:
2668                            encodedcontroller = _lev_ctrl_CC68_EXT;
2669                            break;
2670                        case 69:
2671                            encodedcontroller = _lev_ctrl_CC69_EXT;
2672                            break;
2673                        case 70:
2674                            encodedcontroller = _lev_ctrl_CC70_EXT;
2675                            break;
2676                        case 71:
2677                            encodedcontroller = _lev_ctrl_CC71_EXT;
2678                            break;
2679                        case 72:
2680                            encodedcontroller = _lev_ctrl_CC72_EXT;
2681                            break;
2682                        case 73:
2683                            encodedcontroller = _lev_ctrl_CC73_EXT;
2684                            break;
2685                        case 74:
2686                            encodedcontroller = _lev_ctrl_CC74_EXT;
2687                            break;
2688                        case 75:
2689                            encodedcontroller = _lev_ctrl_CC75_EXT;
2690                            break;
2691                        case 76:
2692                            encodedcontroller = _lev_ctrl_CC76_EXT;
2693                            break;
2694                        case 77:
2695                            encodedcontroller = _lev_ctrl_CC77_EXT;
2696                            break;
2697                        case 78:
2698                            encodedcontroller = _lev_ctrl_CC78_EXT;
2699                            break;
2700                        case 79:
2701                            encodedcontroller = _lev_ctrl_CC79_EXT;
2702                            break;
2703                        case 84:
2704                            encodedcontroller = _lev_ctrl_CC84_EXT;
2705                            break;
2706                        case 85:
2707                            encodedcontroller = _lev_ctrl_CC85_EXT;
2708                            break;
2709                        case 86:
2710                            encodedcontroller = _lev_ctrl_CC86_EXT;
2711                            break;
2712                        case 87:
2713                            encodedcontroller = _lev_ctrl_CC87_EXT;
2714                            break;
2715                        case 89:
2716                            encodedcontroller = _lev_ctrl_CC89_EXT;
2717                            break;
2718                        case 90:
2719                            encodedcontroller = _lev_ctrl_CC90_EXT;
2720                            break;
2721                        case 96:
2722                            encodedcontroller = _lev_ctrl_CC96_EXT;
2723                            break;
2724                        case 97:
2725                            encodedcontroller = _lev_ctrl_CC97_EXT;
2726                            break;
2727                        case 102:
2728                            encodedcontroller = _lev_ctrl_CC102_EXT;
2729                            break;
2730                        case 103:
2731                            encodedcontroller = _lev_ctrl_CC103_EXT;
2732                            break;
2733                        case 104:
2734                            encodedcontroller = _lev_ctrl_CC104_EXT;
2735                            break;
2736                        case 105:
2737                            encodedcontroller = _lev_ctrl_CC105_EXT;
2738                            break;
2739                        case 106:
2740                            encodedcontroller = _lev_ctrl_CC106_EXT;
2741                            break;
2742                        case 107:
2743                            encodedcontroller = _lev_ctrl_CC107_EXT;
2744                            break;
2745                        case 108:
2746                            encodedcontroller = _lev_ctrl_CC108_EXT;
2747                            break;
2748                        case 109:
2749                            encodedcontroller = _lev_ctrl_CC109_EXT;
2750                            break;
2751                        case 110:
2752                            encodedcontroller = _lev_ctrl_CC110_EXT;
2753                            break;
2754                        case 111:
2755                            encodedcontroller = _lev_ctrl_CC111_EXT;
2756                            break;
2757                        case 112:
2758                            encodedcontroller = _lev_ctrl_CC112_EXT;
2759                            break;
2760                        case 113:
2761                            encodedcontroller = _lev_ctrl_CC113_EXT;
2762                            break;
2763                        case 114:
2764                            encodedcontroller = _lev_ctrl_CC114_EXT;
2765                            break;
2766                        case 115:
2767                            encodedcontroller = _lev_ctrl_CC115_EXT;
2768                            break;
2769                        case 116:
2770                            encodedcontroller = _lev_ctrl_CC116_EXT;
2771                            break;
2772                        case 117:
2773                            encodedcontroller = _lev_ctrl_CC117_EXT;
2774                            break;
2775                        case 118:
2776                            encodedcontroller = _lev_ctrl_CC118_EXT;
2777                            break;
2778                        case 119:
2779                            encodedcontroller = _lev_ctrl_CC119_EXT;
2780                            break;
2781    
2782                      default:                      default:
2783                          throw gig::Exception("leverage controller number is not supported by the gig format");                          throw gig::Exception("leverage controller number is not supported by the gig format");
2784                  }                  }
2785                    break;
2786              default:              default:
2787                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2788          }          }
# Line 2008  namespace { Line 2828  namespace {
2828          return pVelocityCutoffTable[MIDIKeyVelocity];          return pVelocityCutoffTable[MIDIKeyVelocity];
2829      }      }
2830    
2831        /**
2832         * Updates the respective member variable and the lookup table / cache
2833         * that depends on this value.
2834         */
2835        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2836            pVelocityAttenuationTable =
2837                GetVelocityTable(
2838                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2839                );
2840            VelocityResponseCurve = curve;
2841        }
2842    
2843        /**
2844         * Updates the respective member variable and the lookup table / cache
2845         * that depends on this value.
2846         */
2847        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2848            pVelocityAttenuationTable =
2849                GetVelocityTable(
2850                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2851                );
2852            VelocityResponseDepth = depth;
2853        }
2854    
2855        /**
2856         * Updates the respective member variable and the lookup table / cache
2857         * that depends on this value.
2858         */
2859        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2860            pVelocityAttenuationTable =
2861                GetVelocityTable(
2862                    VelocityResponseCurve, VelocityResponseDepth, scaling
2863                );
2864            VelocityResponseCurveScaling = scaling;
2865        }
2866    
2867        /**
2868         * Updates the respective member variable and the lookup table / cache
2869         * that depends on this value.
2870         */
2871        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2872            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2873            ReleaseVelocityResponseCurve = curve;
2874        }
2875    
2876        /**
2877         * Updates the respective member variable and the lookup table / cache
2878         * that depends on this value.
2879         */
2880        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2881            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2882            ReleaseVelocityResponseDepth = depth;
2883        }
2884    
2885        /**
2886         * Updates the respective member variable and the lookup table / cache
2887         * that depends on this value.
2888         */
2889        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2890            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2891            VCFCutoffController = controller;
2892        }
2893    
2894        /**
2895         * Updates the respective member variable and the lookup table / cache
2896         * that depends on this value.
2897         */
2898        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2899            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2900            VCFVelocityCurve = curve;
2901        }
2902    
2903        /**
2904         * Updates the respective member variable and the lookup table / cache
2905         * that depends on this value.
2906         */
2907        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2908            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2909            VCFVelocityDynamicRange = range;
2910        }
2911    
2912        /**
2913         * Updates the respective member variable and the lookup table / cache
2914         * that depends on this value.
2915         */
2916        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2917            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2918            VCFVelocityScale = scaling;
2919        }
2920    
2921      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) {
2922    
2923          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 2080  namespace { Line 2990  namespace {
2990  // *  // *
2991    
2992      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;  
   
2993          // Initialization          // Initialization
2994          Dimensions = 0;          Dimensions = 0;
2995          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
# Line 2093  namespace { Line 3001  namespace {
3001    
3002          // Actual Loading          // Actual Loading
3003    
3004            if (!file->GetAutoLoad()) return;
3005    
3006          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
3007    
3008          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2101  namespace { Line 3011  namespace {
3011              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
3012                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
3013                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
3014                  _3lnk->ReadUint8(); // probably the position of the dimension                  _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
3015                  _3lnk->ReadUint8(); // unknown                  _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
3016                  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)
3017                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
3018                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
# Line 2115  namespace { Line 3025  namespace {
3025                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
3026                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
3027                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
3028                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
3029                                                             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;  
3030                      Dimensions++;                      Dimensions++;
3031    
3032                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
# Line 2144  namespace { Line 3046  namespace {
3046              else              else
3047                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
3048    
3049              // load sample references              // load sample references (if auto loading is enabled)
3050              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
3051                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
3052                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
3053                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
3054                    }
3055                    GetSample(); // load global region sample reference
3056                }
3057            } else {
3058                DimensionRegions = 0;
3059                for (int i = 0 ; i < 8 ; i++) {
3060                    pDimensionDefinitions[i].dimension  = dimension_none;
3061                    pDimensionDefinitions[i].bits       = 0;
3062                    pDimensionDefinitions[i].zones      = 0;
3063              }              }
             GetSample(); // load global region sample reference  
3064          }          }
3065    
3066          // make sure there is at least one dimension region          // make sure there is at least one dimension region
# Line 2157  namespace { Line 3068  namespace {
3068              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
3069              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
3070              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
3071              pDimensionRegions[0] = new DimensionRegion(_3ewl);              pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
3072              DimensionRegions = 1;              DimensionRegions = 1;
3073          }          }
3074      }      }
# Line 2169  namespace { Line 3080  namespace {
3080       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
3081       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
3082       *       *
3083         * @param pProgress - callback function for progress notification
3084       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3085       */       */
3086      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
3087            // in the gig format we don't care about the Region's sample reference
3088            // but we still have to provide some existing one to not corrupt the
3089            // file, so to avoid the latter we simply always assign the sample of
3090            // the first dimension region of this region
3091            pSample = pDimensionRegions[0]->pSample;
3092    
3093          // first update base class's chunks          // first update base class's chunks
3094          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks(pProgress);
3095    
3096          // update dimension region's chunks          // update dimension region's chunks
3097          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
3098              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks(pProgress);
3099          }          }
3100    
3101          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
3102          const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;          bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
3103          const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;          const int iMaxDimensions =  version3 ? 8 : 5;
3104            const int iMaxDimensionRegions = version3 ? 256 : 32;
3105    
3106          // make sure '3lnk' chunk exists          // make sure '3lnk' chunk exists
3107          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
3108          if (!_3lnk) {          if (!_3lnk) {
3109              const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;              const int _3lnkChunkSize = version3 ? 1092 : 172;
3110              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3111                memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3112    
3113                // move 3prg to last position
3114                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3115          }          }
3116    
3117          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
3118          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
3119          memcpy(&pData[0], &DimensionRegions, 4);          store32(&pData[0], DimensionRegions);
3120            int shift = 0;
3121          for (int i = 0; i < iMaxDimensions; i++) {          for (int i = 0; i < iMaxDimensions; i++) {
3122              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3123              pData[5 + i * 8] = pDimensionDefinitions[i].bits;              pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3124              // next 2 bytes unknown              pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3125                pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3126              pData[8 + i * 8] = pDimensionDefinitions[i].zones;              pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3127              // next 3 bytes unknown              // next 3 bytes unknown, always zero?
3128    
3129                shift += pDimensionDefinitions[i].bits;
3130          }          }
3131    
3132          // update wave pool table in '3lnk' chunk          // update wave pool table in '3lnk' chunk
3133          const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;          const int iWavePoolOffset = version3 ? 68 : 44;
3134          for (uint i = 0; i < iMaxDimensionRegions; i++) {          for (uint i = 0; i < iMaxDimensionRegions; i++) {
3135              int iWaveIndex = -1;              int iWaveIndex = -1;
3136              if (i < DimensionRegions) {              if (i < DimensionRegions) {
# Line 2216  namespace { Line 3143  namespace {
3143                          break;                          break;
3144                      }                      }
3145                  }                  }
                 if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");  
3146              }              }
3147              memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3148          }          }
3149      }      }
3150    
# Line 2229  namespace { Line 3155  namespace {
3155              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
3156              while (_3ewl) {              while (_3ewl) {
3157                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3158                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3159                      dimensionRegionNr++;                      dimensionRegionNr++;
3160                  }                  }
3161                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 2238  namespace { Line 3164  namespace {
3164          }          }
3165      }      }
3166    
3167        void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3168            // update KeyRange struct and make sure regions are in correct order
3169            DLS::Region::SetKeyRange(Low, High);
3170            // update Region key table for fast lookup
3171            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3172        }
3173    
3174      void Region::UpdateVelocityTable() {      void Region::UpdateVelocityTable() {
3175          // get velocity dimension's index          // get velocity dimension's index
3176          int veldim = -1;          int veldim = -1;
# Line 2252  namespace { Line 3185  namespace {
3185          int step = 1;          int step = 1;
3186          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3187          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3188    
3189          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3190          int dim[8] = { 0 };          int dim[8] = { 0 };
3191          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3192                const int end = i + step * pDimensionDefinitions[veldim].zones;
3193    
3194                // create a velocity table for all cases where the velocity zone is zero
3195              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3196                  pDimensionRegions[i]->VelocityUpperLimit) {                  pDimensionRegions[i]->VelocityUpperLimit) {
3197                  // create the velocity table                  // create the velocity table
# Line 2288  namespace { Line 3222  namespace {
3222                  }                  }
3223              }              }
3224    
3225                // jump to the next case where the velocity zone is zero
3226              int j;              int j;
3227              int shift = 0;              int shift = 0;
3228              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 2324  namespace { Line 3259  namespace {
3259       *                        dimension bits limit is violated       *                        dimension bits limit is violated
3260       */       */
3261      void Region::AddDimension(dimension_def_t* pDimDef) {      void Region::AddDimension(dimension_def_t* pDimDef) {
3262            // some initial sanity checks of the given dimension definition
3263            if (pDimDef->zones < 2)
3264                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3265            if (pDimDef->bits < 1)
3266                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3267            if (pDimDef->dimension == dimension_samplechannel) {
3268                if (pDimDef->zones != 2)
3269                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3270                if (pDimDef->bits != 1)
3271                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3272            }
3273    
3274          // check if max. amount of dimensions reached          // check if max. amount of dimensions reached
3275          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3276          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
# Line 2343  namespace { Line 3290  namespace {
3290              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3291                  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");
3292    
3293            // pos is where the new dimension should be placed, normally
3294            // last in list, except for the samplechannel dimension which
3295            // has to be first in list
3296            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3297            int bitpos = 0;
3298            for (int i = 0 ; i < pos ; i++)
3299                bitpos += pDimensionDefinitions[i].bits;
3300    
3301            // make room for the new dimension
3302            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3303            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3304                for (int j = Dimensions ; j > pos ; j--) {
3305                    pDimensionRegions[i]->DimensionUpperLimits[j] =
3306                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
3307                }
3308            }
3309    
3310          // assign definition of new dimension          // assign definition of new dimension
3311          pDimensionDefinitions[Dimensions] = *pDimDef;          pDimensionDefinitions[pos] = *pDimDef;
3312    
3313            // auto correct certain dimension definition fields (where possible)
3314            pDimensionDefinitions[pos].split_type  =
3315                __resolveSplitType(pDimensionDefinitions[pos].dimension);
3316            pDimensionDefinitions[pos].zone_size =
3317                __resolveZoneSize(pDimensionDefinitions[pos]);
3318    
3319            // create new dimension region(s) for this new dimension, and make
3320            // sure that the dimension regions are placed correctly in both the
3321            // RIFF list and the pDimensionRegions array
3322            RIFF::Chunk* moveTo = NULL;
3323            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3324            for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3325                for (int k = 0 ; k < (1 << bitpos) ; k++) {
3326                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3327                }
3328                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3329                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
3330                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3331                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3332                        // create a new dimension region and copy all parameter values from
3333                        // an existing dimension region
3334                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3335                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3336    
3337                        DimensionRegions++;
3338                    }
3339                }
3340                moveTo = pDimensionRegions[i]->pParentList;
3341            }
3342    
3343          // create new dimension region(s) for this new dimension          // initialize the upper limits for this dimension
3344          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {          int mask = (1 << bitpos) - 1;
3345              //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values          for (int z = 0 ; z < pDimDef->zones ; z++) {
3346              RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);              uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3347              pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);              for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3348              DimensionRegions++;                  pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3349                                      (z << bitpos) |
3350                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3351                }
3352          }          }
3353    
3354          Dimensions++;          Dimensions++;
# Line 2394  namespace { Line 3391  namespace {
3391          for (int i = iDimensionNr + 1; i < Dimensions; i++)          for (int i = iDimensionNr + 1; i < Dimensions; i++)
3392              iUpperBits += pDimensionDefinitions[i].bits;              iUpperBits += pDimensionDefinitions[i].bits;
3393    
3394            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3395    
3396          // delete dimension regions which belong to the given dimension          // delete dimension regions which belong to the given dimension
3397          // (that is where the dimension's bit > 0)          // (that is where the dimension's bit > 0)
3398          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
# Line 2402  namespace { Line 3401  namespace {
3401                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3402                                      iObsoleteBit << iLowerBits |                                      iObsoleteBit << iLowerBits |
3403                                      iLowerBit;                                      iLowerBit;
3404    
3405                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3406                      delete pDimensionRegions[iToDelete];                      delete pDimensionRegions[iToDelete];
3407                      pDimensionRegions[iToDelete] = NULL;                      pDimensionRegions[iToDelete] = NULL;
3408                      DimensionRegions--;                      DimensionRegions--;
# Line 2422  namespace { Line 3423  namespace {
3423              }              }
3424          }          }
3425    
3426            // remove the this dimension from the upper limits arrays
3427            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3428                DimensionRegion* d = pDimensionRegions[j];
3429                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3430                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
3431                }
3432                d->DimensionUpperLimits[Dimensions - 1] = 127;
3433            }
3434    
3435          // 'remove' dimension definition          // 'remove' dimension definition
3436          for (int i = iDimensionNr + 1; i < Dimensions; i++) {          for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3437              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
# Line 2436  namespace { Line 3446  namespace {
3446          if (pDimDef->dimension == dimension_layer) Layers = 1;          if (pDimDef->dimension == dimension_layer) Layers = 1;
3447      }      }
3448    
3449        /** @brief Delete one split zone of a dimension (decrement zone amount).
3450         *
3451         * Instead of deleting an entire dimensions, this method will only delete
3452         * one particular split zone given by @a zone of the Region's dimension
3453         * given by @a type. So this method will simply decrement the amount of
3454         * zones by one of the dimension in question. To be able to do that, the
3455         * respective dimension must exist on this Region and it must have at least
3456         * 3 zones. All DimensionRegion objects associated with the zone will be
3457         * deleted.
3458         *
3459         * @param type - identifies the dimension where a zone shall be deleted
3460         * @param zone - index of the dimension split zone that shall be deleted
3461         * @throws gig::Exception if requested zone could not be deleted
3462         */
3463        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3464            dimension_def_t* oldDef = GetDimensionDefinition(type);
3465            if (!oldDef)
3466                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3467            if (oldDef->zones <= 2)
3468                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3469            if (zone < 0 || zone >= oldDef->zones)
3470                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3471    
3472            const int newZoneSize = oldDef->zones - 1;
3473    
3474            // create a temporary Region which just acts as a temporary copy
3475            // container and will be deleted at the end of this function and will
3476            // also not be visible through the API during this process
3477            gig::Region* tempRgn = NULL;
3478            {
3479                // adding these temporary chunks is probably not even necessary
3480                Instrument* instr = static_cast<Instrument*>(GetParent());
3481                RIFF::List* pCkInstrument = instr->pCkInstrument;
3482                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3483                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3484                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3485                tempRgn = new Region(instr, rgn);
3486            }
3487    
3488            // copy this region's dimensions (with already the dimension split size
3489            // requested by the arguments of this method call) to the temporary
3490            // region, and don't use Region::CopyAssign() here for this task, since
3491            // it would also alter fast lookup helper variables here and there
3492            dimension_def_t newDef;
3493            for (int i = 0; i < Dimensions; ++i) {
3494                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3495                // is this the dimension requested by the method arguments? ...
3496                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3497                    def.zones = newZoneSize;
3498                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3499                    newDef = def;
3500                }
3501                tempRgn->AddDimension(&def);
3502            }
3503    
3504            // find the dimension index in the tempRegion which is the dimension
3505            // type passed to this method (paranoidly expecting different order)
3506            int tempReducedDimensionIndex = -1;
3507            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3508                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3509                    tempReducedDimensionIndex = d;
3510                    break;
3511                }
3512            }
3513    
3514            // copy dimension regions from this region to the temporary region
3515            for (int iDst = 0; iDst < 256; ++iDst) {
3516                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3517                if (!dstDimRgn) continue;
3518                std::map<dimension_t,int> dimCase;
3519                bool isValidZone = true;
3520                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3521                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3522                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3523                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3524                    baseBits += dstBits;
3525                    // there are also DimensionRegion objects of unused zones, skip them
3526                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3527                        isValidZone = false;
3528                        break;
3529                    }
3530                }
3531                if (!isValidZone) continue;
3532                // a bit paranoid: cope with the chance that the dimensions would
3533                // have different order in source and destination regions
3534                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3535                if (dimCase[type] >= zone) dimCase[type]++;
3536                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3537                dstDimRgn->CopyAssign(srcDimRgn);
3538                // if this is the upper most zone of the dimension passed to this
3539                // method, then correct (raise) its upper limit to 127
3540                if (newDef.split_type == split_type_normal && isLastZone)
3541                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3542            }
3543    
3544            // now tempRegion's dimensions and DimensionRegions basically reflect
3545            // what we wanted to get for this actual Region here, so we now just
3546            // delete and recreate the dimension in question with the new amount
3547            // zones and then copy back from tempRegion      
3548            DeleteDimension(oldDef);
3549            AddDimension(&newDef);
3550            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3551                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3552                if (!srcDimRgn) continue;
3553                std::map<dimension_t,int> dimCase;
3554                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3555                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3556                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3557                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3558                    baseBits += srcBits;
3559                }
3560                // a bit paranoid: cope with the chance that the dimensions would
3561                // have different order in source and destination regions
3562                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3563                if (!dstDimRgn) continue;
3564                dstDimRgn->CopyAssign(srcDimRgn);
3565            }
3566    
3567            // delete temporary region
3568            delete tempRgn;
3569    
3570            UpdateVelocityTable();
3571        }
3572    
3573        /** @brief Divide split zone of a dimension in two (increment zone amount).
3574         *
3575         * This will increment the amount of zones for the dimension (given by
3576         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3577         * in the middle of its zone range in two. So the two zones resulting from
3578         * the zone being splitted, will be an equivalent copy regarding all their
3579         * articulation informations and sample reference. The two zones will only
3580         * differ in their zone's upper limit
3581         * (DimensionRegion::DimensionUpperLimits).
3582         *
3583         * @param type - identifies the dimension where a zone shall be splitted
3584         * @param zone - index of the dimension split zone that shall be splitted
3585         * @throws gig::Exception if requested zone could not be splitted
3586         */
3587        void Region::SplitDimensionZone(dimension_t type, int zone) {
3588            dimension_def_t* oldDef = GetDimensionDefinition(type);
3589            if (!oldDef)
3590                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3591            if (zone < 0 || zone >= oldDef->zones)
3592                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3593    
3594            const int newZoneSize = oldDef->zones + 1;
3595    
3596            // create a temporary Region which just acts as a temporary copy
3597            // container and will be deleted at the end of this function and will
3598            // also not be visible through the API during this process
3599            gig::Region* tempRgn = NULL;
3600            {
3601                // adding these temporary chunks is probably not even necessary
3602                Instrument* instr = static_cast<Instrument*>(GetParent());
3603                RIFF::List* pCkInstrument = instr->pCkInstrument;
3604                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3605                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3606                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3607                tempRgn = new Region(instr, rgn);
3608            }
3609    
3610            // copy this region's dimensions (with already the dimension split size
3611            // requested by the arguments of this method call) to the temporary
3612            // region, and don't use Region::CopyAssign() here for this task, since
3613            // it would also alter fast lookup helper variables here and there
3614            dimension_def_t newDef;
3615            for (int i = 0; i < Dimensions; ++i) {
3616                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3617                // is this the dimension requested by the method arguments? ...
3618                if (def.dimension == type) { // ... if yes, increment zone amount by one
3619                    def.zones = newZoneSize;
3620                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3621                    newDef = def;
3622                }
3623                tempRgn->AddDimension(&def);
3624            }
3625    
3626            // find the dimension index in the tempRegion which is the dimension
3627            // type passed to this method (paranoidly expecting different order)
3628            int tempIncreasedDimensionIndex = -1;
3629            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3630                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3631                    tempIncreasedDimensionIndex = d;
3632                    break;
3633                }
3634            }
3635    
3636            // copy dimension regions from this region to the temporary region
3637            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3638                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3639                if (!srcDimRgn) continue;
3640                std::map<dimension_t,int> dimCase;
3641                bool isValidZone = true;
3642                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3643                    const int srcBits = pDimensionDefinitions[d].bits;
3644                    dimCase[pDimensionDefinitions[d].dimension] =
3645                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3646                    // there are also DimensionRegion objects for unused zones, skip them
3647                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3648                        isValidZone = false;
3649                        break;
3650                    }
3651                    baseBits += srcBits;
3652                }
3653                if (!isValidZone) continue;
3654                // a bit paranoid: cope with the chance that the dimensions would
3655                // have different order in source and destination regions            
3656                if (dimCase[type] > zone) dimCase[type]++;
3657                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3658                dstDimRgn->CopyAssign(srcDimRgn);
3659                // if this is the requested zone to be splitted, then also copy
3660                // the source DimensionRegion to the newly created target zone
3661                // and set the old zones upper limit lower
3662                if (dimCase[type] == zone) {
3663                    // lower old zones upper limit
3664                    if (newDef.split_type == split_type_normal) {
3665                        const int high =
3666                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3667                        int low = 0;
3668                        if (zone > 0) {
3669                            std::map<dimension_t,int> lowerCase = dimCase;
3670                            lowerCase[type]--;
3671                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3672                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3673                        }
3674                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3675                    }
3676                    // fill the newly created zone of the divided zone as well
3677                    dimCase[type]++;
3678                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3679                    dstDimRgn->CopyAssign(srcDimRgn);
3680                }
3681            }
3682    
3683            // now tempRegion's dimensions and DimensionRegions basically reflect
3684            // what we wanted to get for this actual Region here, so we now just
3685            // delete and recreate the dimension in question with the new amount
3686            // zones and then copy back from tempRegion      
3687            DeleteDimension(oldDef);
3688            AddDimension(&newDef);
3689            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3690                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3691                if (!srcDimRgn) continue;
3692                std::map<dimension_t,int> dimCase;
3693                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3694                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3695                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3696                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3697                    baseBits += srcBits;
3698                }
3699                // a bit paranoid: cope with the chance that the dimensions would
3700                // have different order in source and destination regions
3701                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3702                if (!dstDimRgn) continue;
3703                dstDimRgn->CopyAssign(srcDimRgn);
3704            }
3705    
3706            // delete temporary region
3707            delete tempRgn;
3708    
3709            UpdateVelocityTable();
3710        }
3711    
3712        /** @brief Change type of an existing dimension.
3713         *
3714         * Alters the dimension type of a dimension already existing on this
3715         * region. If there is currently no dimension on this Region with type
3716         * @a oldType, then this call with throw an Exception. Likewise there are
3717         * cases where the requested dimension type cannot be performed. For example
3718         * if the new dimension type shall be gig::dimension_samplechannel, and the
3719         * current dimension has more than 2 zones. In such cases an Exception is
3720         * thrown as well.
3721         *
3722         * @param oldType - identifies the existing dimension to be changed
3723         * @param newType - to which dimension type it should be changed to
3724         * @throws gig::Exception if requested change cannot be performed
3725         */
3726        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3727            if (oldType == newType) return;
3728            dimension_def_t* def = GetDimensionDefinition(oldType);
3729            if (!def)
3730                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3731            if (newType == dimension_samplechannel && def->zones != 2)
3732                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3733            if (GetDimensionDefinition(newType))
3734                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3735            def->dimension  = newType;
3736            def->split_type = __resolveSplitType(newType);
3737        }
3738    
3739        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3740            uint8_t bits[8] = {};
3741            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3742                 it != DimCase.end(); ++it)
3743            {
3744                for (int d = 0; d < Dimensions; ++d) {
3745                    if (pDimensionDefinitions[d].dimension == it->first) {
3746                        bits[d] = it->second;
3747                        goto nextDimCaseSlice;
3748                    }
3749                }
3750                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3751                nextDimCaseSlice:
3752                ; // noop
3753            }
3754            return GetDimensionRegionByBit(bits);
3755        }
3756    
3757        /**
3758         * Searches in the current Region for a dimension of the given dimension
3759         * type and returns the precise configuration of that dimension in this
3760         * Region.
3761         *
3762         * @param type - dimension type of the sought dimension
3763         * @returns dimension definition or NULL if there is no dimension with
3764         *          sought type in this Region.
3765         */
3766        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3767            for (int i = 0; i < Dimensions; ++i)
3768                if (pDimensionDefinitions[i].dimension == type)
3769                    return &pDimensionDefinitions[i];
3770            return NULL;
3771        }
3772    
3773      Region::~Region() {      Region::~Region() {
3774          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
3775              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
# Line 2493  namespace { Line 3827  namespace {
3827              }              }
3828              bitpos += pDimensionDefinitions[i].bits;              bitpos += pDimensionDefinitions[i].bits;
3829          }          }
3830          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3831            if (!dimreg) return NULL;
3832          if (veldim != -1) {          if (veldim != -1) {
3833              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3834              if (dimreg->VelocityTable) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3835                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3836              else // normal split type              else // normal split type
3837                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3838    
3839              dimregidx |= bits << velbitpos;              const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3840              dimreg = pDimensionRegions[dimregidx];              dimregidx |= (bits & limiter_mask) << velbitpos;
3841                dimreg = pDimensionRegions[dimregidx & 255];
3842          }          }
3843          return dimreg;          return dimreg;
3844      }      }
3845    
3846        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3847            uint8_t bits;
3848            int veldim = -1;
3849            int velbitpos;
3850            int bitpos = 0;
3851            int dimregidx = 0;
3852            for (uint i = 0; i < Dimensions; i++) {
3853                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3854                    // the velocity dimension must be handled after the other dimensions
3855                    veldim = i;
3856                    velbitpos = bitpos;
3857                } else {
3858                    switch (pDimensionDefinitions[i].split_type) {
3859                        case split_type_normal:
3860                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3861                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3862                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3863                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3864                                }
3865                            } else {
3866                                // gig2: evenly sized zones
3867                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3868                            }
3869                            break;
3870                        case split_type_bit: // the value is already the sought dimension bit number
3871                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3872                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3873                            break;
3874                    }
3875                    dimregidx |= bits << bitpos;
3876                }
3877                bitpos += pDimensionDefinitions[i].bits;
3878            }
3879            dimregidx &= 255;
3880            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3881            if (!dimreg) return -1;
3882            if (veldim != -1) {
3883                // (dimreg is now the dimension region for the lowest velocity)
3884                if (dimreg->VelocityTable) // custom defined zone ranges
3885                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3886                else // normal split type
3887                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3888    
3889                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3890                dimregidx |= (bits & limiter_mask) << velbitpos;
3891                dimregidx &= 255;
3892            }
3893            return dimregidx;
3894        }
3895    
3896      /**      /**
3897       * Returns the appropriate DimensionRegion for the given dimension bit       * Returns the appropriate DimensionRegion for the given dimension bit
3898       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
# Line 2545  namespace { Line 3931  namespace {
3931          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
3932          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3933          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
3934          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
3935          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
3936          Sample* sample = file->GetFirstSample(pProgress);              // use 64 bit wave pool offsets (treating this as large file)
3937          while (sample) {              uint64_t soughtoffset =
3938              if (sample->ulWavePoolOffset == soughtoffset &&                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
3939                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
3940              sample = file->GetNextSample();              Sample* sample = file->GetFirstSample(pProgress);
3941                while (sample) {
3942                    if (sample->ullWavePoolOffset == soughtoffset)
3943                        return static_cast<gig::Sample*>(sample);
3944                    sample = file->GetNextSample();
3945                }
3946            } else {
3947                // use extension files and 32 bit wave pool offsets
3948                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3949                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3950                Sample* sample = file->GetFirstSample(pProgress);
3951                while (sample) {
3952                    if (sample->ullWavePoolOffset == soughtoffset &&
3953                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3954                    sample = file->GetNextSample();
3955                }
3956            }
3957            return NULL;
3958        }
3959        
3960        /**
3961         * Make a (semi) deep copy of the Region object given by @a orig
3962         * and assign it to this object.
3963         *
3964         * Note that all sample pointers referenced by @a orig are simply copied as
3965         * memory address. Thus the respective samples are shared, not duplicated!
3966         *
3967         * @param orig - original Region object to be copied from
3968         */
3969        void Region::CopyAssign(const Region* orig) {
3970            CopyAssign(orig, NULL);
3971        }
3972        
3973        /**
3974         * Make a (semi) deep copy of the Region object given by @a orig and
3975         * assign it to this object
3976         *
3977         * @param mSamples - crosslink map between the foreign file's samples and
3978         *                   this file's samples
3979         */
3980        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3981            // handle base classes
3982            DLS::Region::CopyAssign(orig);
3983            
3984            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3985                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3986            }
3987            
3988            // handle own member variables
3989            for (int i = Dimensions - 1; i >= 0; --i) {
3990                DeleteDimension(&pDimensionDefinitions[i]);
3991            }
3992            Layers = 0; // just to be sure
3993            for (int i = 0; i < orig->Dimensions; i++) {
3994                // we need to copy the dim definition here, to avoid the compiler
3995                // complaining about const-ness issue
3996                dimension_def_t def = orig->pDimensionDefinitions[i];
3997                AddDimension(&def);
3998            }
3999            for (int i = 0; i < 256; i++) {
4000                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
4001                    pDimensionRegions[i]->CopyAssign(
4002                        orig->pDimensionRegions[i],
4003                        mSamples
4004                    );
4005                }
4006            }
4007            Layers = orig->Layers;
4008        }
4009    
4010    
4011    // *************** MidiRule ***************
4012    // *
4013    
4014        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
4015            _3ewg->SetPos(36);
4016            Triggers = _3ewg->ReadUint8();
4017            _3ewg->SetPos(40);
4018            ControllerNumber = _3ewg->ReadUint8();
4019            _3ewg->SetPos(46);
4020            for (int i = 0 ; i < Triggers ; i++) {
4021                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
4022                pTriggers[i].Descending = _3ewg->ReadUint8();
4023                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
4024                pTriggers[i].Key = _3ewg->ReadUint8();
4025                pTriggers[i].NoteOff = _3ewg->ReadUint8();
4026                pTriggers[i].Velocity = _3ewg->ReadUint8();
4027                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
4028                _3ewg->ReadUint8();
4029            }
4030        }
4031    
4032        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
4033            ControllerNumber(0),
4034            Triggers(0) {
4035        }
4036    
4037        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
4038            pData[32] = 4;
4039            pData[33] = 16;
4040            pData[36] = Triggers;
4041            pData[40] = ControllerNumber;
4042            for (int i = 0 ; i < Triggers ; i++) {
4043                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
4044                pData[47 + i * 8] = pTriggers[i].Descending;
4045                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
4046                pData[49 + i * 8] = pTriggers[i].Key;
4047                pData[50 + i * 8] = pTriggers[i].NoteOff;
4048                pData[51 + i * 8] = pTriggers[i].Velocity;
4049                pData[52 + i * 8] = pTriggers[i].OverridePedal;
4050            }
4051        }
4052    
4053        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
4054            _3ewg->SetPos(36);
4055            LegatoSamples = _3ewg->ReadUint8(); // always 12
4056            _3ewg->SetPos(40);
4057            BypassUseController = _3ewg->ReadUint8();
4058            BypassKey = _3ewg->ReadUint8();
4059            BypassController = _3ewg->ReadUint8();
4060            ThresholdTime = _3ewg->ReadUint16();
4061            _3ewg->ReadInt16();
4062            ReleaseTime = _3ewg->ReadUint16();
4063            _3ewg->ReadInt16();
4064            KeyRange.low = _3ewg->ReadUint8();
4065            KeyRange.high = _3ewg->ReadUint8();
4066            _3ewg->SetPos(64);
4067            ReleaseTriggerKey = _3ewg->ReadUint8();
4068            AltSustain1Key = _3ewg->ReadUint8();
4069            AltSustain2Key = _3ewg->ReadUint8();
4070        }
4071    
4072        MidiRuleLegato::MidiRuleLegato() :
4073            LegatoSamples(12),
4074            BypassUseController(false),
4075            BypassKey(0),
4076            BypassController(1),
4077            ThresholdTime(20),
4078            ReleaseTime(20),
4079            ReleaseTriggerKey(0),
4080            AltSustain1Key(0),
4081            AltSustain2Key(0)
4082        {
4083            KeyRange.low = KeyRange.high = 0;
4084        }
4085    
4086        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
4087            pData[32] = 0;
4088            pData[33] = 16;
4089            pData[36] = LegatoSamples;
4090            pData[40] = BypassUseController;
4091            pData[41] = BypassKey;
4092            pData[42] = BypassController;
4093            store16(&pData[43], ThresholdTime);
4094            store16(&pData[47], ReleaseTime);
4095            pData[51] = KeyRange.low;
4096            pData[52] = KeyRange.high;
4097            pData[64] = ReleaseTriggerKey;
4098            pData[65] = AltSustain1Key;
4099            pData[66] = AltSustain2Key;
4100        }
4101    
4102        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4103            _3ewg->SetPos(36);
4104            Articulations = _3ewg->ReadUint8();
4105            int flags = _3ewg->ReadUint8();
4106            Polyphonic = flags & 8;
4107            Chained = flags & 4;
4108            Selector = (flags & 2) ? selector_controller :
4109                (flags & 1) ? selector_key_switch : selector_none;
4110            Patterns = _3ewg->ReadUint8();
4111            _3ewg->ReadUint8(); // chosen row
4112            _3ewg->ReadUint8(); // unknown
4113            _3ewg->ReadUint8(); // unknown
4114            _3ewg->ReadUint8(); // unknown
4115            KeySwitchRange.low = _3ewg->ReadUint8();
4116            KeySwitchRange.high = _3ewg->ReadUint8();
4117            Controller = _3ewg->ReadUint8();
4118            PlayRange.low = _3ewg->ReadUint8();
4119            PlayRange.high = _3ewg->ReadUint8();
4120    
4121            int n = std::min(int(Articulations), 32);
4122            for (int i = 0 ; i < n ; i++) {
4123                _3ewg->ReadString(pArticulations[i], 32);
4124            }
4125            _3ewg->SetPos(1072);
4126            n = std::min(int(Patterns), 32);
4127            for (int i = 0 ; i < n ; i++) {
4128                _3ewg->ReadString(pPatterns[i].Name, 16);
4129                pPatterns[i].Size = _3ewg->ReadUint8();
4130                _3ewg->Read(&pPatterns[i][0], 1, 32);
4131            }
4132        }
4133    
4134        MidiRuleAlternator::MidiRuleAlternator() :
4135            Articulations(0),
4136            Patterns(0),
4137            Selector(selector_none),
4138            Controller(0),
4139            Polyphonic(false),
4140            Chained(false)
4141        {
4142            PlayRange.low = PlayRange.high = 0;
4143            KeySwitchRange.low = KeySwitchRange.high = 0;
4144        }
4145    
4146        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4147            pData[32] = 3;
4148            pData[33] = 16;
4149            pData[36] = Articulations;
4150            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4151                (Selector == selector_controller ? 2 :
4152                 (Selector == selector_key_switch ? 1 : 0));
4153            pData[38] = Patterns;
4154    
4155            pData[43] = KeySwitchRange.low;
4156            pData[44] = KeySwitchRange.high;
4157            pData[45] = Controller;
4158            pData[46] = PlayRange.low;
4159            pData[47] = PlayRange.high;
4160    
4161            char* str = reinterpret_cast<char*>(pData);
4162            int pos = 48;
4163            int n = std::min(int(Articulations), 32);
4164            for (int i = 0 ; i < n ; i++, pos += 32) {
4165                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4166            }
4167    
4168            pos = 1072;
4169            n = std::min(int(Patterns), 32);
4170            for (int i = 0 ; i < n ; i++, pos += 49) {
4171                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4172                pData[pos + 16] = pPatterns[i].Size;
4173                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4174            }
4175        }
4176    
4177    // *************** Script ***************
4178    // *
4179    
4180        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4181            pGroup = group;
4182            pChunk = ckScri;
4183            if (ckScri) { // object is loaded from file ...
4184                // read header
4185                uint32_t headerSize = ckScri->ReadUint32();
4186                Compression = (Compression_t) ckScri->ReadUint32();
4187                Encoding    = (Encoding_t) ckScri->ReadUint32();
4188                Language    = (Language_t) ckScri->ReadUint32();
4189                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4190                crc         = ckScri->ReadUint32();
4191                uint32_t nameSize = ckScri->ReadUint32();
4192                Name.resize(nameSize, ' ');
4193                for (int i = 0; i < nameSize; ++i)
4194                    Name[i] = ckScri->ReadUint8();
4195                // to handle potential future extensions of the header
4196                ckScri->SetPos(sizeof(int32_t) + headerSize);
4197                // read actual script data
4198                uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();
4199                data.resize(scriptSize);
4200                for (int i = 0; i < scriptSize; ++i)
4201                    data[i] = ckScri->ReadUint8();
4202            } else { // this is a new script object, so just initialize it as such ...
4203                Compression = COMPRESSION_NONE;
4204                Encoding = ENCODING_ASCII;
4205                Language = LANGUAGE_NKSP;
4206                Bypass   = false;
4207                crc      = 0;
4208                Name     = "Unnamed Script";
4209            }
4210        }
4211    
4212        Script::~Script() {
4213        }
4214    
4215        /**
4216         * Returns the current script (i.e. as source code) in text format.
4217         */
4218        String Script::GetScriptAsText() {
4219            String s;
4220            s.resize(data.size(), ' ');
4221            memcpy(&s[0], &data[0], data.size());
4222            return s;
4223        }
4224    
4225        /**
4226         * Replaces the current script with the new script source code text given
4227         * by @a text.
4228         *
4229         * @param text - new script source code
4230         */
4231        void Script::SetScriptAsText(const String& text) {
4232            data.resize(text.size());
4233            memcpy(&data[0], &text[0], text.size());
4234        }
4235    
4236        /**
4237         * Apply this script to the respective RIFF chunks. You have to call
4238         * File::Save() to make changes persistent.
4239         *
4240         * Usually there is absolutely no need to call this method explicitly.
4241         * It will be called automatically when File::Save() was called.
4242         *
4243         * @param pProgress - callback function for progress notification
4244         */
4245        void Script::UpdateChunks(progress_t* pProgress) {
4246            // recalculate CRC32 check sum
4247            __resetCRC(crc);
4248            __calculateCRC(&data[0], data.size(), crc);
4249            __encodeCRC(crc);
4250            // make sure chunk exists and has the required size
4251            const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size();
4252            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4253            else pChunk->Resize(chunkSize);
4254            // fill the chunk data to be written to disk
4255            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4256            int pos = 0;
4257            store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size
4258            pos += sizeof(int32_t);
4259            store32(&pData[pos], Compression);
4260            pos += sizeof(int32_t);
4261            store32(&pData[pos], Encoding);
4262            pos += sizeof(int32_t);
4263            store32(&pData[pos], Language);
4264            pos += sizeof(int32_t);
4265            store32(&pData[pos], Bypass ? 1 : 0);
4266            pos += sizeof(int32_t);
4267            store32(&pData[pos], crc);
4268            pos += sizeof(int32_t);
4269            store32(&pData[pos], Name.size());
4270            pos += sizeof(int32_t);
4271            for (int i = 0; i < Name.size(); ++i, ++pos)
4272                pData[pos] = Name[i];
4273            for (int i = 0; i < data.size(); ++i, ++pos)
4274                pData[pos] = data[i];
4275        }
4276    
4277        /**
4278         * Move this script from its current ScriptGroup to another ScriptGroup
4279         * given by @a pGroup.
4280         *
4281         * @param pGroup - script's new group
4282         */
4283        void Script::SetGroup(ScriptGroup* pGroup) {
4284            if (this->pGroup == pGroup) return;
4285            if (pChunk)
4286                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4287            this->pGroup = pGroup;
4288        }
4289    
4290        /**
4291         * Returns the script group this script currently belongs to. Each script
4292         * is a member of exactly one ScriptGroup.
4293         *
4294         * @returns current script group
4295         */
4296        ScriptGroup* Script::GetGroup() const {
4297            return pGroup;
4298        }
4299    
4300        void Script::RemoveAllScriptReferences() {
4301            File* pFile = pGroup->pFile;
4302            for (int i = 0; pFile->GetInstrument(i); ++i) {
4303                Instrument* instr = pFile->GetInstrument(i);
4304                instr->RemoveScript(this);
4305            }
4306        }
4307    
4308    // *************** ScriptGroup ***************
4309    // *
4310    
4311        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4312            pFile = file;
4313            pList = lstRTIS;
4314            pScripts = NULL;
4315            if (lstRTIS) {
4316                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4317                ::LoadString(ckName, Name);
4318            } else {
4319                Name = "Default Group";
4320            }
4321        }
4322    
4323        ScriptGroup::~ScriptGroup() {
4324            if (pScripts) {
4325                std::list<Script*>::iterator iter = pScripts->begin();
4326                std::list<Script*>::iterator end  = pScripts->end();
4327                while (iter != end) {
4328                    delete *iter;
4329                    ++iter;
4330                }
4331                delete pScripts;
4332          }          }
4333        }
4334    
4335        /**
4336         * Apply this script group to the respective RIFF chunks. You have to call
4337         * File::Save() to make changes persistent.
4338         *
4339         * Usually there is absolutely no need to call this method explicitly.
4340         * It will be called automatically when File::Save() was called.
4341         *
4342         * @param pProgress - callback function for progress notification
4343         */
4344        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4345            if (pScripts) {
4346                if (!pList)
4347                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4348    
4349                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4350                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4351    
4352                for (std::list<Script*>::iterator it = pScripts->begin();
4353                     it != pScripts->end(); ++it)
4354                {
4355                    (*it)->UpdateChunks(pProgress);
4356                }
4357            }
4358        }
4359    
4360        /** @brief Get instrument script.
4361         *
4362         * Returns the real-time instrument script with the given index.
4363         *
4364         * @param index - number of the sought script (0..n)
4365         * @returns sought script or NULL if there's no such script
4366         */
4367        Script* ScriptGroup::GetScript(uint index) {
4368            if (!pScripts) LoadScripts();
4369            std::list<Script*>::iterator it = pScripts->begin();
4370            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4371                if (i == index) return *it;
4372          return NULL;          return NULL;
4373      }      }
4374    
4375        /** @brief Add new instrument script.
4376         *
4377         * Adds a new real-time instrument script to the file. The script is not
4378         * actually used / executed unless it is referenced by an instrument to be
4379         * used. This is similar to samples, which you can add to a file, without
4380         * an instrument necessarily actually using it.
4381         *
4382         * You have to call Save() to make this persistent to the file.
4383         *
4384         * @return new empty script object
4385         */
4386        Script* ScriptGroup::AddScript() {
4387            if (!pScripts) LoadScripts();
4388            Script* pScript = new Script(this, NULL);
4389            pScripts->push_back(pScript);
4390            return pScript;
4391        }
4392    
4393        /** @brief Delete an instrument script.
4394         *
4395         * This will delete the given real-time instrument script. References of
4396         * instruments that are using that script will be removed accordingly.
4397         *
4398         * You have to call Save() to make this persistent to the file.
4399         *
4400         * @param pScript - script to delete
4401         * @throws gig::Exception if given script could not be found
4402         */
4403        void ScriptGroup::DeleteScript(Script* pScript) {
4404            if (!pScripts) LoadScripts();
4405            std::list<Script*>::iterator iter =
4406                find(pScripts->begin(), pScripts->end(), pScript);
4407            if (iter == pScripts->end())
4408                throw gig::Exception("Could not delete script, could not find given script");
4409            pScripts->erase(iter);
4410            pScript->RemoveAllScriptReferences();
4411            if (pScript->pChunk)
4412                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4413            delete pScript;
4414        }
4415    
4416        void ScriptGroup::LoadScripts() {
4417            if (pScripts) return;
4418            pScripts = new std::list<Script*>;
4419            if (!pList) return;
4420    
4421            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4422                 ck = pList->GetNextSubChunk())
4423            {
4424                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4425                    pScripts->push_back(new Script(this, ck));
4426                }
4427            }
4428        }
4429    
4430  // *************** Instrument ***************  // *************** Instrument ***************
4431  // *  // *
4432    
4433      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) {
4434          pInfo->UseFixedLengthStrings = true;          static const DLS::Info::string_length_t fixedStringLengths[] = {
4435                { CHUNK_ID_INAM, 64 },
4436                { CHUNK_ID_ISFT, 12 },
4437                { 0, 0 }
4438            };
4439            pInfo->SetFixedStringLengths(fixedStringLengths);
4440    
4441          // Initialization          // Initialization
4442          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4443            EffectSend = 0;
4444            Attenuation = 0;
4445            FineTune = 0;
4446            PitchbendRange = 0;
4447            PianoReleaseMode = false;
4448            DimensionKeyRange.low = 0;
4449            DimensionKeyRange.high = 0;
4450            pMidiRules = new MidiRule*[3];
4451            pMidiRules[0] = NULL;
4452            pScriptRefs = NULL;
4453    
4454          // Loading          // Loading
4455          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2580  namespace { Line 4464  namespace {
4464                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
4465                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
4466                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
4467    
4468                    if (_3ewg->GetSize() > 32) {
4469                        // read MIDI rules
4470                        int i = 0;
4471                        _3ewg->SetPos(32);
4472                        uint8_t id1 = _3ewg->ReadUint8();
4473                        uint8_t id2 = _3ewg->ReadUint8();
4474    
4475                        if (id2 == 16) {
4476                            if (id1 == 4) {
4477                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4478                            } else if (id1 == 0) {
4479                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4480                            } else if (id1 == 3) {
4481                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4482                            } else {
4483                                pMidiRules[i++] = new MidiRuleUnknown;
4484                            }
4485                        }
4486                        else if (id1 != 0 || id2 != 0) {
4487                            pMidiRules[i++] = new MidiRuleUnknown;
4488                        }
4489                        //TODO: all the other types of rules
4490    
4491                        pMidiRules[i] = NULL;
4492                    }
4493                }
4494            }
4495    
4496            if (pFile->GetAutoLoad()) {
4497                if (!pRegions) pRegions = new RegionList;
4498                RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4499                if (lrgn) {
4500                    RIFF::List* rgn = lrgn->GetFirstSubList();
4501                    while (rgn) {
4502                        if (rgn->GetListType() == LIST_TYPE_RGN) {
4503                            __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4504                            pRegions->push_back(new Region(this, rgn));
4505                        }
4506                        rgn = lrgn->GetNextSubList();
4507                    }
4508                    // Creating Region Key Table for fast lookup
4509                    UpdateRegionKeyTable();
4510              }              }
4511          }          }
4512    
4513          if (!pRegions) pRegions = new RegionList;          // own gig format extensions
4514          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4515          if (lrgn) {          if (lst3LS) {
4516              RIFF::List* rgn = lrgn->GetFirstSubList();              RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4517              while (rgn) {              if (ckSCSL) {
4518                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  int headerSize = ckSCSL->ReadUint32();
4519                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                  int slotCount  = ckSCSL->ReadUint32();
4520                      pRegions->push_back(new Region(this, rgn));                  if (slotCount) {
4521                        int slotSize  = ckSCSL->ReadUint32();
4522                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4523                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4524                        for (int i = 0; i < slotCount; ++i) {
4525                            _ScriptPooolEntry e;
4526                            e.fileOffset = ckSCSL->ReadUint32();
4527                            e.bypass     = ckSCSL->ReadUint32() & 1;
4528                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4529                            scriptPoolFileOffsets.push_back(e);
4530                        }
4531                  }                  }
                 rgn = lrgn->GetNextSubList();  
4532              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
4533          }          }
4534    
4535          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4536      }      }
4537    
4538      void Instrument::UpdateRegionKeyTable() {      void Instrument::UpdateRegionKeyTable() {
4539            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
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) {
# Line 2613  namespace { Line 4548  namespace {
4548      }      }
4549    
4550      Instrument::~Instrument() {      Instrument::~Instrument() {
4551            for (int i = 0 ; pMidiRules[i] ; i++) {
4552                delete pMidiRules[i];
4553            }
4554            delete[] pMidiRules;
4555            if (pScriptRefs) delete pScriptRefs;
4556      }      }
4557    
4558      /**      /**
# Line 2622  namespace { Line 4562  namespace {
4562       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
4563       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
4564       *       *
4565         * @param pProgress - callback function for progress notification
4566       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
4567       */       */
4568      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
4569          // first update base classes' chunks          // first update base classes' chunks
4570          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks(pProgress);
4571    
4572          // update Regions' chunks          // update Regions' chunks
4573          {          {
4574              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
4575              RegionList::iterator end  = pRegions->end();              RegionList::iterator end  = pRegions->end();
4576              for (; iter != end; ++iter)              for (; iter != end; ++iter)
4577                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
4578          }          }
4579    
4580          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
# Line 2641  namespace { Line 4582  namespace {
4582          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
4583          // make sure '3ewg' RIFF chunk exists          // make sure '3ewg' RIFF chunk exists
4584          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4585          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);          if (!_3ewg)  {
4586                File* pFile = (File*) GetParent();
4587    
4588                // 3ewg is bigger in gig3, as it includes the iMIDI rules
4589                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
4590                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
4591                memset(_3ewg->LoadChunkData(), 0, size);
4592            }
4593          // update '3ewg' RIFF chunk          // update '3ewg' RIFF chunk
4594          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
4595          memcpy(&pData[0], &EffectSend, 2);          store16(&pData[0], EffectSend);
4596          memcpy(&pData[2], &Attenuation, 4);          store32(&pData[2], Attenuation);
4597          memcpy(&pData[6], &FineTune, 2);          store16(&pData[6], FineTune);
4598          memcpy(&pData[8], &PitchbendRange, 2);          store16(&pData[8], PitchbendRange);
4599          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |          const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
4600                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
4601          memcpy(&pData[10], &dimkeystart, 1);          pData[10] = dimkeystart;
4602          memcpy(&pData[11], &DimensionKeyRange.high, 1);          pData[11] = DimensionKeyRange.high;
4603    
4604            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4605                pData[32] = 0;
4606                pData[33] = 0;
4607            } else {
4608                for (int i = 0 ; pMidiRules[i] ; i++) {
4609                    pMidiRules[i]->UpdateChunks(pData);
4610                }
4611            }
4612    
4613            // own gig format extensions
4614           if (ScriptSlotCount()) {
4615               // make sure we have converted the original loaded script file
4616               // offsets into valid Script object pointers
4617               LoadScripts();
4618    
4619               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4620               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4621               const int slotCount = pScriptRefs->size();
4622               const int headerSize = 3 * sizeof(uint32_t);
4623               const int slotSize  = 2 * sizeof(uint32_t);
4624               const int totalChunkSize = headerSize + slotCount * slotSize;
4625               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4626               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4627               else ckSCSL->Resize(totalChunkSize);
4628               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4629               int pos = 0;
4630               store32(&pData[pos], headerSize);
4631               pos += sizeof(uint32_t);
4632               store32(&pData[pos], slotCount);
4633               pos += sizeof(uint32_t);
4634               store32(&pData[pos], slotSize);
4635               pos += sizeof(uint32_t);
4636               for (int i = 0; i < slotCount; ++i) {
4637                   // arbitrary value, the actual file offset will be updated in
4638                   // UpdateScriptFileOffsets() after the file has been resized
4639                   int bogusFileOffset = 0;
4640                   store32(&pData[pos], bogusFileOffset);
4641                   pos += sizeof(uint32_t);
4642                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4643                   pos += sizeof(uint32_t);
4644               }
4645           } else {
4646               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4647               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4648               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4649           }
4650        }
4651    
4652        void Instrument::UpdateScriptFileOffsets() {
4653           // own gig format extensions
4654           if (pScriptRefs && pScriptRefs->size() > 0) {
4655               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4656               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4657               const int slotCount = pScriptRefs->size();
4658               const int headerSize = 3 * sizeof(uint32_t);
4659               ckSCSL->SetPos(headerSize);
4660               for (int i = 0; i < slotCount; ++i) {
4661                   uint32_t fileOffset =
4662                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4663                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4664                        CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize());
4665                   ckSCSL->WriteUint32(&fileOffset);
4666                   // jump over flags entry (containing the bypass flag)
4667                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4668               }
4669           }        
4670      }      }
4671    
4672      /**      /**
# Line 2662  namespace { Line 4677  namespace {
4677       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
4678       */       */
4679      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
4680          if (!pRegions || !pRegions->size() || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
4681          return RegionKeyTable[Key];          return RegionKeyTable[Key];
4682    
4683          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
# Line 2720  namespace { Line 4735  namespace {
4735          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4736      }      }
4737    
4738        /**
4739         * Move this instrument at the position before @arg dst.
4740         *
4741         * This method can be used to reorder the sequence of instruments in a
4742         * .gig file. This might be helpful especially on large .gig files which
4743         * contain a large number of instruments within the same .gig file. So
4744         * grouping such instruments to similar ones, can help to keep track of them
4745         * when working with such complex .gig files.
4746         *
4747         * When calling this method, this instrument will be removed from in its
4748         * current position in the instruments list and moved to the requested
4749         * target position provided by @param dst. You may also pass NULL as
4750         * argument to this method, in that case this intrument will be moved to the
4751         * very end of the .gig file's instrument list.
4752         *
4753         * You have to call Save() to make the order change persistent to the .gig
4754         * file.
4755         *
4756         * Currently this method is limited to moving the instrument within the same
4757         * .gig file. Trying to move it to another .gig file by calling this method
4758         * will throw an exception.
4759         *
4760         * @param dst - destination instrument at which this instrument will be
4761         *              moved to, or pass NULL for moving to end of list
4762         * @throw gig::Exception if this instrument and target instrument are not
4763         *                       part of the same file
4764         */
4765        void Instrument::MoveTo(Instrument* dst) {
4766            if (dst && GetParent() != dst->GetParent())
4767                throw Exception(
4768                    "gig::Instrument::MoveTo() can only be used for moving within "
4769                    "the same gig file."
4770                );
4771    
4772            File* pFile = (File*) GetParent();
4773    
4774            // move this instrument within the instrument list
4775            {
4776                File::InstrumentList& list = *pFile->pInstruments;
4777    
4778                File::InstrumentList::iterator itFrom =
4779                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4780    
4781                File::InstrumentList::iterator itTo =
4782                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4783    
4784                list.splice(itTo, list, itFrom);
4785            }
4786    
4787            // move the instrument's actual list RIFF chunk appropriately
4788            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4789            lstCkInstruments->MoveSubChunk(
4790                this->pCkInstrument,
4791                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4792            );
4793        }
4794    
4795        /**
4796         * Returns a MIDI rule of the instrument.
4797         *
4798         * The list of MIDI rules, at least in gig v3, always contains at
4799         * most two rules. The second rule can only be the DEF filter
4800         * (which currently isn't supported by libgig).
4801         *
4802         * @param i - MIDI rule number
4803         * @returns   pointer address to MIDI rule number i or NULL if there is none
4804         */
4805        MidiRule* Instrument::GetMidiRule(int i) {
4806            return pMidiRules[i];
4807        }
4808    
4809        /**
4810         * Adds the "controller trigger" MIDI rule to the instrument.
4811         *
4812         * @returns the new MIDI rule
4813         */
4814        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4815            delete pMidiRules[0];
4816            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4817            pMidiRules[0] = r;
4818            pMidiRules[1] = 0;
4819            return r;
4820        }
4821    
4822        /**
4823         * Adds the legato MIDI rule to the instrument.
4824         *
4825         * @returns the new MIDI rule
4826         */
4827        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4828            delete pMidiRules[0];
4829            MidiRuleLegato* r = new MidiRuleLegato;
4830            pMidiRules[0] = r;
4831            pMidiRules[1] = 0;
4832            return r;
4833        }
4834    
4835        /**
4836         * Adds the alternator MIDI rule to the instrument.
4837         *
4838         * @returns the new MIDI rule
4839         */
4840        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4841            delete pMidiRules[0];
4842            MidiRuleAlternator* r = new MidiRuleAlternator;
4843            pMidiRules[0] = r;
4844            pMidiRules[1] = 0;
4845            return r;
4846        }
4847    
4848        /**
4849         * Deletes a MIDI rule from the instrument.
4850         *
4851         * @param i - MIDI rule number
4852         */
4853        void Instrument::DeleteMidiRule(int i) {
4854            delete pMidiRules[i];
4855            pMidiRules[i] = 0;
4856        }
4857    
4858        void Instrument::LoadScripts() {
4859            if (pScriptRefs) return;
4860            pScriptRefs = new std::vector<_ScriptPooolRef>;
4861            if (scriptPoolFileOffsets.empty()) return;
4862            File* pFile = (File*) GetParent();
4863            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4864                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4865                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4866                    ScriptGroup* group = pFile->GetScriptGroup(i);
4867                    for (uint s = 0; group->GetScript(s); ++s) {
4868                        Script* script = group->GetScript(s);
4869                        if (script->pChunk) {
4870                            uint32_t offset = script->pChunk->GetFilePos() -
4871                                              script->pChunk->GetPos() -
4872                                              CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize());
4873                            if (offset == soughtOffset)
4874                            {
4875                                _ScriptPooolRef ref;
4876                                ref.script = script;
4877                                ref.bypass = scriptPoolFileOffsets[k].bypass;
4878                                pScriptRefs->push_back(ref);
4879                                break;
4880                            }
4881                        }
4882                    }
4883                }
4884            }
4885            // we don't need that anymore
4886            scriptPoolFileOffsets.clear();
4887        }
4888    
4889        /** @brief Get instrument script (gig format extension).
4890         *
4891         * Returns the real-time instrument script of instrument script slot
4892         * @a index.
4893         *
4894         * @note This is an own format extension which did not exist i.e. in the
4895         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4896         * gigedit.
4897         *
4898         * @param index - instrument script slot index
4899         * @returns script or NULL if index is out of bounds
4900         */
4901        Script* Instrument::GetScriptOfSlot(uint index) {
4902            LoadScripts();
4903            if (index >= pScriptRefs->size()) return NULL;
4904            return pScriptRefs->at(index).script;
4905        }
4906    
4907        /** @brief Add new instrument script slot (gig format extension).
4908         *
4909         * Add the given real-time instrument script reference to this instrument,
4910         * which shall be executed by the sampler for for this instrument. The
4911         * script will be added to the end of the script list of this instrument.
4912         * The positions of the scripts in the Instrument's Script list are
4913         * relevant, because they define in which order they shall be executed by
4914         * the sampler. For this reason it is also legal to add the same script
4915         * twice to an instrument, for example you might have a script called
4916         * "MyFilter" which performs an event filter task, and you might have
4917         * another script called "MyNoteTrigger" which triggers new notes, then you
4918         * might for example have the following list of scripts on the instrument:
4919         *
4920         * 1. Script "MyFilter"
4921         * 2. Script "MyNoteTrigger"
4922         * 3. Script "MyFilter"
4923         *
4924         * Which would make sense, because the 2nd script launched new events, which
4925         * you might need to filter as well.
4926         *
4927         * There are two ways to disable / "bypass" scripts. You can either disable
4928         * a script locally for the respective script slot on an instrument (i.e. by
4929         * passing @c false to the 2nd argument of this method, or by calling
4930         * SetScriptBypassed()). Or you can disable a script globally for all slots
4931         * and all instruments by setting Script::Bypass.
4932         *
4933         * @note This is an own format extension which did not exist i.e. in the
4934         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4935         * gigedit.
4936         *
4937         * @param pScript - script that shall be executed for this instrument
4938         * @param bypass  - if enabled, the sampler shall skip executing this
4939         *                  script (in the respective list position)
4940         * @see SetScriptBypassed()
4941         */
4942        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4943            LoadScripts();
4944            _ScriptPooolRef ref = { pScript, bypass };
4945            pScriptRefs->push_back(ref);
4946        }
4947    
4948        /** @brief Flip two script slots with each other (gig format extension).
4949         *
4950         * Swaps the position of the two given scripts in the Instrument's Script
4951         * list. The positions of the scripts in the Instrument's Script list are
4952         * relevant, because they define in which order they shall be executed by
4953         * the sampler.
4954         *
4955         * @note This is an own format extension which did not exist i.e. in the
4956         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4957         * gigedit.
4958         *
4959         * @param index1 - index of the first script slot to swap
4960         * @param index2 - index of the second script slot to swap
4961         */
4962        void Instrument::SwapScriptSlots(uint index1, uint index2) {
4963            LoadScripts();
4964            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4965                return;
4966            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4967            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4968            (*pScriptRefs)[index2] = tmp;
4969        }
4970    
4971        /** @brief Remove script slot.
4972         *
4973         * Removes the script slot with the given slot index.
4974         *
4975         * @param index - index of script slot to remove
4976         */
4977        void Instrument::RemoveScriptSlot(uint index) {
4978            LoadScripts();
4979            if (index >= pScriptRefs->size()) return;
4980            pScriptRefs->erase( pScriptRefs->begin() + index );
4981        }
4982    
4983        /** @brief Remove reference to given Script (gig format extension).
4984         *
4985         * This will remove all script slots on the instrument which are referencing
4986         * the given script.
4987         *
4988         * @note This is an own format extension which did not exist i.e. in the
4989         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4990         * gigedit.
4991         *
4992         * @param pScript - script reference to remove from this instrument
4993         * @see RemoveScriptSlot()
4994         */
4995        void Instrument::RemoveScript(Script* pScript) {
4996            LoadScripts();
4997            for (int i = pScriptRefs->size() - 1; i >= 0; --i) {
4998                if ((*pScriptRefs)[i].script == pScript) {
4999                    pScriptRefs->erase( pScriptRefs->begin() + i );
5000                }
5001            }
5002        }
5003    
5004        /** @brief Instrument's amount of script slots.
5005         *
5006         * This method returns the amount of script slots this instrument currently
5007         * uses.
5008         *
5009         * A script slot is a reference of a real-time instrument script to be
5010         * executed by the sampler. The scripts will be executed by the sampler in
5011         * sequence of the slots. One (same) script may be referenced multiple
5012         * times in different slots.
5013         *
5014         * @note This is an own format extension which did not exist i.e. in the
5015         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5016         * gigedit.
5017         */
5018        uint Instrument::ScriptSlotCount() const {
5019            return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
5020        }
5021    
5022        /** @brief Whether script execution shall be skipped.
5023         *
5024         * Defines locally for the Script reference slot in the Instrument's Script
5025         * list, whether the script shall be skipped by the sampler regarding
5026         * execution.
5027         *
5028         * It is also possible to ignore exeuction of the script globally, for all
5029         * slots and for all instruments by setting Script::Bypass.
5030         *
5031         * @note This is an own format extension which did not exist i.e. in the
5032         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5033         * gigedit.
5034         *
5035         * @param index - index of the script slot on this instrument
5036         * @see Script::Bypass
5037         */
5038        bool Instrument::IsScriptSlotBypassed(uint index) {
5039            if (index >= ScriptSlotCount()) return false;
5040            return pScriptRefs ? pScriptRefs->at(index).bypass
5041                               : scriptPoolFileOffsets.at(index).bypass;
5042            
5043        }
5044    
5045        /** @brief Defines whether execution shall be skipped.
5046         *
5047         * You can call this method to define locally whether or whether not the
5048         * given script slot shall be executed by the sampler.
5049         *
5050         * @note This is an own format extension which did not exist i.e. in the
5051         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5052         * gigedit.
5053         *
5054         * @param index - script slot index on this instrument
5055         * @param bBypass - if true, the script slot will be skipped by the sampler
5056         * @see Script::Bypass
5057         */
5058        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
5059            if (index >= ScriptSlotCount()) return;
5060            if (pScriptRefs)
5061                pScriptRefs->at(index).bypass = bBypass;
5062            else
5063                scriptPoolFileOffsets.at(index).bypass = bBypass;
5064        }
5065    
5066        /**
5067         * Make a (semi) deep copy of the Instrument object given by @a orig
5068         * and assign it to this object.
5069         *
5070         * Note that all sample pointers referenced by @a orig are simply copied as
5071         * memory address. Thus the respective samples are shared, not duplicated!
5072         *
5073         * @param orig - original Instrument object to be copied from
5074         */
5075        void Instrument::CopyAssign(const Instrument* orig) {
5076            CopyAssign(orig, NULL);
5077        }
5078            
5079        /**
5080         * Make a (semi) deep copy of the Instrument object given by @a orig
5081         * and assign it to this object.
5082         *
5083         * @param orig - original Instrument object to be copied from
5084         * @param mSamples - crosslink map between the foreign file's samples and
5085         *                   this file's samples
5086         */
5087        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
5088            // handle base class
5089            // (without copying DLS region stuff)
5090            DLS::Instrument::CopyAssignCore(orig);
5091            
5092            // handle own member variables
5093            Attenuation = orig->Attenuation;
5094            EffectSend = orig->EffectSend;
5095            FineTune = orig->FineTune;
5096            PitchbendRange = orig->PitchbendRange;
5097            PianoReleaseMode = orig->PianoReleaseMode;
5098            DimensionKeyRange = orig->DimensionKeyRange;
5099            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5100            pScriptRefs = orig->pScriptRefs;
5101            
5102            // free old midi rules
5103            for (int i = 0 ; pMidiRules[i] ; i++) {
5104                delete pMidiRules[i];
5105            }
5106            //TODO: MIDI rule copying
5107            pMidiRules[0] = NULL;
5108            
5109            // delete all old regions
5110            while (Regions) DeleteRegion(GetFirstRegion());
5111            // create new regions and copy them from original
5112            {
5113                RegionList::const_iterator it = orig->pRegions->begin();
5114                for (int i = 0; i < orig->Regions; ++i, ++it) {
5115                    Region* dstRgn = AddRegion();
5116                    //NOTE: Region does semi-deep copy !
5117                    dstRgn->CopyAssign(
5118                        static_cast<gig::Region*>(*it),
5119                        mSamples
5120                    );
5121                }
5122            }
5123    
5124            UpdateRegionKeyTable();
5125        }
5126    
5127    
5128  // *************** Group ***************  // *************** Group ***************
# Line 2738  namespace { Line 5141  namespace {
5141      }      }
5142    
5143      Group::~Group() {      Group::~Group() {
5144            // remove the chunk associated with this group (if any)
5145            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
5146      }      }
5147    
5148      /** @brief Update chunks with current group settings.      /** @brief Update chunks with current group settings.
5149       *       *
5150       * Apply current Group field values to the respective. You have to call       * Apply current Group field values to the respective chunks. You have
5151       * File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
5152         *
5153         * Usually there is absolutely no need to call this method explicitly.
5154         * It will be called automatically when File::Save() was called.
5155         *
5156         * @param pProgress - callback function for progress notification
5157       */       */
5158      void Group::UpdateChunks() {      void Group::UpdateChunks(progress_t* pProgress) {
5159          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
5160          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5161          if (!_3gri) _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);          if (!_3gri) {
5162                _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
5163                pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5164            }
5165          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5166          if (!_3gnl) _3gnl = pFile->pRIFF->AddSubList(LIST_TYPE_3GNL);          if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5167    
5168            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
5169                // v3 has a fixed list of 128 strings, find a free one
5170                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
5171                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
5172                        pNameChunk = ck;
5173                        break;
5174                    }
5175                }
5176            }
5177    
5178          // 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
5179          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
5180      }      }
# Line 2826  namespace { Line 5250  namespace {
5250  // *************** File ***************  // *************** File ***************
5251  // *  // *
5252    
5253        /// Reflects Gigasampler file format version 2.0 (1998-06-28).
5254        const DLS::version_t File::VERSION_2 = {
5255            0, 2, 19980628 & 0xffff, 19980628 >> 16
5256        };
5257    
5258        /// Reflects Gigasampler file format version 3.0 (2003-03-31).
5259        const DLS::version_t File::VERSION_3 = {
5260            0, 3, 20030331 & 0xffff, 20030331 >> 16
5261        };
5262    
5263        static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
5264            { CHUNK_ID_IARL, 256 },
5265            { CHUNK_ID_IART, 128 },
5266            { CHUNK_ID_ICMS, 128 },
5267            { CHUNK_ID_ICMT, 1024 },
5268            { CHUNK_ID_ICOP, 128 },
5269            { CHUNK_ID_ICRD, 128 },
5270            { CHUNK_ID_IENG, 128 },
5271            { CHUNK_ID_IGNR, 128 },
5272            { CHUNK_ID_IKEY, 128 },
5273            { CHUNK_ID_IMED, 128 },
5274            { CHUNK_ID_INAM, 128 },
5275            { CHUNK_ID_IPRD, 128 },
5276            { CHUNK_ID_ISBJ, 128 },
5277            { CHUNK_ID_ISFT, 128 },
5278            { CHUNK_ID_ISRC, 128 },
5279            { CHUNK_ID_ISRF, 128 },
5280            { CHUNK_ID_ITCH, 128 },
5281            { 0, 0 }
5282        };
5283    
5284      File::File() : DLS::File() {      File::File() : DLS::File() {
5285            bAutoLoad = true;
5286            *pVersion = VERSION_3;
5287          pGroups = NULL;          pGroups = NULL;
5288          pInfo->UseFixedLengthStrings = true;          pScriptGroups = NULL;
5289            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5290            pInfo->ArchivalLocation = String(256, ' ');
5291    
5292            // add some mandatory chunks to get the file chunks in right
5293            // order (INFO chunk will be moved to first position later)
5294            pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
5295            pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
5296            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
5297    
5298            GenerateDLSID();
5299      }      }
5300    
5301      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5302            bAutoLoad = true;
5303          pGroups = NULL;          pGroups = NULL;
5304          pInfo->UseFixedLengthStrings = true;          pScriptGroups = NULL;
5305            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5306      }      }
5307    
5308      File::~File() {      File::~File() {
# Line 2846  namespace { Line 5315  namespace {
5315              }              }
5316              delete pGroups;              delete pGroups;
5317          }          }
5318            if (pScriptGroups) {
5319                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5320                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5321                while (iter != end) {
5322                    delete *iter;
5323                    ++iter;
5324                }
5325                delete pScriptGroups;
5326            }
5327      }      }
5328    
5329      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 2860  namespace { Line 5338  namespace {
5338          SamplesIterator++;          SamplesIterator++;
5339          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5340      }      }
5341        
5342        /**
5343         * Returns Sample object of @a index.
5344         *
5345         * @returns sample object or NULL if index is out of bounds
5346         */
5347        Sample* File::GetSample(uint index) {
5348            if (!pSamples) LoadSamples();
5349            if (!pSamples) return NULL;
5350            DLS::File::SampleList::iterator it = pSamples->begin();
5351            for (int i = 0; i < index; ++i) {
5352                ++it;
5353                if (it == pSamples->end()) return NULL;
5354            }
5355            if (it == pSamples->end()) return NULL;
5356            return static_cast<gig::Sample*>( *it );
5357        }
5358    
5359      /** @brief Add a new sample.      /** @brief Add a new sample.
5360       *       *
# Line 2875  namespace { Line 5370  namespace {
5370         // create new Sample object and its respective 'wave' list chunk         // create new Sample object and its respective 'wave' list chunk
5371         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
5372         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*/);
5373    
5374           // add mandatory chunks to get the chunks in right order
5375           wave->AddSubChunk(CHUNK_ID_FMT, 16);
5376           wave->AddSubList(LIST_TYPE_INFO);
5377    
5378         pSamples->push_back(pSample);         pSamples->push_back(pSample);
5379         return pSample;         return pSample;
5380      }      }
5381    
5382      /** @brief Delete a sample.      /** @brief Delete a sample.
5383       *       *
5384       * 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
5385       * to call Save() to make this persistent to the file.       * references to this sample from Regions and DimensionRegions will be
5386         * removed. You have to call Save() to make this persistent to the file.
5387       *       *
5388       * @param pSample - sample to delete       * @param pSample - sample to delete
5389       * @throws gig::Exception if given sample could not be found       * @throws gig::Exception if given sample could not be found
# Line 2891  namespace { Line 5392  namespace {
5392          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");
5393          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
5394          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");
5395            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
5396          pSamples->erase(iter);          pSamples->erase(iter);
5397          delete pSample;          delete pSample;
5398    
5399            SampleList::iterator tmp = SamplesIterator;
5400            // remove all references to the sample
5401            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5402                 instrument = GetNextInstrument()) {
5403                for (Region* region = instrument->GetFirstRegion() ; region ;
5404                     region = instrument->GetNextRegion()) {
5405    
5406                    if (region->GetSample() == pSample) region->SetSample(NULL);
5407    
5408                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
5409                        gig::DimensionRegion *d = region->pDimensionRegions[i];
5410                        if (d->pSample == pSample) d->pSample = NULL;
5411                    }
5412                }
5413            }
5414            SamplesIterator = tmp; // restore iterator
5415      }      }
5416    
5417      void File::LoadSamples() {      void File::LoadSamples() {
# Line 2902  namespace { Line 5421  namespace {
5421      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
5422          // Groups must be loaded before samples, because samples will try          // Groups must be loaded before samples, because samples will try
5423          // to resolve the group they belong to          // to resolve the group they belong to
5424          LoadGroups();          if (!pGroups) LoadGroups();
5425    
5426          if (!pSamples) pSamples = new SampleList;          if (!pSamples) pSamples = new SampleList;
5427    
# Line 2913  namespace { Line 5432  namespace {
5432          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5433    
5434          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5435            // (only for old gig files < 2 GB)
5436          int lastFileNo = 0;          int lastFileNo = 0;
5437          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5438              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5439                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5440                }
5441          }          }
5442          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5443          int nameLen = name.length();          int nameLen = name.length();
# Line 2925  namespace { Line 5447  namespace {
5447          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5448              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5449              if (wvpl) {              if (wvpl) {
5450                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5451                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5452                  while (wave) {                  while (wave) {
5453                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 2933  namespace { Line 5455  namespace {
5455                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5456                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5457    
5458                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5459                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5460    
5461                          iSampleIndex++;                          iSampleIndex++;
5462                      }                      }
# Line 2983  namespace { Line 5505  namespace {
5505              progress_t subprogress;              progress_t subprogress;
5506              __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
5507              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
5508              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
5509                    GetFirstSample(&subprogress); // now force all samples to be loaded
5510              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
5511    
5512              // instrument loading subtask              // instrument loading subtask
# Line 3016  namespace { Line 5539  namespace {
5539         __ensureMandatoryChunksExist();         __ensureMandatoryChunksExist();
5540         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5541         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
5542    
5543           // add mandatory chunks to get the chunks in right order
5544           lstInstr->AddSubList(LIST_TYPE_INFO);
5545           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
5546    
5547         Instrument* pInstrument = new Instrument(this, lstInstr);         Instrument* pInstrument = new Instrument(this, lstInstr);
5548           pInstrument->GenerateDLSID();
5549    
5550           lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
5551    
5552           // this string is needed for the gig to be loadable in GSt:
5553           pInstrument->pInfo->Software = "Endless Wave";
5554    
5555         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
5556         return pInstrument;         return pInstrument;
5557      }      }
5558        
5559        /** @brief Add a duplicate of an existing instrument.
5560         *
5561         * Duplicates the instrument definition given by @a orig and adds it
5562         * to this file. This allows in an instrument editor application to
5563         * easily create variations of an instrument, which will be stored in
5564         * the same .gig file, sharing i.e. the same samples.
5565         *
5566         * Note that all sample pointers referenced by @a orig are simply copied as
5567         * memory address. Thus the respective samples are shared, not duplicated!
5568         *
5569         * You have to call Save() to make this persistent to the file.
5570         *
5571         * @param orig - original instrument to be copied
5572         * @returns duplicated copy of the given instrument
5573         */
5574        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
5575            Instrument* instr = AddInstrument();
5576            instr->CopyAssign(orig);
5577            return instr;
5578        }
5579        
5580        /** @brief Add content of another existing file.
5581         *
5582         * Duplicates the samples, groups and instruments of the original file
5583         * given by @a pFile and adds them to @c this File. In case @c this File is
5584         * a new one that you haven't saved before, then you have to call
5585         * SetFileName() before calling AddContentOf(), because this method will
5586         * automatically save this file during operation, which is required for
5587         * writing the sample waveform data by disk streaming.
5588         *
5589         * @param pFile - original file whose's content shall be copied from
5590         */
5591        void File::AddContentOf(File* pFile) {
5592            static int iCallCount = -1;
5593            iCallCount++;
5594            std::map<Group*,Group*> mGroups;
5595            std::map<Sample*,Sample*> mSamples;
5596            
5597            // clone sample groups
5598            for (int i = 0; pFile->GetGroup(i); ++i) {
5599                Group* g = AddGroup();
5600                g->Name =
5601                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5602                mGroups[pFile->GetGroup(i)] = g;
5603            }
5604            
5605            // clone samples (not waveform data here yet)
5606            for (int i = 0; pFile->GetSample(i); ++i) {
5607                Sample* s = AddSample();
5608                s->CopyAssignMeta(pFile->GetSample(i));
5609                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5610                mSamples[pFile->GetSample(i)] = s;
5611            }
5612            
5613            //BUG: For some reason this method only works with this additional
5614            //     Save() call in between here.
5615            //
5616            // Important: The correct one of the 2 Save() methods has to be called
5617            // here, depending on whether the file is completely new or has been
5618            // saved to disk already, otherwise it will result in data corruption.
5619            if (pRIFF->IsNew())
5620                Save(GetFileName());
5621            else
5622                Save();
5623            
5624            // clone instruments
5625            // (passing the crosslink table here for the cloned samples)
5626            for (int i = 0; pFile->GetInstrument(i); ++i) {
5627                Instrument* instr = AddInstrument();
5628                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5629            }
5630            
5631            // Mandatory: file needs to be saved to disk at this point, so this
5632            // file has the correct size and data layout for writing the samples'
5633            // waveform data to disk.
5634            Save();
5635            
5636            // clone samples' waveform data
5637            // (using direct read & write disk streaming)
5638            for (int i = 0; pFile->GetSample(i); ++i) {
5639                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5640            }
5641        }
5642    
5643      /** @brief Delete an instrument.      /** @brief Delete an instrument.
5644       *       *
# Line 3027  namespace { Line 5646  namespace {
5646       * have to call Save() to make this persistent to the file.       * have to call Save() to make this persistent to the file.
5647       *       *
5648       * @param pInstrument - instrument to delete       * @param pInstrument - instrument to delete
5649       * @throws gig::Excption if given instrument could not be found       * @throws gig::Exception if given instrument could not be found
5650       */       */
5651      void File::DeleteInstrument(Instrument* pInstrument) {      void File::DeleteInstrument(Instrument* pInstrument) {
5652          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 3067  namespace { Line 5686  namespace {
5686          }          }
5687      }      }
5688    
5689        /// Updates the 3crc chunk with the checksum of a sample. The
5690        /// update is done directly to disk, as this method is called
5691        /// after File::Save()
5692        void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
5693            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5694            if (!_3crc) return;
5695    
5696            // get the index of the sample
5697            int iWaveIndex = GetWaveTableIndexOf(pSample);
5698            if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
5699    
5700            // write the CRC-32 checksum to disk
5701            _3crc->SetPos(iWaveIndex * 8);
5702            uint32_t one = 1;
5703            _3crc->WriteUint32(&one); // always 1
5704            _3crc->WriteUint32(&crc);
5705        }
5706    
5707        uint32_t File::GetSampleChecksum(Sample* pSample) {
5708            // get the index of the sample
5709            int iWaveIndex = GetWaveTableIndexOf(pSample);
5710            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5711    
5712            return GetSampleChecksumByIndex(iWaveIndex);
5713        }
5714    
5715        uint32_t File::GetSampleChecksumByIndex(int index) {
5716            if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5717    
5718            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5719            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5720            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5721            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5722    
5723            // read the CRC-32 checksum directly from disk
5724            size_t pos = index * 8;
5725            if (pos + 8 > _3crc->GetNewSize())
5726                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5727    
5728            uint32_t one = load32(&pData[pos]); // always 1
5729            if (one != 1)
5730                throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5731    
5732            return load32(&pData[pos+4]);
5733        }
5734    
5735        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5736            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5737            File::SampleList::iterator iter = pSamples->begin();
5738            File::SampleList::iterator end  = pSamples->end();
5739            for (int index = 0; iter != end; ++iter, ++index)
5740                if (*iter == pSample)
5741                    return index;
5742            return -1;
5743        }
5744    
5745        /**
5746         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5747         * the CRC32 check sums of all samples' raw wave data.
5748         *
5749         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5750         */
5751        bool File::VerifySampleChecksumTable() {
5752            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5753            if (!_3crc) return false;
5754            if (_3crc->GetNewSize() <= 0) return false;
5755            if (_3crc->GetNewSize() % 8) return false;
5756            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5757            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5758    
5759            const int n = _3crc->GetNewSize() / 8;
5760    
5761            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5762            if (!pData) return false;
5763    
5764            for (int i = 0; i < n; ++i) {
5765                uint32_t one = pData[i*2];
5766                if (one != 1) return false;
5767            }
5768    
5769            return true;
5770        }
5771    
5772        /**
5773         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5774         * file's checksum table with those new checksums. This might usually
5775         * just be necessary if the checksum table was damaged.
5776         *
5777         * @e IMPORTANT: The current implementation of this method only works
5778         * with files that have not been modified since it was loaded, because
5779         * it expects that no externally caused file structure changes are
5780         * required!
5781         *
5782         * Due to the expectation above, this method is currently protected
5783         * and actually only used by the command line tool "gigdump" yet.
5784         *
5785         * @returns true if Save() is required to be called after this call,
5786         *          false if no further action is required
5787         */
5788        bool File::RebuildSampleChecksumTable() {
5789            // make sure sample chunks were scanned
5790            if (!pSamples) GetFirstSample();
5791    
5792            bool bRequiresSave = false;
5793    
5794            // make sure "3CRC" chunk exists with required size
5795            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5796            if (!_3crc) {
5797                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5798                // the order of einf and 3crc is not the same in v2 and v3
5799                RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5800                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5801                bRequiresSave = true;
5802            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5803                _3crc->Resize(pSamples->size() * 8);
5804                bRequiresSave = true;
5805            }
5806    
5807            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5808                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5809                {
5810                    File::SampleList::iterator iter = pSamples->begin();
5811                    File::SampleList::iterator end  = pSamples->end();
5812                    for (; iter != end; ++iter) {
5813                        gig::Sample* pSample = (gig::Sample*) *iter;
5814                        int index = GetWaveTableIndexOf(pSample);
5815                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5816                        pData[index*2]   = 1; // always 1
5817                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5818                    }
5819                }
5820            } else { // no file structure changes necessary, so directly write to disk and we are done ...
5821                // make sure file is in write mode
5822                pRIFF->SetMode(RIFF::stream_mode_read_write);
5823                {
5824                    File::SampleList::iterator iter = pSamples->begin();
5825                    File::SampleList::iterator end  = pSamples->end();
5826                    for (; iter != end; ++iter) {
5827                        gig::Sample* pSample = (gig::Sample*) *iter;
5828                        int index = GetWaveTableIndexOf(pSample);
5829                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5830                        pSample->crc  = pSample->CalculateWaveDataChecksum();
5831                        SetSampleChecksum(pSample, pSample->crc);
5832                    }
5833                }
5834            }
5835    
5836            return bRequiresSave;
5837        }
5838    
5839      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
5840          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5841          // there must always be at least one group          // there must always be at least one group
# Line 3096  namespace { Line 5865  namespace {
5865          return NULL;          return NULL;
5866      }      }
5867    
5868        /**
5869         * Returns the group with the given group name.
5870         *
5871         * Note: group names don't have to be unique in the gig format! So there
5872         * can be multiple groups with the same name. This method will simply
5873         * return the first group found with the given name.
5874         *
5875         * @param name - name of the sought group
5876         * @returns sought group or NULL if there's no group with that name
5877         */
5878        Group* File::GetGroup(String name) {
5879            if (!pGroups) LoadGroups();
5880            GroupsIterator = pGroups->begin();
5881            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
5882                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
5883            return NULL;
5884        }
5885    
5886      Group* File::AddGroup() {      Group* File::AddGroup() {
5887          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5888          // there must always be at least one group          // there must always be at least one group
# Line 3105  namespace { Line 5892  namespace {
5892          return pGroup;          return pGroup;
5893      }      }
5894    
5895        /** @brief Delete a group and its samples.
5896         *
5897         * This will delete the given Group object and all the samples that
5898         * belong to this group from the gig file. You have to call Save() to
5899         * make this persistent to the file.
5900         *
5901         * @param pGroup - group to delete
5902         * @throws gig::Exception if given group could not be found
5903         */
5904      void File::DeleteGroup(Group* pGroup) {      void File::DeleteGroup(Group* pGroup) {
5905          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5906          std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);          std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5907          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");
5908          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!");
5909            // delete all members of this group
5910            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
5911                DeleteSample(pSample);
5912            }
5913            // now delete this group object
5914            pGroups->erase(iter);
5915            delete pGroup;
5916        }
5917    
5918        /** @brief Delete a group.
5919         *
5920         * This will delete the given Group object from the gig file. All the
5921         * samples that belong to this group will not be deleted, but instead
5922         * be moved to another group. You have to call Save() to make this
5923         * persistent to the file.
5924         *
5925         * @param pGroup - group to delete
5926         * @throws gig::Exception if given group could not be found
5927         */
5928        void File::DeleteGroupOnly(Group* pGroup) {
5929            if (!pGroups) LoadGroups();
5930            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5931            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5932            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5933          // move all members of this group to another group          // move all members of this group to another group
5934          pGroup->MoveAll();          pGroup->MoveAll();
5935          pGroups->erase(iter);          pGroups->erase(iter);
# Line 3126  namespace { Line 5946  namespace {
5946                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
5947                  while (ck) {                  while (ck) {
5948                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {
5949                            if (pVersion && pVersion->major == 3 &&
5950                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
5951    
5952                          pGroups->push_back(new Group(this, ck));                          pGroups->push_back(new Group(this, ck));
5953                      }                      }
5954                      ck = lst3gnl->GetNextSubChunk();                      ck = lst3gnl->GetNextSubChunk();
# Line 3140  namespace { Line 5963  namespace {
5963          }          }
5964      }      }
5965    
5966        /** @brief Get instrument script group (by index).
5967         *
5968         * Returns the real-time instrument script group with the given index.
5969         *
5970         * @param index - number of the sought group (0..n)
5971         * @returns sought script group or NULL if there's no such group
5972         */
5973        ScriptGroup* File::GetScriptGroup(uint index) {
5974            if (!pScriptGroups) LoadScriptGroups();
5975            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5976            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5977                if (i == index) return *it;
5978            return NULL;
5979        }
5980    
5981        /** @brief Get instrument script group (by name).
5982         *
5983         * Returns the first real-time instrument script group found with the given
5984         * group name. Note that group names may not necessarily be unique.
5985         *
5986         * @param name - name of the sought script group
5987         * @returns sought script group or NULL if there's no such group
5988         */
5989        ScriptGroup* File::GetScriptGroup(const String& name) {
5990            if (!pScriptGroups) LoadScriptGroups();
5991            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5992            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5993                if ((*it)->Name == name) return *it;
5994            return NULL;
5995        }
5996    
5997        /** @brief Add new instrument script group.
5998         *
5999         * Adds a new, empty real-time instrument script group to the file.
6000         *
6001         * You have to call Save() to make this persistent to the file.
6002         *
6003         * @return new empty script group
6004         */
6005        ScriptGroup* File::AddScriptGroup() {
6006            if (!pScriptGroups) LoadScriptGroups();
6007            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
6008            pScriptGroups->push_back(pScriptGroup);
6009            return pScriptGroup;
6010        }
6011    
6012        /** @brief Delete an instrument script group.
6013         *
6014         * This will delete the given real-time instrument script group and all its
6015         * instrument scripts it contains. References inside instruments that are
6016         * using the deleted scripts will be removed from the respective instruments
6017         * accordingly.
6018         *
6019         * You have to call Save() to make this persistent to the file.
6020         *
6021         * @param pScriptGroup - script group to delete
6022         * @throws gig::Exception if given script group could not be found
6023         */
6024        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
6025            if (!pScriptGroups) LoadScriptGroups();
6026            std::list<ScriptGroup*>::iterator iter =
6027                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
6028            if (iter == pScriptGroups->end())
6029                throw gig::Exception("Could not delete script group, could not find given script group");
6030            pScriptGroups->erase(iter);
6031            for (int i = 0; pScriptGroup->GetScript(i); ++i)
6032                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
6033            if (pScriptGroup->pList)
6034                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
6035            delete pScriptGroup;
6036        }
6037    
6038        void File::LoadScriptGroups() {
6039            if (pScriptGroups) return;
6040            pScriptGroups = new std::list<ScriptGroup*>;
6041            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
6042            if (lstLS) {
6043                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
6044                     lst = lstLS->GetNextSubList())
6045                {
6046                    if (lst->GetListType() == LIST_TYPE_RTIS) {
6047                        pScriptGroups->push_back(new ScriptGroup(this, lst));
6048                    }
6049                }
6050            }
6051        }
6052    
6053        /**
6054         * Apply all the gig file's current instruments, samples, groups and settings
6055         * to the respective RIFF chunks. You have to call Save() to make changes
6056         * persistent.
6057         *
6058         * Usually there is absolutely no need to call this method explicitly.
6059         * It will be called automatically when File::Save() was called.
6060         *
6061         * @param pProgress - callback function for progress notification
6062         * @throws Exception - on errors
6063         */
6064        void File::UpdateChunks(progress_t* pProgress) {
6065            bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6066    
6067            // update own gig format extension chunks
6068            // (not part of the GigaStudio 4 format)
6069            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6070            if (!lst3LS) {
6071                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6072            }
6073            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6074            // location of <3LS > is irrelevant, however it should be located
6075            // before  the actual wave data
6076            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6077            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6078    
6079            // This must be performed before writing the chunks for instruments,
6080            // because the instruments' script slots will write the file offsets
6081            // of the respective instrument script chunk as reference.
6082            if (pScriptGroups) {
6083                // Update instrument script (group) chunks.
6084                for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6085                     it != pScriptGroups->end(); ++it)
6086                {
6087                    (*it)->UpdateChunks(pProgress);
6088                }
6089            }
6090    
6091            // in case no libgig custom format data was added, then remove the
6092            // custom "3LS " chunk again
6093            if (!lst3LS->CountSubChunks()) {
6094                pRIFF->DeleteSubChunk(lst3LS);
6095                lst3LS = NULL;
6096            }
6097    
6098            // first update base class's chunks
6099            DLS::File::UpdateChunks(pProgress);
6100    
6101            if (newFile) {
6102                // INFO was added by Resource::UpdateChunks - make sure it
6103                // is placed first in file
6104                RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
6105                RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
6106                if (first != info) {
6107                    pRIFF->MoveSubChunk(info, first);
6108                }
6109            }
6110    
6111            // update group's chunks
6112            if (pGroups) {
6113                // make sure '3gri' and '3gnl' list chunks exist
6114                // (before updating the Group chunks)
6115                RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
6116                if (!_3gri) {
6117                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
6118                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
6119                }
6120                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
6121                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
6122    
6123                // v3: make sure the file has 128 3gnm chunks
6124                // (before updating the Group chunks)
6125                if (pVersion && pVersion->major == 3) {
6126                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
6127                    for (int i = 0 ; i < 128 ; i++) {
6128                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
6129                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
6130                    }
6131                }
6132    
6133                std::list<Group*>::iterator iter = pGroups->begin();
6134                std::list<Group*>::iterator end  = pGroups->end();
6135                for (; iter != end; ++iter) {
6136                    (*iter)->UpdateChunks(pProgress);
6137                }
6138            }
6139    
6140            // update einf chunk
6141    
6142            // The einf chunk contains statistics about the gig file, such
6143            // as the number of regions and samples used by each
6144            // instrument. It is divided in equally sized parts, where the
6145            // first part contains information about the whole gig file,
6146            // and the rest of the parts map to each instrument in the
6147            // file.
6148            //
6149            // At the end of each part there is a bit map of each sample
6150            // in the file, where a set bit means that the sample is used
6151            // by the file/instrument.
6152            //
6153            // Note that there are several fields with unknown use. These
6154            // are set to zero.
6155    
6156            int sublen = pSamples->size() / 8 + 49;
6157            int einfSize = (Instruments + 1) * sublen;
6158    
6159            RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
6160            if (einf) {
6161                if (einf->GetSize() != einfSize) {
6162                    einf->Resize(einfSize);
6163                    memset(einf->LoadChunkData(), 0, einfSize);
6164                }
6165            } else if (newFile) {
6166                einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
6167            }
6168            if (einf) {
6169                uint8_t* pData = (uint8_t*) einf->LoadChunkData();
6170    
6171                std::map<gig::Sample*,int> sampleMap;
6172                int sampleIdx = 0;
6173                for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
6174                    sampleMap[pSample] = sampleIdx++;
6175                }
6176    
6177                int totnbusedsamples = 0;
6178                int totnbusedchannels = 0;
6179                int totnbregions = 0;
6180                int totnbdimregions = 0;
6181                int totnbloops = 0;
6182                int instrumentIdx = 0;
6183    
6184                memset(&pData[48], 0, sublen - 48);
6185    
6186                for (Instrument* instrument = GetFirstInstrument() ; instrument ;
6187                     instrument = GetNextInstrument()) {
6188                    int nbusedsamples = 0;
6189                    int nbusedchannels = 0;
6190                    int nbdimregions = 0;
6191                    int nbloops = 0;
6192    
6193                    memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
6194    
6195                    for (Region* region = instrument->GetFirstRegion() ; region ;
6196                         region = instrument->GetNextRegion()) {
6197                        for (int i = 0 ; i < region->DimensionRegions ; i++) {
6198                            gig::DimensionRegion *d = region->pDimensionRegions[i];
6199                            if (d->pSample) {
6200                                int sampleIdx = sampleMap[d->pSample];
6201                                int byte = 48 + sampleIdx / 8;
6202                                int bit = 1 << (sampleIdx & 7);
6203                                if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
6204                                    pData[(instrumentIdx + 1) * sublen + byte] |= bit;
6205                                    nbusedsamples++;
6206                                    nbusedchannels += d->pSample->Channels;
6207    
6208                                    if ((pData[byte] & bit) == 0) {
6209                                        pData[byte] |= bit;
6210                                        totnbusedsamples++;
6211                                        totnbusedchannels += d->pSample->Channels;
6212                                    }
6213                                }
6214                            }
6215                            if (d->SampleLoops) nbloops++;
6216                        }
6217                        nbdimregions += region->DimensionRegions;
6218                    }
6219                    // first 4 bytes unknown - sometimes 0, sometimes length of einf part
6220                    // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
6221                    store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
6222                    store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
6223                    store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
6224                    store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
6225                    store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
6226                    store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6227                    // next 8 bytes unknown
6228                    store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6229                    store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
6230                    // next 4 bytes unknown
6231    
6232                    totnbregions += instrument->Regions;
6233                    totnbdimregions += nbdimregions;
6234                    totnbloops += nbloops;
6235                    instrumentIdx++;
6236                }
6237                // first 4 bytes unknown - sometimes 0, sometimes length of einf part
6238                // store32(&pData[0], sublen);
6239                store32(&pData[4], totnbusedchannels);
6240                store32(&pData[8], totnbusedsamples);
6241                store32(&pData[12], Instruments);
6242                store32(&pData[16], totnbregions);
6243                store32(&pData[20], totnbdimregions);
6244                store32(&pData[24], totnbloops);
6245                // next 8 bytes unknown
6246                // next 4 bytes unknown, not always 0
6247                store32(&pData[40], pSamples->size());
6248                // next 4 bytes unknown
6249            }
6250    
6251            // update 3crc chunk
6252    
6253            // The 3crc chunk contains CRC-32 checksums for the
6254            // samples. When saving a gig file to disk, we first update the 3CRC
6255            // chunk here (in RAM) with the old crc values which we read from the
6256            // 3CRC chunk when we opened the file (available with gig::Sample::crc
6257            // member variable). This step is required, because samples might have
6258            // been deleted by the user since the file was opened, which in turn
6259            // changes the order of the (i.e. old) checksums within the 3crc chunk.
6260            // If a sample was conciously modified by the user (that is if
6261            // Sample::Write() was called later on) then Sample::Write() will just
6262            // update the respective individual checksum(s) directly on disk and
6263            // leaves all other sample checksums untouched.
6264    
6265            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6266            if (_3crc) {
6267                _3crc->Resize(pSamples->size() * 8);
6268            } else /*if (newFile)*/ {
6269                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
6270                // the order of einf and 3crc is not the same in v2 and v3
6271                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6272            }
6273            { // must be performed in RAM here ...
6274                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6275                if (pData) {
6276                    File::SampleList::iterator iter = pSamples->begin();
6277                    File::SampleList::iterator end  = pSamples->end();
6278                    for (int index = 0; iter != end; ++iter, ++index) {
6279                        gig::Sample* pSample = (gig::Sample*) *iter;
6280                        pData[index*2]   = 1; // always 1
6281                        pData[index*2+1] = pSample->crc;
6282                    }
6283                }
6284            }
6285        }
6286        
6287        void File::UpdateFileOffsets() {
6288            DLS::File::UpdateFileOffsets();
6289    
6290            for (Instrument* instrument = GetFirstInstrument(); instrument;
6291                 instrument = GetNextInstrument())
6292            {
6293                instrument->UpdateScriptFileOffsets();
6294            }
6295        }
6296    
6297        /**
6298         * Enable / disable automatic loading. By default this properyt is
6299         * enabled and all informations are loaded automatically. However
6300         * loading all Regions, DimensionRegions and especially samples might
6301         * take a long time for large .gig files, and sometimes one might only
6302         * be interested in retrieving very superficial informations like the
6303         * amount of instruments and their names. In this case one might disable
6304         * automatic loading to avoid very slow response times.
6305         *
6306         * @e CAUTION: by disabling this property many pointers (i.e. sample
6307         * references) and informations will have invalid or even undefined
6308         * data! This feature is currently only intended for retrieving very
6309         * superficial informations in a very fast way. Don't use it to retrieve
6310         * details like synthesis informations or even to modify .gig files!
6311         */
6312        void File::SetAutoLoad(bool b) {
6313            bAutoLoad = b;
6314        }
6315    
6316        /**
6317         * Returns whether automatic loading is enabled.
6318         * @see SetAutoLoad()
6319         */
6320        bool File::GetAutoLoad() {
6321            return bAutoLoad;
6322        }
6323    
6324    
6325    
6326  // *************** Exception ***************  // *************** Exception ***************

Legend:
Removed from v.1070  
changed lines
  Added in v.2989

  ViewVC Help
Powered by ViewVC