/[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 1218 by persson, Fri Jun 1 19:19:28 2007 UTC revision 2639 by schoenebeck, Mon Jun 16 13:22:50 2014 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-2014 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  /// Initial size of the sample buffer which is used for decompression of  /// Initial size of the sample buffer which is used for decompression of
34  /// compressed sample wave streams - this value should always be bigger than  /// compressed sample wave streams - this value should always be bigger than
# Line 255  namespace { Line 257  namespace {
257    
258    
259    
260    // *************** Internal CRC-32 (Cyclic Redundancy Check) functions  ***************
261    // *
262    
263        static uint32_t* __initCRCTable() {
264            static uint32_t res[256];
265    
266            for (int i = 0 ; i < 256 ; i++) {
267                uint32_t c = i;
268                for (int j = 0 ; j < 8 ; j++) {
269                    c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
270                }
271                res[i] = c;
272            }
273            return res;
274        }
275    
276        static const uint32_t* __CRCTable = __initCRCTable();
277    
278        /**
279         * Initialize a CRC variable.
280         *
281         * @param crc - variable to be initialized
282         */
283        inline static void __resetCRC(uint32_t& crc) {
284            crc = 0xffffffff;
285        }
286    
287        /**
288         * Used to calculate checksums of the sample data in a gig file. The
289         * checksums are stored in the 3crc chunk of the gig file and
290         * automatically updated when a sample is written with Sample::Write().
291         *
292         * One should call __resetCRC() to initialize the CRC variable to be
293         * used before calling this function the first time.
294         *
295         * After initializing the CRC variable one can call this function
296         * arbitrary times, i.e. to split the overall CRC calculation into
297         * steps.
298         *
299         * Once the whole data was processed by __calculateCRC(), one should
300         * call __encodeCRC() to get the final CRC result.
301         *
302         * @param buf     - pointer to data the CRC shall be calculated of
303         * @param bufSize - size of the data to be processed
304         * @param crc     - variable the CRC sum shall be stored to
305         */
306        static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
307            for (int i = 0 ; i < bufSize ; i++) {
308                crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
309            }
310        }
311    
312        /**
313         * Returns the final CRC result.
314         *
315         * @param crc - variable previously passed to __calculateCRC()
316         */
317        inline static uint32_t __encodeCRC(const uint32_t& crc) {
318            return crc ^ 0xffffffff;
319        }
320    
321    
322    
323  // *************** Other Internal functions  ***************  // *************** Other Internal functions  ***************
324  // *  // *
325    
# Line 278  namespace { Line 343  namespace {
343    
344    
345    
 // *************** CRC ***************  
 // *  
   
     const uint32_t* CRC::table(initTable());  
   
     uint32_t* CRC::initTable() {  
         uint32_t* res = new uint32_t[256];  
   
         for (int i = 0 ; i < 256 ; i++) {  
             uint32_t c = i;  
             for (int j = 0 ; j < 8 ; j++) {  
                 c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;  
             }  
             res[i] = c;  
         }  
         return res;  
     }  
   
   
   
346  // *************** Sample ***************  // *************** Sample ***************
347  // *  // *
348    
# Line 323  namespace { Line 368  namespace {
368       *                         is located, 0 otherwise       *                         is located, 0 otherwise
369       */       */
370      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, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
371          static const DLS::Info::FixedStringLength fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
372              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
373              { 0, 0 }              { 0, 0 }
374          };          };
375          pInfo->FixedStringLengths = fixedStringLengths;          pInfo->SetFixedStringLengths(fixedStringLengths);
376          Instances++;          Instances++;
377          FileNo = fileNo;          FileNo = fileNo;
378    
379            __resetCRC(crc);
380    
381          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
382          if (pCk3gix) {          if (pCk3gix) {
383              uint16_t iSampleGroup = pCk3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
# Line 408  namespace { Line 455  namespace {
455      }      }
456    
457      /**      /**
458         * Make a (semi) deep copy of the Sample object given by @a orig (without
459         * the actual waveform data) and assign it to this object.
460         *
461         * Discussion: copying .gig samples is a bit tricky. It requires three
462         * steps:
463         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
464         *    its new sample waveform data size.
465         * 2. Saving the file (done by File::Save()) so that it gains correct size
466         *    and layout for writing the actual wave form data directly to disc
467         *    in next step.
468         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
469         *
470         * @param orig - original Sample object to be copied from
471         */
472        void Sample::CopyAssignMeta(const Sample* orig) {
473            // handle base classes
474            DLS::Sample::CopyAssignCore(orig);
475            
476            // handle actual own attributes of this class
477            Manufacturer = orig->Manufacturer;
478            Product = orig->Product;
479            SamplePeriod = orig->SamplePeriod;
480            MIDIUnityNote = orig->MIDIUnityNote;
481            FineTune = orig->FineTune;
482            SMPTEFormat = orig->SMPTEFormat;
483            SMPTEOffset = orig->SMPTEOffset;
484            Loops = orig->Loops;
485            LoopID = orig->LoopID;
486            LoopType = orig->LoopType;
487            LoopStart = orig->LoopStart;
488            LoopEnd = orig->LoopEnd;
489            LoopSize = orig->LoopSize;
490            LoopFraction = orig->LoopFraction;
491            LoopPlayCount = orig->LoopPlayCount;
492            
493            // schedule resizing this sample to the given sample's size
494            Resize(orig->GetSize());
495        }
496    
497        /**
498         * Should be called after CopyAssignMeta() and File::Save() sequence.
499         * Read more about it in the discussion of CopyAssignMeta(). This method
500         * copies the actual waveform data by disk streaming.
501         *
502         * @e CAUTION: this method is currently not thread safe! During this
503         * operation the sample must not be used for other purposes by other
504         * threads!
505         *
506         * @param orig - original Sample object to be copied from
507         */
508        void Sample::CopyAssignWave(const Sample* orig) {
509            const int iReadAtOnce = 32*1024;
510            char* buf = new char[iReadAtOnce * orig->FrameSize];
511            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
512            unsigned long restorePos = pOrig->GetPos();
513            pOrig->SetPos(0);
514            SetPos(0);
515            for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;
516                               n = pOrig->Read(buf, iReadAtOnce))
517            {
518                Write(buf, n);
519            }
520            pOrig->SetPos(restorePos);
521            delete [] buf;
522        }
523    
524        /**
525       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
526       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
527       *       *
# Line 468  namespace { Line 582  namespace {
582          // update '3gix' chunk          // update '3gix' chunk
583          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
584          store16(&pData[0], iSampleGroup);          store16(&pData[0], iSampleGroup);
585    
586            // if the library user toggled the "Compressed" attribute from true to
587            // false, then the EWAV chunk associated with compressed samples needs
588            // to be deleted
589            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
590            if (ewav && !Compressed) {
591                pWaveList->DeleteSubChunk(ewav);
592            }
593      }      }
594    
595      /// 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).
# Line 631  namespace { Line 753  namespace {
753          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
754          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
755          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
756            SetPos(0); // reset read position to begin of sample
757          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
758          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
759          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 668  namespace { Line 791  namespace {
791          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
792          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
793          RAMCache.Size   = 0;          RAMCache.Size   = 0;
794            RAMCache.NullExtensionSize = 0;
795      }      }
796    
797      /** @brief Resize sample.      /** @brief Resize sample.
# Line 760  namespace { Line 884  namespace {
884      /**      /**
885       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
886       */       */
887      unsigned long Sample::GetPos() {      unsigned long Sample::GetPos() const {
888          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
889          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
890      }      }
# Line 862  namespace { Line 986  namespace {
986                                  }                                  }
987    
988                                  // reverse the sample frames for backward playback                                  // reverse the sample frames for backward playback
989                                  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!
990                                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
991                              }                              }
992                          } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
993                          break;                          break;
# Line 1152  namespace { Line 1277  namespace {
1277       *       *
1278       * Note: there is currently no support for writing compressed samples.       * Note: there is currently no support for writing compressed samples.
1279       *       *
1280         * For 16 bit samples, the data in the source buffer should be
1281         * int16_t (using native endianness). For 24 bit, the buffer
1282         * should contain three bytes per sample, little-endian.
1283         *
1284       * @param pBuffer     - source buffer       * @param pBuffer     - source buffer
1285       * @param SampleCount - number of sample points to write       * @param SampleCount - number of sample points to write
1286       * @throws DLS::Exception if current sample size is too small       * @throws DLS::Exception if current sample size is too small
# Line 1164  namespace { Line 1293  namespace {
1293          // if this is the first write in this sample, reset the          // if this is the first write in this sample, reset the
1294          // checksum calculator          // checksum calculator
1295          if (pCkData->GetPos() == 0) {          if (pCkData->GetPos() == 0) {
1296              crc.reset();              __resetCRC(crc);
1297            }
1298            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1299            unsigned long res;
1300            if (BitDepth == 24) {
1301                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1302            } else { // 16 bit
1303                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1304                                    : pCkData->Write(pBuffer, SampleCount, 2);
1305          }          }
1306          unsigned long res = DLS::Sample::Write(pBuffer, SampleCount);          __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
         crc.update((unsigned char *)pBuffer, SampleCount * FrameSize);  
1307    
1308          // if this is the last write, update the checksum chunk in the          // if this is the last write, update the checksum chunk in the
1309          // file          // file
1310          if (pCkData->GetPos() == pCkData->GetSize()) {          if (pCkData->GetPos() == pCkData->GetSize()) {
1311              File* pFile = static_cast<File*>(GetParent());              File* pFile = static_cast<File*>(GetParent());
1312              pFile->SetSampleChecksum(this, crc.getValue());              pFile->SetSampleChecksum(this, __encodeCRC(crc));
1313          }          }
1314          return res;          return res;
1315      }      }
# Line 1251  namespace { Line 1387  namespace {
1387      uint                               DimensionRegion::Instances       = 0;      uint                               DimensionRegion::Instances       = 0;
1388      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1389    
1390      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1391          Instances++;          Instances++;
1392    
1393          pSample = NULL;          pSample = NULL;
1394            pRegion = pParent;
1395    
1396            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1397            else memset(&Crossfade, 0, 4);
1398    
         memcpy(&Crossfade, &SamplerOptions, 4);  
1399          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1400    
1401          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
# Line 1370  namespace { Line 1509  namespace {
1509                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1510              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1511              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1512                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1513              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1514              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1515              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1491  namespace { Line 1630  namespace {
1630              VCFVelocityDynamicRange         = 0x04;              VCFVelocityDynamicRange         = 0x04;
1631              VCFVelocityCurve                = curve_type_linear;              VCFVelocityCurve                = curve_type_linear;
1632              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1633              memset(DimensionUpperLimits, 0, 8);              memset(DimensionUpperLimits, 127, 8);
1634          }          }
1635    
1636          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1637                                                       VelocityResponseDepth,                                                       VelocityResponseDepth,
1638                                                       VelocityResponseCurveScaling);                                                       VelocityResponseCurveScaling);
1639    
1640          curve_type_t curveType = ReleaseVelocityResponseCurve;          pVelocityReleaseTable = GetReleaseVelocityTable(
1641          uint8_t depth = ReleaseVelocityResponseDepth;                                      ReleaseVelocityResponseCurve,
1642                                        ReleaseVelocityResponseDepth
1643                                    );
1644    
1645            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1646                                                          VCFVelocityDynamicRange,
1647                                                          VCFVelocityScale,
1648                                                          VCFCutoffController);
1649    
1650          // this models a strange behaviour or bug in GSt: two of the          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1651          // velocity response curves for release time are not used even          VelocityTable = 0;
1652          // 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);  
1653    
1654          curveType = VCFVelocityCurve;      /*
1655          depth = VCFVelocityDynamicRange;       * Constructs a DimensionRegion by copying all parameters from
1656         * another DimensionRegion
1657         */
1658        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1659            Instances++;
1660            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1661            *this = src; // default memberwise shallow copy of all parameters
1662            pParentList = _3ewl; // restore the chunk pointer
1663    
1664            // deep copy of owned structures
1665            if (src.VelocityTable) {
1666                VelocityTable = new uint8_t[128];
1667                for (int k = 0 ; k < 128 ; k++)
1668                    VelocityTable[k] = src.VelocityTable[k];
1669            }
1670            if (src.pSampleLoops) {
1671                pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1672                for (int k = 0 ; k < src.SampleLoops ; k++)
1673                    pSampleLoops[k] = src.pSampleLoops[k];
1674            }
1675        }
1676        
1677        /**
1678         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1679         * and assign it to this object.
1680         *
1681         * Note that all sample pointers referenced by @a orig are simply copied as
1682         * memory address. Thus the respective samples are shared, not duplicated!
1683         *
1684         * @param orig - original DimensionRegion object to be copied from
1685         */
1686        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1687            CopyAssign(orig, NULL);
1688        }
1689    
1690          // even stranger GSt: two of the velocity response curves for      /**
1691          // filter cutoff are not used, instead another special curve       * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1692          // is chosen. This curve is not used anywhere else.       * and assign it to this object.
1693          if ((curveType == curve_type_nonlinear && depth == 0) ||       *
1694              (curveType == curve_type_special   && depth == 4)) {       * @param orig - original DimensionRegion object to be copied from
1695              curveType = curve_type_special;       * @param mSamples - crosslink map between the foreign file's samples and
1696              depth = 5;       *                   this file's samples
1697         */
1698        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1699            // delete all allocated data first
1700            if (VelocityTable) delete [] VelocityTable;
1701            if (pSampleLoops) delete [] pSampleLoops;
1702            
1703            // backup parent list pointer
1704            RIFF::List* p = pParentList;
1705            
1706            gig::Sample* pOriginalSample = pSample;
1707            gig::Region* pOriginalRegion = pRegion;
1708            
1709            //NOTE: copy code copied from assignment constructor above, see comment there as well
1710            
1711            *this = *orig; // default memberwise shallow copy of all parameters
1712            
1713            // restore members that shall not be altered
1714            pParentList = p; // restore the chunk pointer
1715            pRegion = pOriginalRegion;
1716            
1717            // only take the raw sample reference reference if the
1718            // two DimensionRegion objects are part of the same file
1719            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1720                pSample = pOriginalSample;
1721            }
1722            
1723            if (mSamples && mSamples->count(orig->pSample)) {
1724                pSample = mSamples->find(orig->pSample)->second;
1725            }
1726    
1727            // deep copy of owned structures
1728            if (orig->VelocityTable) {
1729                VelocityTable = new uint8_t[128];
1730                for (int k = 0 ; k < 128 ; k++)
1731                    VelocityTable[k] = orig->VelocityTable[k];
1732            }
1733            if (orig->pSampleLoops) {
1734                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1735                for (int k = 0 ; k < orig->SampleLoops ; k++)
1736                    pSampleLoops[k] = orig->pSampleLoops[k];
1737          }          }
1738          pVelocityCutoffTable = GetVelocityTable(curveType, depth,      }
                                                 VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);  
1739    
1740        /**
1741         * Updates the respective member variable and updates @c SampleAttenuation
1742         * which depends on this value.
1743         */
1744        void DimensionRegion::SetGain(int32_t gain) {
1745            DLS::Sampler::SetGain(gain);
1746          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
         VelocityTable = 0;  
1747      }      }
1748    
1749      /**      /**
# Line 1540  namespace { Line 1757  namespace {
1757          // first update base class's chunk          // first update base class's chunk
1758          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks();
1759    
1760            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1761            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1762            pData[12] = Crossfade.in_start;
1763            pData[13] = Crossfade.in_end;
1764            pData[14] = Crossfade.out_start;
1765            pData[15] = Crossfade.out_end;
1766    
1767          // make sure '3ewa' chunk exists          // make sure '3ewa' chunk exists
1768          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1769          if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);          if (!_3ewa) {
1770          uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();              File* pFile = (File*) GetParent()->GetParent()->GetParent();
1771                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1772                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1773            }
1774            pData = (uint8_t*) _3ewa->LoadChunkData();
1775    
1776          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1777    
# Line 1589  namespace { Line 1817  namespace {
1817          pData[44] = eg1ctl;          pData[44] = eg1ctl;
1818    
1819          const uint8_t eg1ctrloptions =          const uint8_t eg1ctrloptions =
1820              (EG1ControllerInvert) ? 0x01 : 0x00 |              (EG1ControllerInvert ? 0x01 : 0x00) |
1821              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1822              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1823              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
# Line 1599  namespace { Line 1827  namespace {
1827          pData[46] = eg2ctl;          pData[46] = eg2ctl;
1828    
1829          const uint8_t eg2ctrloptions =          const uint8_t eg2ctrloptions =
1830              (EG2ControllerInvert) ? 0x01 : 0x00 |              (EG2ControllerInvert ? 0x01 : 0x00) |
1831              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1832              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1833              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
# Line 1749  namespace { Line 1977  namespace {
1977          }          }
1978    
1979          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1980                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1981          pData[116] = eg3depth;          store16(&pData[116], eg3depth);
1982    
1983          // next 2 bytes unknown          // next 2 bytes unknown
1984    
# Line 1777  namespace { Line 2005  namespace {
2005          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
2006          pData[131] = eg1hold;          pData[131] = eg1hold;
2007    
2008          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */          const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
2009                                    (VCFCutoff & 0x7f);   /* lower 7 bits */                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
2010          pData[132] = vcfcutoff;          pData[132] = vcfcutoff;
2011    
2012          pData[133] = VCFCutoffController;          pData[133] = VCFCutoffController;
2013    
2014          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2015                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
2016          pData[134] = vcfvelscale;          pData[134] = vcfvelscale;
2017    
2018          // next byte unknown          // next byte unknown
2019    
2020          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */          const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2021                                       (VCFResonance & 0x7f); /* lower 7 bits */                                       (VCFResonance & 0x7f); /* lower 7 bits */
2022          pData[136] = vcfresonance;          pData[136] = vcfresonance;
2023    
2024          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2025                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2026          pData[137] = vcfbreakpoint;          pData[137] = vcfbreakpoint;
2027    
2028          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2029                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2030          pData[138] = vcfvelocity;          pData[138] = vcfvelocity;
2031    
# Line 1809  namespace { Line 2037  namespace {
2037          }          }
2038      }      }
2039    
2040        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2041            curve_type_t curveType = releaseVelocityResponseCurve;
2042            uint8_t depth = releaseVelocityResponseDepth;
2043            // this models a strange behaviour or bug in GSt: two of the
2044            // velocity response curves for release time are not used even
2045            // if specified, instead another curve is chosen.
2046            if ((curveType == curve_type_nonlinear && depth == 0) ||
2047                (curveType == curve_type_special   && depth == 4)) {
2048                curveType = curve_type_nonlinear;
2049                depth = 3;
2050            }
2051            return GetVelocityTable(curveType, depth, 0);
2052        }
2053    
2054        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2055                                                        uint8_t vcfVelocityDynamicRange,
2056                                                        uint8_t vcfVelocityScale,
2057                                                        vcf_cutoff_ctrl_t vcfCutoffController)
2058        {
2059            curve_type_t curveType = vcfVelocityCurve;
2060            uint8_t depth = vcfVelocityDynamicRange;
2061            // even stranger GSt: two of the velocity response curves for
2062            // filter cutoff are not used, instead another special curve
2063            // is chosen. This curve is not used anywhere else.
2064            if ((curveType == curve_type_nonlinear && depth == 0) ||
2065                (curveType == curve_type_special   && depth == 4)) {
2066                curveType = curve_type_special;
2067                depth = 5;
2068            }
2069            return GetVelocityTable(curveType, depth,
2070                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2071                                        ? vcfVelocityScale : 0);
2072        }
2073    
2074      // 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
2075      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)
2076      {      {
# Line 1824  namespace { Line 2086  namespace {
2086          return table;          return table;
2087      }      }
2088    
2089        Region* DimensionRegion::GetParent() const {
2090            return pRegion;
2091        }
2092    
2093    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2094    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2095    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2096    //#pragma GCC diagnostic push
2097    //#pragma GCC diagnostic error "-Wswitch"
2098    
2099      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2100          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2101          switch (EncodedController) {          switch (EncodedController) {
# Line 1935  namespace { Line 2207  namespace {
2207                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2208                  break;                  break;
2209    
2210                // format extension (these controllers are so far only supported by
2211                // LinuxSampler & gigedit) they will *NOT* work with
2212                // Gigasampler/GigaStudio !
2213                case _lev_ctrl_CC3_EXT:
2214                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2215                    decodedcontroller.controller_number = 3;
2216                    break;
2217                case _lev_ctrl_CC6_EXT:
2218                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2219                    decodedcontroller.controller_number = 6;
2220                    break;
2221                case _lev_ctrl_CC7_EXT:
2222                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2223                    decodedcontroller.controller_number = 7;
2224                    break;
2225                case _lev_ctrl_CC8_EXT:
2226                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2227                    decodedcontroller.controller_number = 8;
2228                    break;
2229                case _lev_ctrl_CC9_EXT:
2230                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2231                    decodedcontroller.controller_number = 9;
2232                    break;
2233                case _lev_ctrl_CC10_EXT:
2234                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2235                    decodedcontroller.controller_number = 10;
2236                    break;
2237                case _lev_ctrl_CC11_EXT:
2238                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2239                    decodedcontroller.controller_number = 11;
2240                    break;
2241                case _lev_ctrl_CC14_EXT:
2242                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2243                    decodedcontroller.controller_number = 14;
2244                    break;
2245                case _lev_ctrl_CC15_EXT:
2246                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2247                    decodedcontroller.controller_number = 15;
2248                    break;
2249                case _lev_ctrl_CC20_EXT:
2250                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2251                    decodedcontroller.controller_number = 20;
2252                    break;
2253                case _lev_ctrl_CC21_EXT:
2254                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2255                    decodedcontroller.controller_number = 21;
2256                    break;
2257                case _lev_ctrl_CC22_EXT:
2258                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2259                    decodedcontroller.controller_number = 22;
2260                    break;
2261                case _lev_ctrl_CC23_EXT:
2262                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2263                    decodedcontroller.controller_number = 23;
2264                    break;
2265                case _lev_ctrl_CC24_EXT:
2266                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2267                    decodedcontroller.controller_number = 24;
2268                    break;
2269                case _lev_ctrl_CC25_EXT:
2270                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2271                    decodedcontroller.controller_number = 25;
2272                    break;
2273                case _lev_ctrl_CC26_EXT:
2274                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2275                    decodedcontroller.controller_number = 26;
2276                    break;
2277                case _lev_ctrl_CC27_EXT:
2278                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2279                    decodedcontroller.controller_number = 27;
2280                    break;
2281                case _lev_ctrl_CC28_EXT:
2282                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2283                    decodedcontroller.controller_number = 28;
2284                    break;
2285                case _lev_ctrl_CC29_EXT:
2286                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2287                    decodedcontroller.controller_number = 29;
2288                    break;
2289                case _lev_ctrl_CC30_EXT:
2290                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2291                    decodedcontroller.controller_number = 30;
2292                    break;
2293                case _lev_ctrl_CC31_EXT:
2294                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2295                    decodedcontroller.controller_number = 31;
2296                    break;
2297                case _lev_ctrl_CC68_EXT:
2298                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2299                    decodedcontroller.controller_number = 68;
2300                    break;
2301                case _lev_ctrl_CC69_EXT:
2302                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2303                    decodedcontroller.controller_number = 69;
2304                    break;
2305                case _lev_ctrl_CC70_EXT:
2306                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2307                    decodedcontroller.controller_number = 70;
2308                    break;
2309                case _lev_ctrl_CC71_EXT:
2310                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2311                    decodedcontroller.controller_number = 71;
2312                    break;
2313                case _lev_ctrl_CC72_EXT:
2314                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2315                    decodedcontroller.controller_number = 72;
2316                    break;
2317                case _lev_ctrl_CC73_EXT:
2318                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2319                    decodedcontroller.controller_number = 73;
2320                    break;
2321                case _lev_ctrl_CC74_EXT:
2322                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2323                    decodedcontroller.controller_number = 74;
2324                    break;
2325                case _lev_ctrl_CC75_EXT:
2326                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2327                    decodedcontroller.controller_number = 75;
2328                    break;
2329                case _lev_ctrl_CC76_EXT:
2330                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2331                    decodedcontroller.controller_number = 76;
2332                    break;
2333                case _lev_ctrl_CC77_EXT:
2334                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2335                    decodedcontroller.controller_number = 77;
2336                    break;
2337                case _lev_ctrl_CC78_EXT:
2338                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2339                    decodedcontroller.controller_number = 78;
2340                    break;
2341                case _lev_ctrl_CC79_EXT:
2342                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2343                    decodedcontroller.controller_number = 79;
2344                    break;
2345                case _lev_ctrl_CC84_EXT:
2346                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2347                    decodedcontroller.controller_number = 84;
2348                    break;
2349                case _lev_ctrl_CC85_EXT:
2350                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2351                    decodedcontroller.controller_number = 85;
2352                    break;
2353                case _lev_ctrl_CC86_EXT:
2354                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2355                    decodedcontroller.controller_number = 86;
2356                    break;
2357                case _lev_ctrl_CC87_EXT:
2358                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2359                    decodedcontroller.controller_number = 87;
2360                    break;
2361                case _lev_ctrl_CC89_EXT:
2362                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2363                    decodedcontroller.controller_number = 89;
2364                    break;
2365                case _lev_ctrl_CC90_EXT:
2366                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2367                    decodedcontroller.controller_number = 90;
2368                    break;
2369                case _lev_ctrl_CC96_EXT:
2370                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2371                    decodedcontroller.controller_number = 96;
2372                    break;
2373                case _lev_ctrl_CC97_EXT:
2374                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2375                    decodedcontroller.controller_number = 97;
2376                    break;
2377                case _lev_ctrl_CC102_EXT:
2378                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2379                    decodedcontroller.controller_number = 102;
2380                    break;
2381                case _lev_ctrl_CC103_EXT:
2382                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2383                    decodedcontroller.controller_number = 103;
2384                    break;
2385                case _lev_ctrl_CC104_EXT:
2386                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2387                    decodedcontroller.controller_number = 104;
2388                    break;
2389                case _lev_ctrl_CC105_EXT:
2390                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2391                    decodedcontroller.controller_number = 105;
2392                    break;
2393                case _lev_ctrl_CC106_EXT:
2394                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2395                    decodedcontroller.controller_number = 106;
2396                    break;
2397                case _lev_ctrl_CC107_EXT:
2398                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2399                    decodedcontroller.controller_number = 107;
2400                    break;
2401                case _lev_ctrl_CC108_EXT:
2402                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2403                    decodedcontroller.controller_number = 108;
2404                    break;
2405                case _lev_ctrl_CC109_EXT:
2406                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2407                    decodedcontroller.controller_number = 109;
2408                    break;
2409                case _lev_ctrl_CC110_EXT:
2410                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2411                    decodedcontroller.controller_number = 110;
2412                    break;
2413                case _lev_ctrl_CC111_EXT:
2414                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2415                    decodedcontroller.controller_number = 111;
2416                    break;
2417                case _lev_ctrl_CC112_EXT:
2418                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2419                    decodedcontroller.controller_number = 112;
2420                    break;
2421                case _lev_ctrl_CC113_EXT:
2422                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2423                    decodedcontroller.controller_number = 113;
2424                    break;
2425                case _lev_ctrl_CC114_EXT:
2426                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2427                    decodedcontroller.controller_number = 114;
2428                    break;
2429                case _lev_ctrl_CC115_EXT:
2430                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2431                    decodedcontroller.controller_number = 115;
2432                    break;
2433                case _lev_ctrl_CC116_EXT:
2434                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2435                    decodedcontroller.controller_number = 116;
2436                    break;
2437                case _lev_ctrl_CC117_EXT:
2438                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2439                    decodedcontroller.controller_number = 117;
2440                    break;
2441                case _lev_ctrl_CC118_EXT:
2442                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2443                    decodedcontroller.controller_number = 118;
2444                    break;
2445                case _lev_ctrl_CC119_EXT:
2446                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2447                    decodedcontroller.controller_number = 119;
2448                    break;
2449    
2450              // unknown controller type              // unknown controller type
2451              default:              default:
2452                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2453          }          }
2454          return decodedcontroller;          return decodedcontroller;
2455      }      }
2456        
2457    // see above (diagnostic push not supported prior GCC 4.6)
2458    //#pragma GCC diagnostic pop
2459    
2460      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2461          _lev_ctrl_t encodedcontroller;          _lev_ctrl_t encodedcontroller;
# Line 2028  namespace { Line 2543  namespace {
2543                      case 95:                      case 95:
2544                          encodedcontroller = _lev_ctrl_effect5depth;                          encodedcontroller = _lev_ctrl_effect5depth;
2545                          break;                          break;
2546    
2547                        // format extension (these controllers are so far only
2548                        // supported by LinuxSampler & gigedit) they will *NOT*
2549                        // work with Gigasampler/GigaStudio !
2550                        case 3:
2551                            encodedcontroller = _lev_ctrl_CC3_EXT;
2552                            break;
2553                        case 6:
2554                            encodedcontroller = _lev_ctrl_CC6_EXT;
2555                            break;
2556                        case 7:
2557                            encodedcontroller = _lev_ctrl_CC7_EXT;
2558                            break;
2559                        case 8:
2560                            encodedcontroller = _lev_ctrl_CC8_EXT;
2561                            break;
2562                        case 9:
2563                            encodedcontroller = _lev_ctrl_CC9_EXT;
2564                            break;
2565                        case 10:
2566                            encodedcontroller = _lev_ctrl_CC10_EXT;
2567                            break;
2568                        case 11:
2569                            encodedcontroller = _lev_ctrl_CC11_EXT;
2570                            break;
2571                        case 14:
2572                            encodedcontroller = _lev_ctrl_CC14_EXT;
2573                            break;
2574                        case 15:
2575                            encodedcontroller = _lev_ctrl_CC15_EXT;
2576                            break;
2577                        case 20:
2578                            encodedcontroller = _lev_ctrl_CC20_EXT;
2579                            break;
2580                        case 21:
2581                            encodedcontroller = _lev_ctrl_CC21_EXT;
2582                            break;
2583                        case 22:
2584                            encodedcontroller = _lev_ctrl_CC22_EXT;
2585                            break;
2586                        case 23:
2587                            encodedcontroller = _lev_ctrl_CC23_EXT;
2588                            break;
2589                        case 24:
2590                            encodedcontroller = _lev_ctrl_CC24_EXT;
2591                            break;
2592                        case 25:
2593                            encodedcontroller = _lev_ctrl_CC25_EXT;
2594                            break;
2595                        case 26:
2596                            encodedcontroller = _lev_ctrl_CC26_EXT;
2597                            break;
2598                        case 27:
2599                            encodedcontroller = _lev_ctrl_CC27_EXT;
2600                            break;
2601                        case 28:
2602                            encodedcontroller = _lev_ctrl_CC28_EXT;
2603                            break;
2604                        case 29:
2605                            encodedcontroller = _lev_ctrl_CC29_EXT;
2606                            break;
2607                        case 30:
2608                            encodedcontroller = _lev_ctrl_CC30_EXT;
2609                            break;
2610                        case 31:
2611                            encodedcontroller = _lev_ctrl_CC31_EXT;
2612                            break;
2613                        case 68:
2614                            encodedcontroller = _lev_ctrl_CC68_EXT;
2615                            break;
2616                        case 69:
2617                            encodedcontroller = _lev_ctrl_CC69_EXT;
2618                            break;
2619                        case 70:
2620                            encodedcontroller = _lev_ctrl_CC70_EXT;
2621                            break;
2622                        case 71:
2623                            encodedcontroller = _lev_ctrl_CC71_EXT;
2624                            break;
2625                        case 72:
2626                            encodedcontroller = _lev_ctrl_CC72_EXT;
2627                            break;
2628                        case 73:
2629                            encodedcontroller = _lev_ctrl_CC73_EXT;
2630                            break;
2631                        case 74:
2632                            encodedcontroller = _lev_ctrl_CC74_EXT;
2633                            break;
2634                        case 75:
2635                            encodedcontroller = _lev_ctrl_CC75_EXT;
2636                            break;
2637                        case 76:
2638                            encodedcontroller = _lev_ctrl_CC76_EXT;
2639                            break;
2640                        case 77:
2641                            encodedcontroller = _lev_ctrl_CC77_EXT;
2642                            break;
2643                        case 78:
2644                            encodedcontroller = _lev_ctrl_CC78_EXT;
2645                            break;
2646                        case 79:
2647                            encodedcontroller = _lev_ctrl_CC79_EXT;
2648                            break;
2649                        case 84:
2650                            encodedcontroller = _lev_ctrl_CC84_EXT;
2651                            break;
2652                        case 85:
2653                            encodedcontroller = _lev_ctrl_CC85_EXT;
2654                            break;
2655                        case 86:
2656                            encodedcontroller = _lev_ctrl_CC86_EXT;
2657                            break;
2658                        case 87:
2659                            encodedcontroller = _lev_ctrl_CC87_EXT;
2660                            break;
2661                        case 89:
2662                            encodedcontroller = _lev_ctrl_CC89_EXT;
2663                            break;
2664                        case 90:
2665                            encodedcontroller = _lev_ctrl_CC90_EXT;
2666                            break;
2667                        case 96:
2668                            encodedcontroller = _lev_ctrl_CC96_EXT;
2669                            break;
2670                        case 97:
2671                            encodedcontroller = _lev_ctrl_CC97_EXT;
2672                            break;
2673                        case 102:
2674                            encodedcontroller = _lev_ctrl_CC102_EXT;
2675                            break;
2676                        case 103:
2677                            encodedcontroller = _lev_ctrl_CC103_EXT;
2678                            break;
2679                        case 104:
2680                            encodedcontroller = _lev_ctrl_CC104_EXT;
2681                            break;
2682                        case 105:
2683                            encodedcontroller = _lev_ctrl_CC105_EXT;
2684                            break;
2685                        case 106:
2686                            encodedcontroller = _lev_ctrl_CC106_EXT;
2687                            break;
2688                        case 107:
2689                            encodedcontroller = _lev_ctrl_CC107_EXT;
2690                            break;
2691                        case 108:
2692                            encodedcontroller = _lev_ctrl_CC108_EXT;
2693                            break;
2694                        case 109:
2695                            encodedcontroller = _lev_ctrl_CC109_EXT;
2696                            break;
2697                        case 110:
2698                            encodedcontroller = _lev_ctrl_CC110_EXT;
2699                            break;
2700                        case 111:
2701                            encodedcontroller = _lev_ctrl_CC111_EXT;
2702                            break;
2703                        case 112:
2704                            encodedcontroller = _lev_ctrl_CC112_EXT;
2705                            break;
2706                        case 113:
2707                            encodedcontroller = _lev_ctrl_CC113_EXT;
2708                            break;
2709                        case 114:
2710                            encodedcontroller = _lev_ctrl_CC114_EXT;
2711                            break;
2712                        case 115:
2713                            encodedcontroller = _lev_ctrl_CC115_EXT;
2714                            break;
2715                        case 116:
2716                            encodedcontroller = _lev_ctrl_CC116_EXT;
2717                            break;
2718                        case 117:
2719                            encodedcontroller = _lev_ctrl_CC117_EXT;
2720                            break;
2721                        case 118:
2722                            encodedcontroller = _lev_ctrl_CC118_EXT;
2723                            break;
2724                        case 119:
2725                            encodedcontroller = _lev_ctrl_CC119_EXT;
2726                            break;
2727    
2728                      default:                      default:
2729                          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");
2730                  }                  }
# Line 2077  namespace { Line 2774  namespace {
2774          return pVelocityCutoffTable[MIDIKeyVelocity];          return pVelocityCutoffTable[MIDIKeyVelocity];
2775      }      }
2776    
2777        /**
2778         * Updates the respective member variable and the lookup table / cache
2779         * that depends on this value.
2780         */
2781        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2782            pVelocityAttenuationTable =
2783                GetVelocityTable(
2784                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2785                );
2786            VelocityResponseCurve = curve;
2787        }
2788    
2789        /**
2790         * Updates the respective member variable and the lookup table / cache
2791         * that depends on this value.
2792         */
2793        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2794            pVelocityAttenuationTable =
2795                GetVelocityTable(
2796                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2797                );
2798            VelocityResponseDepth = depth;
2799        }
2800    
2801        /**
2802         * Updates the respective member variable and the lookup table / cache
2803         * that depends on this value.
2804         */
2805        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2806            pVelocityAttenuationTable =
2807                GetVelocityTable(
2808                    VelocityResponseCurve, VelocityResponseDepth, scaling
2809                );
2810            VelocityResponseCurveScaling = scaling;
2811        }
2812    
2813        /**
2814         * Updates the respective member variable and the lookup table / cache
2815         * that depends on this value.
2816         */
2817        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2818            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2819            ReleaseVelocityResponseCurve = curve;
2820        }
2821    
2822        /**
2823         * Updates the respective member variable and the lookup table / cache
2824         * that depends on this value.
2825         */
2826        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2827            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2828            ReleaseVelocityResponseDepth = depth;
2829        }
2830    
2831        /**
2832         * Updates the respective member variable and the lookup table / cache
2833         * that depends on this value.
2834         */
2835        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2836            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2837            VCFCutoffController = controller;
2838        }
2839    
2840        /**
2841         * Updates the respective member variable and the lookup table / cache
2842         * that depends on this value.
2843         */
2844        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2845            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2846            VCFVelocityCurve = curve;
2847        }
2848    
2849        /**
2850         * Updates the respective member variable and the lookup table / cache
2851         * that depends on this value.
2852         */
2853        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2854            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2855            VCFVelocityDynamicRange = range;
2856        }
2857    
2858        /**
2859         * Updates the respective member variable and the lookup table / cache
2860         * that depends on this value.
2861         */
2862        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2863            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2864            VCFVelocityScale = scaling;
2865        }
2866    
2867      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) {
2868    
2869          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 2160  namespace { Line 2947  namespace {
2947    
2948          // Actual Loading          // Actual Loading
2949    
2950            if (!file->GetAutoLoad()) return;
2951    
2952          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2953    
2954          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2203  namespace { Line 2992  namespace {
2992              else              else
2993                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
2994    
2995              // load sample references              // load sample references (if auto loading is enabled)
2996              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
2997                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
2998                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2999                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
3000                    }
3001                    GetSample(); // load global region sample reference
3002              }              }
             GetSample(); // load global region sample reference  
3003          } else {          } else {
3004              DimensionRegions = 0;              DimensionRegions = 0;
3005              for (int i = 0 ; i < 8 ; i++) {              for (int i = 0 ; i < 8 ; i++) {
# Line 2223  namespace { Line 3014  namespace {
3014              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
3015              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
3016              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
3017              pDimensionRegions[0] = new DimensionRegion(_3ewl);              pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
3018              DimensionRegions = 1;              DimensionRegions = 1;
3019          }          }
3020      }      }
# Line 2253  namespace { Line 3044  namespace {
3044          }          }
3045    
3046          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
3047          const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;          bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
3048          const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;          const int iMaxDimensions =  version3 ? 8 : 5;
3049            const int iMaxDimensionRegions = version3 ? 256 : 32;
3050    
3051          // make sure '3lnk' chunk exists          // make sure '3lnk' chunk exists
3052          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
3053          if (!_3lnk) {          if (!_3lnk) {
3054              const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;              const int _3lnkChunkSize = version3 ? 1092 : 172;
3055              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3056              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3057    
3058              // move 3prg to last position              // move 3prg to last position
3059              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3060          }          }
3061    
3062          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
# Line 2274  namespace { Line 3066  namespace {
3066          for (int i = 0; i < iMaxDimensions; i++) {          for (int i = 0; i < iMaxDimensions; i++) {
3067              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3068              pData[5 + i * 8] = pDimensionDefinitions[i].bits;              pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3069              pData[6 + i * 8] = shift;              pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3070              pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);              pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3071              pData[8 + i * 8] = pDimensionDefinitions[i].zones;              pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3072              // next 3 bytes unknown, always zero?              // next 3 bytes unknown, always zero?
# Line 2283  namespace { Line 3075  namespace {
3075          }          }
3076    
3077          // update wave pool table in '3lnk' chunk          // update wave pool table in '3lnk' chunk
3078          const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;          const int iWavePoolOffset = version3 ? 68 : 44;
3079          for (uint i = 0; i < iMaxDimensionRegions; i++) {          for (uint i = 0; i < iMaxDimensionRegions; i++) {
3080              int iWaveIndex = -1;              int iWaveIndex = -1;
3081              if (i < DimensionRegions) {              if (i < DimensionRegions) {
# Line 2296  namespace { Line 3088  namespace {
3088                          break;                          break;
3089                      }                      }
3090                  }                  }
                 if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");  
3091              }              }
3092              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3093          }          }
# Line 2309  namespace { Line 3100  namespace {
3100              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
3101              while (_3ewl) {              while (_3ewl) {
3102                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3103                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3104                      dimensionRegionNr++;                      dimensionRegionNr++;
3105                  }                  }
3106                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 2318  namespace { Line 3109  namespace {
3109          }          }
3110      }      }
3111    
3112        void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3113            // update KeyRange struct and make sure regions are in correct order
3114            DLS::Region::SetKeyRange(Low, High);
3115            // update Region key table for fast lookup
3116            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3117        }
3118    
3119      void Region::UpdateVelocityTable() {      void Region::UpdateVelocityTable() {
3120          // get velocity dimension's index          // get velocity dimension's index
3121          int veldim = -1;          int veldim = -1;
# Line 2404  namespace { Line 3202  namespace {
3202       *                        dimension bits limit is violated       *                        dimension bits limit is violated
3203       */       */
3204      void Region::AddDimension(dimension_def_t* pDimDef) {      void Region::AddDimension(dimension_def_t* pDimDef) {
3205            // some initial sanity checks of the given dimension definition
3206            if (pDimDef->zones < 2)
3207                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3208            if (pDimDef->bits < 1)
3209                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3210            if (pDimDef->dimension == dimension_samplechannel) {
3211                if (pDimDef->zones != 2)
3212                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3213                if (pDimDef->bits != 1)
3214                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3215            }
3216    
3217          // check if max. amount of dimensions reached          // check if max. amount of dimensions reached
3218          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3219          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
# Line 2423  namespace { Line 3233  namespace {
3233              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3234                  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");
3235    
3236            // pos is where the new dimension should be placed, normally
3237            // last in list, except for the samplechannel dimension which
3238            // has to be first in list
3239            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3240            int bitpos = 0;
3241            for (int i = 0 ; i < pos ; i++)
3242                bitpos += pDimensionDefinitions[i].bits;
3243    
3244            // make room for the new dimension
3245            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3246            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3247                for (int j = Dimensions ; j > pos ; j--) {
3248                    pDimensionRegions[i]->DimensionUpperLimits[j] =
3249                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
3250                }
3251            }
3252    
3253          // assign definition of new dimension          // assign definition of new dimension
3254          pDimensionDefinitions[Dimensions] = *pDimDef;          pDimensionDefinitions[pos] = *pDimDef;
3255    
3256          // auto correct certain dimension definition fields (where possible)          // auto correct certain dimension definition fields (where possible)
3257          pDimensionDefinitions[Dimensions].split_type  =          pDimensionDefinitions[pos].split_type  =
3258              __resolveSplitType(pDimensionDefinitions[Dimensions].dimension);              __resolveSplitType(pDimensionDefinitions[pos].dimension);
3259          pDimensionDefinitions[Dimensions].zone_size =          pDimensionDefinitions[pos].zone_size =
3260              __resolveZoneSize(pDimensionDefinitions[Dimensions]);              __resolveZoneSize(pDimensionDefinitions[pos]);
3261    
3262          // create new dimension region(s) for this new dimension          // create new dimension region(s) for this new dimension, and make
3263          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {          // sure that the dimension regions are placed correctly in both the
3264              //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values          // RIFF list and the pDimensionRegions array
3265              RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);          RIFF::Chunk* moveTo = NULL;
3266              RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);          RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3267              pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);          for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3268              DimensionRegions++;              for (int k = 0 ; k < (1 << bitpos) ; k++) {
3269                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3270                }
3271                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3272                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
3273                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3274                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3275                        // create a new dimension region and copy all parameter values from
3276                        // an existing dimension region
3277                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3278                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3279    
3280                        DimensionRegions++;
3281                    }
3282                }
3283                moveTo = pDimensionRegions[i]->pParentList;
3284            }
3285    
3286            // initialize the upper limits for this dimension
3287            int mask = (1 << bitpos) - 1;
3288            for (int z = 0 ; z < pDimDef->zones ; z++) {
3289                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3290                for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3291                    pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3292                                      (z << bitpos) |
3293                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3294                }
3295          }          }
3296    
3297          Dimensions++;          Dimensions++;
# Line 2481  namespace { Line 3334  namespace {
3334          for (int i = iDimensionNr + 1; i < Dimensions; i++)          for (int i = iDimensionNr + 1; i < Dimensions; i++)
3335              iUpperBits += pDimensionDefinitions[i].bits;              iUpperBits += pDimensionDefinitions[i].bits;
3336    
3337            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3338    
3339          // delete dimension regions which belong to the given dimension          // delete dimension regions which belong to the given dimension
3340          // (that is where the dimension's bit > 0)          // (that is where the dimension's bit > 0)
3341          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
# Line 2489  namespace { Line 3344  namespace {
3344                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3345                                      iObsoleteBit << iLowerBits |                                      iObsoleteBit << iLowerBits |
3346                                      iLowerBit;                                      iLowerBit;
3347    
3348                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3349                      delete pDimensionRegions[iToDelete];                      delete pDimensionRegions[iToDelete];
3350                      pDimensionRegions[iToDelete] = NULL;                      pDimensionRegions[iToDelete] = NULL;
3351                      DimensionRegions--;                      DimensionRegions--;
# Line 2509  namespace { Line 3366  namespace {
3366              }              }
3367          }          }
3368    
3369            // remove the this dimension from the upper limits arrays
3370            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3371                DimensionRegion* d = pDimensionRegions[j];
3372                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3373                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
3374                }
3375                d->DimensionUpperLimits[Dimensions - 1] = 127;
3376            }
3377    
3378          // 'remove' dimension definition          // 'remove' dimension definition
3379          for (int i = iDimensionNr + 1; i < Dimensions; i++) {          for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3380              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
# Line 2523  namespace { Line 3389  namespace {
3389          if (pDimDef->dimension == dimension_layer) Layers = 1;          if (pDimDef->dimension == dimension_layer) Layers = 1;
3390      }      }
3391    
3392        /** @brief Delete one split zone of a dimension (decrement zone amount).
3393         *
3394         * Instead of deleting an entire dimensions, this method will only delete
3395         * one particular split zone given by @a zone of the Region's dimension
3396         * given by @a type. So this method will simply decrement the amount of
3397         * zones by one of the dimension in question. To be able to do that, the
3398         * respective dimension must exist on this Region and it must have at least
3399         * 3 zones. All DimensionRegion objects associated with the zone will be
3400         * deleted.
3401         *
3402         * @param type - identifies the dimension where a zone shall be deleted
3403         * @param zone - index of the dimension split zone that shall be deleted
3404         * @throws gig::Exception if requested zone could not be deleted
3405         */
3406        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3407            dimension_def_t* oldDef = GetDimensionDefinition(type);
3408            if (!oldDef)
3409                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3410            if (oldDef->zones <= 2)
3411                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3412            if (zone < 0 || zone >= oldDef->zones)
3413                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3414    
3415            const int newZoneSize = oldDef->zones - 1;
3416    
3417            // create a temporary Region which just acts as a temporary copy
3418            // container and will be deleted at the end of this function and will
3419            // also not be visible through the API during this process
3420            gig::Region* tempRgn = NULL;
3421            {
3422                // adding these temporary chunks is probably not even necessary
3423                Instrument* instr = static_cast<Instrument*>(GetParent());
3424                RIFF::List* pCkInstrument = instr->pCkInstrument;
3425                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3426                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3427                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3428                tempRgn = new Region(instr, rgn);
3429            }
3430    
3431            // copy this region's dimensions (with already the dimension split size
3432            // requested by the arguments of this method call) to the temporary
3433            // region, and don't use Region::CopyAssign() here for this task, since
3434            // it would also alter fast lookup helper variables here and there
3435            dimension_def_t newDef;
3436            for (int i = 0; i < Dimensions; ++i) {
3437                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3438                // is this the dimension requested by the method arguments? ...
3439                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3440                    def.zones = newZoneSize;
3441                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3442                    newDef = def;
3443                }
3444                tempRgn->AddDimension(&def);
3445            }
3446    
3447            // find the dimension index in the tempRegion which is the dimension
3448            // type passed to this method (paranoidly expecting different order)
3449            int tempReducedDimensionIndex = -1;
3450            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3451                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3452                    tempReducedDimensionIndex = d;
3453                    break;
3454                }
3455            }
3456    
3457            // copy dimension regions from this region to the temporary region
3458            for (int iDst = 0; iDst < 256; ++iDst) {
3459                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3460                if (!dstDimRgn) continue;
3461                std::map<dimension_t,int> dimCase;
3462                bool isValidZone = true;
3463                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3464                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3465                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3466                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3467                    baseBits += dstBits;
3468                    // there are also DimensionRegion objects of unused zones, skip them
3469                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3470                        isValidZone = false;
3471                        break;
3472                    }
3473                }
3474                if (!isValidZone) continue;
3475                // a bit paranoid: cope with the chance that the dimensions would
3476                // have different order in source and destination regions
3477                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3478                if (dimCase[type] >= zone) dimCase[type]++;
3479                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3480                dstDimRgn->CopyAssign(srcDimRgn);
3481                // if this is the upper most zone of the dimension passed to this
3482                // method, then correct (raise) its upper limit to 127
3483                if (newDef.split_type == split_type_normal && isLastZone)
3484                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3485            }
3486    
3487            // now tempRegion's dimensions and DimensionRegions basically reflect
3488            // what we wanted to get for this actual Region here, so we now just
3489            // delete and recreate the dimension in question with the new amount
3490            // zones and then copy back from tempRegion      
3491            DeleteDimension(oldDef);
3492            AddDimension(&newDef);
3493            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3494                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3495                if (!srcDimRgn) continue;
3496                std::map<dimension_t,int> dimCase;
3497                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3498                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3499                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3500                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3501                    baseBits += srcBits;
3502                }
3503                // a bit paranoid: cope with the chance that the dimensions would
3504                // have different order in source and destination regions
3505                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3506                if (!dstDimRgn) continue;
3507                dstDimRgn->CopyAssign(srcDimRgn);
3508            }
3509    
3510            // delete temporary region
3511            delete tempRgn;
3512    
3513            UpdateVelocityTable();
3514        }
3515    
3516        /** @brief Divide split zone of a dimension in two (increment zone amount).
3517         *
3518         * This will increment the amount of zones for the dimension (given by
3519         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3520         * in the middle of its zone range in two. So the two zones resulting from
3521         * the zone being splitted, will be an equivalent copy regarding all their
3522         * articulation informations and sample reference. The two zones will only
3523         * differ in their zone's upper limit
3524         * (DimensionRegion::DimensionUpperLimits).
3525         *
3526         * @param type - identifies the dimension where a zone shall be splitted
3527         * @param zone - index of the dimension split zone that shall be splitted
3528         * @throws gig::Exception if requested zone could not be splitted
3529         */
3530        void Region::SplitDimensionZone(dimension_t type, int zone) {
3531            dimension_def_t* oldDef = GetDimensionDefinition(type);
3532            if (!oldDef)
3533                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3534            if (zone < 0 || zone >= oldDef->zones)
3535                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3536    
3537            const int newZoneSize = oldDef->zones + 1;
3538    
3539            // create a temporary Region which just acts as a temporary copy
3540            // container and will be deleted at the end of this function and will
3541            // also not be visible through the API during this process
3542            gig::Region* tempRgn = NULL;
3543            {
3544                // adding these temporary chunks is probably not even necessary
3545                Instrument* instr = static_cast<Instrument*>(GetParent());
3546                RIFF::List* pCkInstrument = instr->pCkInstrument;
3547                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3548                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3549                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3550                tempRgn = new Region(instr, rgn);
3551            }
3552    
3553            // copy this region's dimensions (with already the dimension split size
3554            // requested by the arguments of this method call) to the temporary
3555            // region, and don't use Region::CopyAssign() here for this task, since
3556            // it would also alter fast lookup helper variables here and there
3557            dimension_def_t newDef;
3558            for (int i = 0; i < Dimensions; ++i) {
3559                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3560                // is this the dimension requested by the method arguments? ...
3561                if (def.dimension == type) { // ... if yes, increment zone amount by one
3562                    def.zones = newZoneSize;
3563                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3564                    newDef = def;
3565                }
3566                tempRgn->AddDimension(&def);
3567            }
3568    
3569            // find the dimension index in the tempRegion which is the dimension
3570            // type passed to this method (paranoidly expecting different order)
3571            int tempIncreasedDimensionIndex = -1;
3572            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3573                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3574                    tempIncreasedDimensionIndex = d;
3575                    break;
3576                }
3577            }
3578    
3579            // copy dimension regions from this region to the temporary region
3580            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3581                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3582                if (!srcDimRgn) continue;
3583                std::map<dimension_t,int> dimCase;
3584                bool isValidZone = true;
3585                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3586                    const int srcBits = pDimensionDefinitions[d].bits;
3587                    dimCase[pDimensionDefinitions[d].dimension] =
3588                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3589                    // there are also DimensionRegion objects for unused zones, skip them
3590                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3591                        isValidZone = false;
3592                        break;
3593                    }
3594                    baseBits += srcBits;
3595                }
3596                if (!isValidZone) continue;
3597                // a bit paranoid: cope with the chance that the dimensions would
3598                // have different order in source and destination regions            
3599                if (dimCase[type] > zone) dimCase[type]++;
3600                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3601                dstDimRgn->CopyAssign(srcDimRgn);
3602                // if this is the requested zone to be splitted, then also copy
3603                // the source DimensionRegion to the newly created target zone
3604                // and set the old zones upper limit lower
3605                if (dimCase[type] == zone) {
3606                    // lower old zones upper limit
3607                    if (newDef.split_type == split_type_normal) {
3608                        const int high =
3609                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3610                        int low = 0;
3611                        if (zone > 0) {
3612                            std::map<dimension_t,int> lowerCase = dimCase;
3613                            lowerCase[type]--;
3614                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3615                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3616                        }
3617                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3618                    }
3619                    // fill the newly created zone of the divided zone as well
3620                    dimCase[type]++;
3621                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3622                    dstDimRgn->CopyAssign(srcDimRgn);
3623                }
3624            }
3625    
3626            // now tempRegion's dimensions and DimensionRegions basically reflect
3627            // what we wanted to get for this actual Region here, so we now just
3628            // delete and recreate the dimension in question with the new amount
3629            // zones and then copy back from tempRegion      
3630            DeleteDimension(oldDef);
3631            AddDimension(&newDef);
3632            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3633                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3634                if (!srcDimRgn) continue;
3635                std::map<dimension_t,int> dimCase;
3636                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3637                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3638                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3639                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3640                    baseBits += srcBits;
3641                }
3642                // a bit paranoid: cope with the chance that the dimensions would
3643                // have different order in source and destination regions
3644                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3645                if (!dstDimRgn) continue;
3646                dstDimRgn->CopyAssign(srcDimRgn);
3647            }
3648    
3649            // delete temporary region
3650            delete tempRgn;
3651    
3652            UpdateVelocityTable();
3653        }
3654    
3655        /** @brief Change type of an existing dimension.
3656         *
3657         * Alters the dimension type of a dimension already existing on this
3658         * region. If there is currently no dimension on this Region with type
3659         * @a oldType, then this call with throw an Exception. Likewise there are
3660         * cases where the requested dimension type cannot be performed. For example
3661         * if the new dimension type shall be gig::dimension_samplechannel, and the
3662         * current dimension has more than 2 zones. In such cases an Exception is
3663         * thrown as well.
3664         *
3665         * @param oldType - identifies the existing dimension to be changed
3666         * @param newType - to which dimension type it should be changed to
3667         * @throws gig::Exception if requested change cannot be performed
3668         */
3669        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3670            if (oldType == newType) return;
3671            dimension_def_t* def = GetDimensionDefinition(oldType);
3672            if (!def)
3673                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3674            if (newType == dimension_samplechannel && def->zones != 2)
3675                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3676            def->split_type = __resolveSplitType(newType);
3677        }
3678    
3679        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3680            uint8_t bits[8] = {};
3681            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3682                 it != DimCase.end(); ++it)
3683            {
3684                for (int d = 0; d < Dimensions; ++d) {
3685                    if (pDimensionDefinitions[d].dimension == it->first) {
3686                        bits[d] = it->second;
3687                        goto nextDimCaseSlice;
3688                    }
3689                }
3690                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3691                nextDimCaseSlice:
3692                ; // noop
3693            }
3694            return GetDimensionRegionByBit(bits);
3695        }
3696    
3697        /**
3698         * Searches in the current Region for a dimension of the given dimension
3699         * type and returns the precise configuration of that dimension in this
3700         * Region.
3701         *
3702         * @param type - dimension type of the sought dimension
3703         * @returns dimension definition or NULL if there is no dimension with
3704         *          sought type in this Region.
3705         */
3706        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3707            for (int i = 0; i < Dimensions; ++i)
3708                if (pDimensionDefinitions[i].dimension == type)
3709                    return &pDimensionDefinitions[i];
3710            return NULL;
3711        }
3712    
3713      Region::~Region() {      Region::~Region() {
3714          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
3715              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
# Line 2580  namespace { Line 3767  namespace {
3767              }              }
3768              bitpos += pDimensionDefinitions[i].bits;              bitpos += pDimensionDefinitions[i].bits;
3769          }          }
3770          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3771            if (!dimreg) return NULL;
3772          if (veldim != -1) {          if (veldim != -1) {
3773              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3774              if (dimreg->VelocityTable) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3775                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3776              else // normal split type              else // normal split type
3777                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3778    
3779              dimregidx |= bits << velbitpos;              const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3780              dimreg = pDimensionRegions[dimregidx];              dimregidx |= (bits & limiter_mask) << velbitpos;
3781                dimreg = pDimensionRegions[dimregidx & 255];
3782          }          }
3783          return dimreg;          return dimreg;
3784      }      }
3785    
3786        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3787            uint8_t bits;
3788            int veldim = -1;
3789            int velbitpos;
3790            int bitpos = 0;
3791            int dimregidx = 0;
3792            for (uint i = 0; i < Dimensions; i++) {
3793                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3794                    // the velocity dimension must be handled after the other dimensions
3795                    veldim = i;
3796                    velbitpos = bitpos;
3797                } else {
3798                    switch (pDimensionDefinitions[i].split_type) {
3799                        case split_type_normal:
3800                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3801                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3802                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3803                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3804                                }
3805                            } else {
3806                                // gig2: evenly sized zones
3807                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3808                            }
3809                            break;
3810                        case split_type_bit: // the value is already the sought dimension bit number
3811                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3812                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3813                            break;
3814                    }
3815                    dimregidx |= bits << bitpos;
3816                }
3817                bitpos += pDimensionDefinitions[i].bits;
3818            }
3819            dimregidx &= 255;
3820            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3821            if (!dimreg) return -1;
3822            if (veldim != -1) {
3823                // (dimreg is now the dimension region for the lowest velocity)
3824                if (dimreg->VelocityTable) // custom defined zone ranges
3825                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3826                else // normal split type
3827                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3828    
3829                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3830                dimregidx |= (bits & limiter_mask) << velbitpos;
3831                dimregidx &= 255;
3832            }
3833            return dimregidx;
3834        }
3835    
3836      /**      /**
3837       * Returns the appropriate DimensionRegion for the given dimension bit       * Returns the appropriate DimensionRegion for the given dimension bit
3838       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
# Line 2642  namespace { Line 3881  namespace {
3881          }          }
3882          return NULL;          return NULL;
3883      }      }
3884        
3885        /**
3886         * Make a (semi) deep copy of the Region object given by @a orig
3887         * and assign it to this object.
3888         *
3889         * Note that all sample pointers referenced by @a orig are simply copied as
3890         * memory address. Thus the respective samples are shared, not duplicated!
3891         *
3892         * @param orig - original Region object to be copied from
3893         */
3894        void Region::CopyAssign(const Region* orig) {
3895            CopyAssign(orig, NULL);
3896        }
3897        
3898        /**
3899         * Make a (semi) deep copy of the Region object given by @a orig and
3900         * assign it to this object
3901         *
3902         * @param mSamples - crosslink map between the foreign file's samples and
3903         *                   this file's samples
3904         */
3905        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3906            // handle base classes
3907            DLS::Region::CopyAssign(orig);
3908            
3909            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3910                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3911            }
3912            
3913            // handle own member variables
3914            for (int i = Dimensions - 1; i >= 0; --i) {
3915                DeleteDimension(&pDimensionDefinitions[i]);
3916            }
3917            Layers = 0; // just to be sure
3918            for (int i = 0; i < orig->Dimensions; i++) {
3919                // we need to copy the dim definition here, to avoid the compiler
3920                // complaining about const-ness issue
3921                dimension_def_t def = orig->pDimensionDefinitions[i];
3922                AddDimension(&def);
3923            }
3924            for (int i = 0; i < 256; i++) {
3925                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3926                    pDimensionRegions[i]->CopyAssign(
3927                        orig->pDimensionRegions[i],
3928                        mSamples
3929                    );
3930                }
3931            }
3932            Layers = orig->Layers;
3933        }
3934    
3935    
3936    // *************** MidiRule ***************
3937    // *
3938    
3939        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3940            _3ewg->SetPos(36);
3941            Triggers = _3ewg->ReadUint8();
3942            _3ewg->SetPos(40);
3943            ControllerNumber = _3ewg->ReadUint8();
3944            _3ewg->SetPos(46);
3945            for (int i = 0 ; i < Triggers ; i++) {
3946                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3947                pTriggers[i].Descending = _3ewg->ReadUint8();
3948                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3949                pTriggers[i].Key = _3ewg->ReadUint8();
3950                pTriggers[i].NoteOff = _3ewg->ReadUint8();
3951                pTriggers[i].Velocity = _3ewg->ReadUint8();
3952                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3953                _3ewg->ReadUint8();
3954            }
3955        }
3956    
3957        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3958            ControllerNumber(0),
3959            Triggers(0) {
3960        }
3961    
3962        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3963            pData[32] = 4;
3964            pData[33] = 16;
3965            pData[36] = Triggers;
3966            pData[40] = ControllerNumber;
3967            for (int i = 0 ; i < Triggers ; i++) {
3968                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3969                pData[47 + i * 8] = pTriggers[i].Descending;
3970                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3971                pData[49 + i * 8] = pTriggers[i].Key;
3972                pData[50 + i * 8] = pTriggers[i].NoteOff;
3973                pData[51 + i * 8] = pTriggers[i].Velocity;
3974                pData[52 + i * 8] = pTriggers[i].OverridePedal;
3975            }
3976        }
3977    
3978        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3979            _3ewg->SetPos(36);
3980            LegatoSamples = _3ewg->ReadUint8(); // always 12
3981            _3ewg->SetPos(40);
3982            BypassUseController = _3ewg->ReadUint8();
3983            BypassKey = _3ewg->ReadUint8();
3984            BypassController = _3ewg->ReadUint8();
3985            ThresholdTime = _3ewg->ReadUint16();
3986            _3ewg->ReadInt16();
3987            ReleaseTime = _3ewg->ReadUint16();
3988            _3ewg->ReadInt16();
3989            KeyRange.low = _3ewg->ReadUint8();
3990            KeyRange.high = _3ewg->ReadUint8();
3991            _3ewg->SetPos(64);
3992            ReleaseTriggerKey = _3ewg->ReadUint8();
3993            AltSustain1Key = _3ewg->ReadUint8();
3994            AltSustain2Key = _3ewg->ReadUint8();
3995        }
3996    
3997        MidiRuleLegato::MidiRuleLegato() :
3998            LegatoSamples(12),
3999            BypassUseController(false),
4000            BypassKey(0),
4001            BypassController(1),
4002            ThresholdTime(20),
4003            ReleaseTime(20),
4004            ReleaseTriggerKey(0),
4005            AltSustain1Key(0),
4006            AltSustain2Key(0)
4007        {
4008            KeyRange.low = KeyRange.high = 0;
4009        }
4010    
4011        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
4012            pData[32] = 0;
4013            pData[33] = 16;
4014            pData[36] = LegatoSamples;
4015            pData[40] = BypassUseController;
4016            pData[41] = BypassKey;
4017            pData[42] = BypassController;
4018            store16(&pData[43], ThresholdTime);
4019            store16(&pData[47], ReleaseTime);
4020            pData[51] = KeyRange.low;
4021            pData[52] = KeyRange.high;
4022            pData[64] = ReleaseTriggerKey;
4023            pData[65] = AltSustain1Key;
4024            pData[66] = AltSustain2Key;
4025        }
4026    
4027        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4028            _3ewg->SetPos(36);
4029            Articulations = _3ewg->ReadUint8();
4030            int flags = _3ewg->ReadUint8();
4031            Polyphonic = flags & 8;
4032            Chained = flags & 4;
4033            Selector = (flags & 2) ? selector_controller :
4034                (flags & 1) ? selector_key_switch : selector_none;
4035            Patterns = _3ewg->ReadUint8();
4036            _3ewg->ReadUint8(); // chosen row
4037            _3ewg->ReadUint8(); // unknown
4038            _3ewg->ReadUint8(); // unknown
4039            _3ewg->ReadUint8(); // unknown
4040            KeySwitchRange.low = _3ewg->ReadUint8();
4041            KeySwitchRange.high = _3ewg->ReadUint8();
4042            Controller = _3ewg->ReadUint8();
4043            PlayRange.low = _3ewg->ReadUint8();
4044            PlayRange.high = _3ewg->ReadUint8();
4045    
4046            int n = std::min(int(Articulations), 32);
4047            for (int i = 0 ; i < n ; i++) {
4048                _3ewg->ReadString(pArticulations[i], 32);
4049            }
4050            _3ewg->SetPos(1072);
4051            n = std::min(int(Patterns), 32);
4052            for (int i = 0 ; i < n ; i++) {
4053                _3ewg->ReadString(pPatterns[i].Name, 16);
4054                pPatterns[i].Size = _3ewg->ReadUint8();
4055                _3ewg->Read(&pPatterns[i][0], 1, 32);
4056            }
4057        }
4058    
4059        MidiRuleAlternator::MidiRuleAlternator() :
4060            Articulations(0),
4061            Patterns(0),
4062            Selector(selector_none),
4063            Controller(0),
4064            Polyphonic(false),
4065            Chained(false)
4066        {
4067            PlayRange.low = PlayRange.high = 0;
4068            KeySwitchRange.low = KeySwitchRange.high = 0;
4069        }
4070    
4071        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4072            pData[32] = 3;
4073            pData[33] = 16;
4074            pData[36] = Articulations;
4075            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4076                (Selector == selector_controller ? 2 :
4077                 (Selector == selector_key_switch ? 1 : 0));
4078            pData[38] = Patterns;
4079    
4080            pData[43] = KeySwitchRange.low;
4081            pData[44] = KeySwitchRange.high;
4082            pData[45] = Controller;
4083            pData[46] = PlayRange.low;
4084            pData[47] = PlayRange.high;
4085    
4086            char* str = reinterpret_cast<char*>(pData);
4087            int pos = 48;
4088            int n = std::min(int(Articulations), 32);
4089            for (int i = 0 ; i < n ; i++, pos += 32) {
4090                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4091            }
4092    
4093            pos = 1072;
4094            n = std::min(int(Patterns), 32);
4095            for (int i = 0 ; i < n ; i++, pos += 49) {
4096                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4097                pData[pos + 16] = pPatterns[i].Size;
4098                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4099            }
4100        }
4101    
4102    // *************** Script ***************
4103    // *
4104    
4105        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4106            pGroup = group;
4107            pChunk = ckScri;
4108            if (ckScri) { // object is loaded from file ...
4109                // read header
4110                uint32_t headerSize = ckScri->ReadUint32();
4111                Compression = (Compression_t) ckScri->ReadUint32();
4112                Encoding    = (Encoding_t) ckScri->ReadUint32();
4113                Language    = (Language_t) ckScri->ReadUint32();
4114                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4115                crc         = ckScri->ReadUint32();
4116                uint32_t nameSize = ckScri->ReadUint32();
4117                Name.resize(nameSize, ' ');
4118                for (int i = 0; i < nameSize; ++i)
4119                    Name[i] = ckScri->ReadUint8();
4120                // to handle potential future extensions of the header
4121                ckScri->SetPos(sizeof(int32_t) + headerSize);
4122                // read actual script data
4123                uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();
4124                data.resize(scriptSize);
4125                for (int i = 0; i < scriptSize; ++i)
4126                    data[i] = ckScri->ReadUint8();
4127            } else { // this is a new script object, so just initialize it as such ...
4128                Compression = COMPRESSION_NONE;
4129                Encoding = ENCODING_ASCII;
4130                Language = LANGUAGE_NKSP;
4131                Bypass   = false;
4132                crc      = 0;
4133                Name     = "Unnamed Script";
4134            }
4135        }
4136    
4137        Script::~Script() {
4138        }
4139    
4140        /**
4141         * Returns the current script (i.e. as source code) in text format.
4142         */
4143        String Script::GetScriptAsText() {
4144            String s;
4145            s.resize(data.size(), ' ');
4146            memcpy(&s[0], &data[0], data.size());
4147            return s;
4148        }
4149    
4150        /**
4151         * Replaces the current script with the new script source code text given
4152         * by @a text.
4153         *
4154         * @param text - new script source code
4155         */
4156        void Script::SetScriptAsText(const String& text) {
4157            data.resize(text.size());
4158            memcpy(&data[0], &text[0], text.size());
4159        }
4160    
4161        void Script::UpdateChunks() {
4162            // recalculate CRC32 check sum
4163            __resetCRC(crc);
4164            __calculateCRC(&data[0], data.size(), crc);
4165            __encodeCRC(crc);
4166            // make sure chunk exists and has the required size
4167            const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size();
4168            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4169            else pChunk->Resize(chunkSize);
4170            // fill the chunk data to be written to disk
4171            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4172            int pos = 0;
4173            store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size
4174            pos += sizeof(int32_t);
4175            store32(&pData[pos], Compression);
4176            pos += sizeof(int32_t);
4177            store32(&pData[pos], Encoding);
4178            pos += sizeof(int32_t);
4179            store32(&pData[pos], Language);
4180            pos += sizeof(int32_t);
4181            store32(&pData[pos], Bypass ? 1 : 0);
4182            pos += sizeof(int32_t);
4183            store32(&pData[pos], crc);
4184            pos += sizeof(int32_t);
4185            store32(&pData[pos], Name.size());
4186            pos += sizeof(int32_t);
4187            for (int i = 0; i < Name.size(); ++i, ++pos)
4188                pData[pos] = Name[i];
4189            for (int i = 0; i < data.size(); ++i, ++pos)
4190                pData[pos] = data[i];
4191        }
4192    
4193        /**
4194         * Move this script from its current ScriptGroup to another ScriptGroup
4195         * given by @a pGroup.
4196         *
4197         * @param pGroup - script's new group
4198         */
4199        void Script::SetGroup(ScriptGroup* pGroup) {
4200            if (this->pGroup = pGroup) return;
4201            if (pChunk)
4202                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4203            this->pGroup = pGroup;
4204        }
4205    
4206        /**
4207         * Returns the script group this script currently belongs to. Each script
4208         * is a member of exactly one ScriptGroup.
4209         *
4210         * @returns current script group
4211         */
4212        ScriptGroup* Script::GetGroup() const {
4213            return pGroup;
4214        }
4215    
4216        void Script::RemoveAllScriptReferences() {
4217            File* pFile = pGroup->pFile;
4218            for (int i = 0; pFile->GetInstrument(i); ++i) {
4219                Instrument* instr = pFile->GetInstrument(i);
4220                instr->RemoveScript(this);
4221            }
4222        }
4223    
4224    // *************** ScriptGroup ***************
4225    // *
4226    
4227        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4228            pFile = file;
4229            pList = lstRTIS;
4230            pScripts = NULL;
4231            if (lstRTIS) {
4232                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4233                ::LoadString(ckName, Name);
4234            } else {
4235                Name = "Default Group";
4236            }
4237        }
4238    
4239        ScriptGroup::~ScriptGroup() {
4240            if (pScripts) {
4241                std::list<Script*>::iterator iter = pScripts->begin();
4242                std::list<Script*>::iterator end  = pScripts->end();
4243                while (iter != end) {
4244                    delete *iter;
4245                    ++iter;
4246                }
4247                delete pScripts;
4248            }
4249        }
4250    
4251        void ScriptGroup::UpdateChunks() {
4252            if (pScripts) {
4253                if (!pList)
4254                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4255    
4256                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4257                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4258    
4259                for (std::list<Script*>::iterator it = pScripts->begin();
4260                     it != pScripts->end(); ++it)
4261                {
4262                    (*it)->UpdateChunks();
4263                }
4264            }
4265        }
4266    
4267        /** @brief Get instrument script.
4268         *
4269         * Returns the real-time instrument script with the given index.
4270         *
4271         * @param index - number of the sought script (0..n)
4272         * @returns sought script or NULL if there's no such script
4273         */
4274        Script* ScriptGroup::GetScript(uint index) {
4275            if (!pScripts) LoadScripts();
4276            std::list<Script*>::iterator it = pScripts->begin();
4277            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4278                if (i == index) return *it;
4279            return NULL;
4280        }
4281    
4282        /** @brief Add new instrument script.
4283         *
4284         * Adds a new real-time instrument script to the file. The script is not
4285         * actually used / executed unless it is referenced by an instrument to be
4286         * used. This is similar to samples, which you can add to a file, without
4287         * an instrument necessarily actually using it.
4288         *
4289         * You have to call Save() to make this persistent to the file.
4290         *
4291         * @return new empty script object
4292         */
4293        Script* ScriptGroup::AddScript() {
4294            if (!pScripts) LoadScripts();
4295            Script* pScript = new Script(this, NULL);
4296            pScripts->push_back(pScript);
4297            return pScript;
4298        }
4299    
4300        /** @brief Delete an instrument script.
4301         *
4302         * This will delete the given real-time instrument script. References of
4303         * instruments that are using that script will be removed accordingly.
4304         *
4305         * You have to call Save() to make this persistent to the file.
4306         *
4307         * @param pScript - script to delete
4308         * @throws gig::Exception if given script could not be found
4309         */
4310        void ScriptGroup::DeleteScript(Script* pScript) {
4311            if (!pScripts) LoadScripts();
4312            std::list<Script*>::iterator iter =
4313                find(pScripts->begin(), pScripts->end(), pScript);
4314            if (iter == pScripts->end())
4315                throw gig::Exception("Could not delete script, could not find given script");
4316            pScripts->erase(iter);
4317            pScript->RemoveAllScriptReferences();
4318            if (pScript->pChunk)
4319                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4320            delete pScript;
4321        }
4322    
4323        void ScriptGroup::LoadScripts() {
4324            if (pScripts) return;
4325            pScripts = new std::list<Script*>;
4326            if (!pList) return;
4327    
4328            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4329                 ck = pList->GetNextSubChunk())
4330            {
4331                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4332                    pScripts->push_back(new Script(this, ck));
4333                }
4334            }
4335        }
4336    
4337  // *************** Instrument ***************  // *************** Instrument ***************
4338  // *  // *
4339    
4340      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) {
4341          static const DLS::Info::FixedStringLength fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
4342              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
4343              { CHUNK_ID_ISFT, 12 },              { CHUNK_ID_ISFT, 12 },
4344              { 0, 0 }              { 0, 0 }
4345          };          };
4346          pInfo->FixedStringLengths = fixedStringLengths;          pInfo->SetFixedStringLengths(fixedStringLengths);
4347    
4348          // Initialization          // Initialization
4349          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
# Line 2665  namespace { Line 4354  namespace {
4354          PianoReleaseMode = false;          PianoReleaseMode = false;
4355          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
4356          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
4357            pMidiRules = new MidiRule*[3];
4358            pMidiRules[0] = NULL;
4359            pScriptRefs = NULL;
4360    
4361          // Loading          // Loading
4362          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2679  namespace { Line 4371  namespace {
4371                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
4372                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
4373                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
4374    
4375                    if (_3ewg->GetSize() > 32) {
4376                        // read MIDI rules
4377                        int i = 0;
4378                        _3ewg->SetPos(32);
4379                        uint8_t id1 = _3ewg->ReadUint8();
4380                        uint8_t id2 = _3ewg->ReadUint8();
4381    
4382                        if (id2 == 16) {
4383                            if (id1 == 4) {
4384                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4385                            } else if (id1 == 0) {
4386                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4387                            } else if (id1 == 3) {
4388                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4389                            } else {
4390                                pMidiRules[i++] = new MidiRuleUnknown;
4391                            }
4392                        }
4393                        else if (id1 != 0 || id2 != 0) {
4394                            pMidiRules[i++] = new MidiRuleUnknown;
4395                        }
4396                        //TODO: all the other types of rules
4397    
4398                        pMidiRules[i] = NULL;
4399                    }
4400              }              }
4401          }          }
4402    
4403          if (!pRegions) pRegions = new RegionList;          if (pFile->GetAutoLoad()) {
4404          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);              if (!pRegions) pRegions = new RegionList;
4405          if (lrgn) {              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4406              RIFF::List* rgn = lrgn->GetFirstSubList();              if (lrgn) {
4407              while (rgn) {                  RIFF::List* rgn = lrgn->GetFirstSubList();
4408                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  while (rgn) {
4409                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                      if (rgn->GetListType() == LIST_TYPE_RGN) {
4410                      pRegions->push_back(new Region(this, rgn));                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4411                            pRegions->push_back(new Region(this, rgn));
4412                        }
4413                        rgn = lrgn->GetNextSubList();
4414                    }
4415                    // Creating Region Key Table for fast lookup
4416                    UpdateRegionKeyTable();
4417                }
4418            }
4419    
4420            // own gig format extensions
4421            RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4422            if (lst3LS) {
4423                RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4424                if (ckSCSL) {
4425                    int headerSize = ckSCSL->ReadUint32();
4426                    int slotCount  = ckSCSL->ReadUint32();
4427                    if (slotCount) {
4428                        int slotSize  = ckSCSL->ReadUint32();
4429                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4430                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4431                        for (int i = 0; i < slotCount; ++i) {
4432                            _ScriptPooolEntry e;
4433                            e.fileOffset = ckSCSL->ReadUint32();
4434                            e.bypass     = ckSCSL->ReadUint32() & 1;
4435                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4436                            scriptPoolFileOffsets.push_back(e);
4437                        }
4438                  }                  }
                 rgn = lrgn->GetNextSubList();  
4439              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
4440          }          }
4441    
4442          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4443      }      }
4444    
4445      void Instrument::UpdateRegionKeyTable() {      void Instrument::UpdateRegionKeyTable() {
4446            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4447          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
4448          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
4449          for (; iter != end; ++iter) {          for (; iter != end; ++iter) {
# Line 2712  namespace { Line 4455  namespace {
4455      }      }
4456    
4457      Instrument::~Instrument() {      Instrument::~Instrument() {
4458            for (int i = 0 ; pMidiRules[i] ; i++) {
4459                delete pMidiRules[i];
4460            }
4461            delete[] pMidiRules;
4462            if (pScriptRefs) delete pScriptRefs;
4463      }      }
4464    
4465      /**      /**
# Line 2740  namespace { Line 4488  namespace {
4488          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
4489          // make sure '3ewg' RIFF chunk exists          // make sure '3ewg' RIFF chunk exists
4490          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4491          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);          if (!_3ewg)  {
4492                File* pFile = (File*) GetParent();
4493    
4494                // 3ewg is bigger in gig3, as it includes the iMIDI rules
4495                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
4496                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
4497                memset(_3ewg->LoadChunkData(), 0, size);
4498            }
4499          // update '3ewg' RIFF chunk          // update '3ewg' RIFF chunk
4500          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
4501          store16(&pData[0], EffectSend);          store16(&pData[0], EffectSend);
4502          store32(&pData[2], Attenuation);          store32(&pData[2], Attenuation);
4503          store16(&pData[6], FineTune);          store16(&pData[6], FineTune);
4504          store16(&pData[8], PitchbendRange);          store16(&pData[8], PitchbendRange);
4505          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |          const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
4506                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
4507          pData[10] = dimkeystart;          pData[10] = dimkeystart;
4508          pData[11] = DimensionKeyRange.high;          pData[11] = DimensionKeyRange.high;
4509    
4510            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4511                pData[32] = 0;
4512                pData[33] = 0;
4513            } else {
4514                for (int i = 0 ; pMidiRules[i] ; i++) {
4515                    pMidiRules[i]->UpdateChunks(pData);
4516                }
4517            }
4518    
4519            // own gig format extensions
4520           if (pScriptRefs) {
4521               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4522               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4523               const int slotCount = pScriptRefs->size();
4524               const int headerSize = 3 * sizeof(uint32_t);
4525               const int slotSize  = 2 * sizeof(uint32_t);
4526               const int totalChunkSize = headerSize + slotCount * slotSize;
4527               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4528               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4529               else ckSCSL->Resize(totalChunkSize);
4530               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4531               int pos = 0;
4532               store32(&pData[pos], headerSize);
4533               pos += sizeof(uint32_t);
4534               store32(&pData[pos], slotCount);
4535               pos += sizeof(uint32_t);
4536               store32(&pData[pos], slotSize);
4537               pos += sizeof(uint32_t);
4538               for (int i = 0; i < slotCount; ++i) {
4539                   // arbitrary value, the actual file offset will be updated in
4540                   // UpdateScriptFileOffsets() after the file has been resized
4541                   int bogusFileOffset = 0;
4542                   store32(&pData[pos], bogusFileOffset);
4543                   pos += sizeof(uint32_t);
4544                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4545                   pos += sizeof(uint32_t);
4546               }
4547           }
4548        }
4549    
4550        void Instrument::UpdateScriptFileOffsets() {
4551           // own gig format extensions
4552           if (pScriptRefs) {
4553               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4554               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4555               const int slotCount = pScriptRefs->size();
4556               const int headerSize = 3 * sizeof(uint32_t);
4557               ckSCSL->SetPos(headerSize);
4558               for (int i = 0; i < slotCount; ++i) {
4559                   uint32_t fileOffset =
4560                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4561                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4562                        CHUNK_HEADER_SIZE;
4563                   ckSCSL->WriteUint32(&fileOffset);
4564                   // jump over flags entry (containing the bypass flag)
4565                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4566               }
4567           }        
4568      }      }
4569    
4570      /**      /**
# Line 2761  namespace { Line 4575  namespace {
4575       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
4576       */       */
4577      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
4578          if (!pRegions || !pRegions->size() || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
4579          return RegionKeyTable[Key];          return RegionKeyTable[Key];
4580    
4581          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
# Line 2819  namespace { Line 4633  namespace {
4633          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4634      }      }
4635    
4636        /**
4637         * Returns a MIDI rule of the instrument.
4638         *
4639         * The list of MIDI rules, at least in gig v3, always contains at
4640         * most two rules. The second rule can only be the DEF filter
4641         * (which currently isn't supported by libgig).
4642         *
4643         * @param i - MIDI rule number
4644         * @returns   pointer address to MIDI rule number i or NULL if there is none
4645         */
4646        MidiRule* Instrument::GetMidiRule(int i) {
4647            return pMidiRules[i];
4648        }
4649    
4650        /**
4651         * Adds the "controller trigger" MIDI rule to the instrument.
4652         *
4653         * @returns the new MIDI rule
4654         */
4655        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4656            delete pMidiRules[0];
4657            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4658            pMidiRules[0] = r;
4659            pMidiRules[1] = 0;
4660            return r;
4661        }
4662    
4663        /**
4664         * Adds the legato MIDI rule to the instrument.
4665         *
4666         * @returns the new MIDI rule
4667         */
4668        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4669            delete pMidiRules[0];
4670            MidiRuleLegato* r = new MidiRuleLegato;
4671            pMidiRules[0] = r;
4672            pMidiRules[1] = 0;
4673            return r;
4674        }
4675    
4676        /**
4677         * Adds the alternator MIDI rule to the instrument.
4678         *
4679         * @returns the new MIDI rule
4680         */
4681        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4682            delete pMidiRules[0];
4683            MidiRuleAlternator* r = new MidiRuleAlternator;
4684            pMidiRules[0] = r;
4685            pMidiRules[1] = 0;
4686            return r;
4687        }
4688    
4689        /**
4690         * Deletes a MIDI rule from the instrument.
4691         *
4692         * @param i - MIDI rule number
4693         */
4694        void Instrument::DeleteMidiRule(int i) {
4695            delete pMidiRules[i];
4696            pMidiRules[i] = 0;
4697        }
4698    
4699        void Instrument::LoadScripts() {
4700            if (pScriptRefs) return;
4701            pScriptRefs = new std::vector<_ScriptPooolRef>;
4702            if (scriptPoolFileOffsets.empty()) return;
4703            File* pFile = (File*) GetParent();
4704            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4705                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4706                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4707                    ScriptGroup* group = pFile->GetScriptGroup(i);
4708                    for (uint s = 0; group->GetScript(s); ++s) {
4709                        Script* script = group->GetScript(s);
4710                        if (script->pChunk) {
4711                            uint32_t offset = script->pChunk->GetFilePos() -
4712                                              script->pChunk->GetPos() -
4713                                              CHUNK_HEADER_SIZE;
4714                            if (offset == soughtOffset)
4715                            {
4716                                _ScriptPooolRef ref;
4717                                ref.script = script;
4718                                ref.bypass = scriptPoolFileOffsets[k].bypass;
4719                                pScriptRefs->push_back(ref);
4720                                break;
4721                            }
4722                        }
4723                    }
4724                }
4725            }
4726            // we don't need that anymore
4727            scriptPoolFileOffsets.clear();
4728        }
4729    
4730        /** @brief Get instrument script (gig format extension).
4731         *
4732         * Returns the real-time instrument script of instrument script slot
4733         * @a index.
4734         *
4735         * @note This is an own format extension which did not exist i.e. in the
4736         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4737         * gigedit.
4738         *
4739         * @param index - instrument script slot index
4740         * @returns script or NULL if index is out of bounds
4741         */
4742        Script* Instrument::GetScriptOfSlot(uint index) {
4743            LoadScripts();
4744            if (index >= pScriptRefs->size()) return NULL;
4745            return pScriptRefs->at(index).script;
4746        }
4747    
4748        /** @brief Add new instrument script slot (gig format extension).
4749         *
4750         * Add the given real-time instrument script reference to this instrument,
4751         * which shall be executed by the sampler for for this instrument. The
4752         * script will be added to the end of the script list of this instrument.
4753         * The positions of the scripts in the Instrument's Script list are
4754         * relevant, because they define in which order they shall be executed by
4755         * the sampler. For this reason it is also legal to add the same script
4756         * twice to an instrument, for example you might have a script called
4757         * "MyFilter" which performs an event filter task, and you might have
4758         * another script called "MyNoteTrigger" which triggers new notes, then you
4759         * might for example have the following list of scripts on the instrument:
4760         *
4761         * 1. Script "MyFilter"
4762         * 2. Script "MyNoteTrigger"
4763         * 3. Script "MyFilter"
4764         *
4765         * Which would make sense, because the 2nd script launched new events, which
4766         * you might need to filter as well.
4767         *
4768         * There are two ways to disable / "bypass" scripts. You can either disable
4769         * a script locally for the respective script slot on an instrument (i.e. by
4770         * passing @c false to the 2nd argument of this method, or by calling
4771         * SetScriptBypassed()). Or you can disable a script globally for all slots
4772         * and all instruments by setting Script::Bypass.
4773         *
4774         * @note This is an own format extension which did not exist i.e. in the
4775         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4776         * gigedit.
4777         *
4778         * @param pScript - script that shall be executed for this instrument
4779         * @param bypass  - if enabled, the sampler shall skip executing this
4780         *                  script (in the respective list position)
4781         * @see SetScriptBypassed()
4782         */
4783        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4784            LoadScripts();
4785            _ScriptPooolRef ref = { pScript, bypass };
4786            pScriptRefs->push_back(ref);
4787        }
4788    
4789        /** @brief Flip two script slots with each other (gig format extension).
4790         *
4791         * Swaps the position of the two given scripts in the Instrument's Script
4792         * list. The positions of the scripts in the Instrument's Script list are
4793         * relevant, because they define in which order they shall be executed by
4794         * the sampler.
4795         *
4796         * @note This is an own format extension which did not exist i.e. in the
4797         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4798         * gigedit.
4799         *
4800         * @param index1 - index of the first script slot to swap
4801         * @param index2 - index of the second script slot to swap
4802         */
4803        void Instrument::SwapScriptSlots(uint index1, uint index2) {
4804            LoadScripts();
4805            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4806                return;
4807            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4808            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4809            (*pScriptRefs)[index2] = tmp;
4810        }
4811    
4812        /** @brief Remove script slot.
4813         *
4814         * Removes the script slot with the given slot index.
4815         *
4816         * @param index - index of script slot to remove
4817         */
4818        void Instrument::RemoveScriptSlot(uint index) {
4819            LoadScripts();
4820            if (index >= pScriptRefs->size()) return;
4821            pScriptRefs->erase( pScriptRefs->begin() + index );
4822        }
4823    
4824        /** @brief Remove reference to given Script (gig format extension).
4825         *
4826         * This will remove all script slots on the instrument which are referencing
4827         * the given script.
4828         *
4829         * @note This is an own format extension which did not exist i.e. in the
4830         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4831         * gigedit.
4832         *
4833         * @param pScript - script reference to remove from this instrument
4834         * @see RemoveScriptSlot()
4835         */
4836        void Instrument::RemoveScript(Script* pScript) {
4837            LoadScripts();
4838            for (int i = pScriptRefs->size() - 1; i >= 0; --i) {
4839                if ((*pScriptRefs)[i].script == pScript) {
4840                    pScriptRefs->erase( pScriptRefs->begin() + i );
4841                }
4842            }
4843        }
4844    
4845        /** @brief Instrument's amount of script slots.
4846         *
4847         * This method returns the amount of script slots this instrument currently
4848         * uses.
4849         *
4850         * A script slot is a reference of a real-time instrument script to be
4851         * executed by the sampler. The scripts will be executed by the sampler in
4852         * sequence of the slots. One (same) script may be referenced multiple
4853         * times in different slots.
4854         *
4855         * @note This is an own format extension which did not exist i.e. in the
4856         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4857         * gigedit.
4858         */
4859        uint Instrument::ScriptSlotCount() const {
4860            return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
4861        }
4862    
4863        /** @brief Whether script execution shall be skipped.
4864         *
4865         * Defines locally for the Script reference slot in the Instrument's Script
4866         * list, whether the script shall be skipped by the sampler regarding
4867         * execution.
4868         *
4869         * It is also possible to ignore exeuction of the script globally, for all
4870         * slots and for all instruments by setting Script::Bypass.
4871         *
4872         * @note This is an own format extension which did not exist i.e. in the
4873         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4874         * gigedit.
4875         *
4876         * @param index - index of the script slot on this instrument
4877         * @see Script::Bypass
4878         */
4879        bool Instrument::IsScriptSlotBypassed(uint index) {
4880            if (index >= ScriptSlotCount()) return false;
4881            return pScriptRefs ? pScriptRefs->at(index).bypass
4882                               : scriptPoolFileOffsets.at(index).bypass;
4883            
4884        }
4885    
4886        /** @brief Defines whether execution shall be skipped.
4887         *
4888         * You can call this method to define locally whether or whether not the
4889         * given script slot shall be executed by the sampler.
4890         *
4891         * @note This is an own format extension which did not exist i.e. in the
4892         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4893         * gigedit.
4894         *
4895         * @param index - script slot index on this instrument
4896         * @param bBypass - if true, the script slot will be skipped by the sampler
4897         * @see Script::Bypass
4898         */
4899        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
4900            if (index >= ScriptSlotCount()) return;
4901            if (pScriptRefs)
4902                pScriptRefs->at(index).bypass = bBypass;
4903            else
4904                scriptPoolFileOffsets.at(index).bypass = bBypass;
4905        }
4906    
4907        /**
4908         * Make a (semi) deep copy of the Instrument object given by @a orig
4909         * and assign it to this object.
4910         *
4911         * Note that all sample pointers referenced by @a orig are simply copied as
4912         * memory address. Thus the respective samples are shared, not duplicated!
4913         *
4914         * @param orig - original Instrument object to be copied from
4915         */
4916        void Instrument::CopyAssign(const Instrument* orig) {
4917            CopyAssign(orig, NULL);
4918        }
4919            
4920        /**
4921         * Make a (semi) deep copy of the Instrument object given by @a orig
4922         * and assign it to this object.
4923         *
4924         * @param orig - original Instrument object to be copied from
4925         * @param mSamples - crosslink map between the foreign file's samples and
4926         *                   this file's samples
4927         */
4928        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
4929            // handle base class
4930            // (without copying DLS region stuff)
4931            DLS::Instrument::CopyAssignCore(orig);
4932            
4933            // handle own member variables
4934            Attenuation = orig->Attenuation;
4935            EffectSend = orig->EffectSend;
4936            FineTune = orig->FineTune;
4937            PitchbendRange = orig->PitchbendRange;
4938            PianoReleaseMode = orig->PianoReleaseMode;
4939            DimensionKeyRange = orig->DimensionKeyRange;
4940            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
4941            pScriptRefs = orig->pScriptRefs;
4942            
4943            // free old midi rules
4944            for (int i = 0 ; pMidiRules[i] ; i++) {
4945                delete pMidiRules[i];
4946            }
4947            //TODO: MIDI rule copying
4948            pMidiRules[0] = NULL;
4949            
4950            // delete all old regions
4951            while (Regions) DeleteRegion(GetFirstRegion());
4952            // create new regions and copy them from original
4953            {
4954                RegionList::const_iterator it = orig->pRegions->begin();
4955                for (int i = 0; i < orig->Regions; ++i, ++it) {
4956                    Region* dstRgn = AddRegion();
4957                    //NOTE: Region does semi-deep copy !
4958                    dstRgn->CopyAssign(
4959                        static_cast<gig::Region*>(*it),
4960                        mSamples
4961                    );
4962                }
4963            }
4964    
4965            UpdateRegionKeyTable();
4966        }
4967    
4968    
4969  // *************** Group ***************  // *************** Group ***************
# Line 2858  namespace { Line 5003  namespace {
5003          }          }
5004          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5005          if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);          if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5006    
5007            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
5008                // v3 has a fixed list of 128 strings, find a free one
5009                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
5010                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
5011                        pNameChunk = ck;
5012                        break;
5013                    }
5014                }
5015            }
5016    
5017          // 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
5018          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
5019      }      }
# Line 2933  namespace { Line 5089  namespace {
5089  // *************** File ***************  // *************** File ***************
5090  // *  // *
5091    
5092      // File version 2.0, 1998-06-28      /// Reflects Gigasampler file format version 2.0 (1998-06-28).
5093      const DLS::version_t File::VERSION_2 = {      const DLS::version_t File::VERSION_2 = {
5094          0, 2, 19980628 & 0xffff, 19980628 >> 16          0, 2, 19980628 & 0xffff, 19980628 >> 16
5095      };      };
5096    
5097      // File version 3.0, 2003-03-31      /// Reflects Gigasampler file format version 3.0 (2003-03-31).
5098      const DLS::version_t File::VERSION_3 = {      const DLS::version_t File::VERSION_3 = {
5099          0, 3, 20030331 & 0xffff, 20030331 >> 16          0, 3, 20030331 & 0xffff, 20030331 >> 16
5100      };      };
5101    
5102      const DLS::Info::FixedStringLength File::FixedStringLengths[] = {      static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
5103          { CHUNK_ID_IARL, 256 },          { CHUNK_ID_IARL, 256 },
5104          { CHUNK_ID_IART, 128 },          { CHUNK_ID_IART, 128 },
5105          { CHUNK_ID_ICMS, 128 },          { CHUNK_ID_ICMS, 128 },
# Line 2965  namespace { Line 5121  namespace {
5121      };      };
5122    
5123      File::File() : DLS::File() {      File::File() : DLS::File() {
5124            bAutoLoad = true;
5125            *pVersion = VERSION_3;
5126          pGroups = NULL;          pGroups = NULL;
5127          pInfo->FixedStringLengths = FixedStringLengths;          pScriptGroups = NULL;
5128            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5129          pInfo->ArchivalLocation = String(256, ' ');          pInfo->ArchivalLocation = String(256, ' ');
5130    
5131          // add some mandatory chunks to get the file chunks in right          // add some mandatory chunks to get the file chunks in right
# Line 2979  namespace { Line 5138  namespace {
5138      }      }
5139    
5140      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5141            bAutoLoad = true;
5142          pGroups = NULL;          pGroups = NULL;
5143          pInfo->FixedStringLengths = FixedStringLengths;          pScriptGroups = NULL;
5144            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5145      }      }
5146    
5147      File::~File() {      File::~File() {
# Line 2993  namespace { Line 5154  namespace {
5154              }              }
5155              delete pGroups;              delete pGroups;
5156          }          }
5157            if (pScriptGroups) {
5158                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5159                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5160                while (iter != end) {
5161                    delete *iter;
5162                    ++iter;
5163                }
5164                delete pScriptGroups;
5165            }
5166      }      }
5167    
5168      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 3007  namespace { Line 5177  namespace {
5177          SamplesIterator++;          SamplesIterator++;
5178          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5179      }      }
5180        
5181        /**
5182         * Returns Sample object of @a index.
5183         *
5184         * @returns sample object or NULL if index is out of bounds
5185         */
5186        Sample* File::GetSample(uint index) {
5187            if (!pSamples) LoadSamples();
5188            if (!pSamples) return NULL;
5189            DLS::File::SampleList::iterator it = pSamples->begin();
5190            for (int i = 0; i < index; ++i) {
5191                ++it;
5192                if (it == pSamples->end()) return NULL;
5193            }
5194            if (it == pSamples->end()) return NULL;
5195            return static_cast<gig::Sample*>( *it );
5196        }
5197    
5198      /** @brief Add a new sample.      /** @brief Add a new sample.
5199       *       *
# Line 3033  namespace { Line 5220  namespace {
5220    
5221      /** @brief Delete a sample.      /** @brief Delete a sample.
5222       *       *
5223       * 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
5224       * to call Save() to make this persistent to the file.       * references to this sample from Regions and DimensionRegions will be
5225         * removed. You have to call Save() to make this persistent to the file.
5226       *       *
5227       * @param pSample - sample to delete       * @param pSample - sample to delete
5228       * @throws gig::Exception if given sample could not be found       * @throws gig::Exception if given sample could not be found
# Line 3046  namespace { Line 5234  namespace {
5234          if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation          if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
5235          pSamples->erase(iter);          pSamples->erase(iter);
5236          delete pSample;          delete pSample;
5237    
5238            SampleList::iterator tmp = SamplesIterator;
5239            // remove all references to the sample
5240            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5241                 instrument = GetNextInstrument()) {
5242                for (Region* region = instrument->GetFirstRegion() ; region ;
5243                     region = instrument->GetNextRegion()) {
5244    
5245                    if (region->GetSample() == pSample) region->SetSample(NULL);
5246    
5247                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
5248                        gig::DimensionRegion *d = region->pDimensionRegions[i];
5249                        if (d->pSample == pSample) d->pSample = NULL;
5250                    }
5251                }
5252            }
5253            SamplesIterator = tmp; // restore iterator
5254      }      }
5255    
5256      void File::LoadSamples() {      void File::LoadSamples() {
# Line 3136  namespace { Line 5341  namespace {
5341              progress_t subprogress;              progress_t subprogress;
5342              __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
5343              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
5344              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
5345                    GetFirstSample(&subprogress); // now force all samples to be loaded
5346              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
5347    
5348              // instrument loading subtask              // instrument loading subtask
# Line 3185  namespace { Line 5391  namespace {
5391         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
5392         return pInstrument;         return pInstrument;
5393      }      }
5394        
5395        /** @brief Add a duplicate of an existing instrument.
5396         *
5397         * Duplicates the instrument definition given by @a orig and adds it
5398         * to this file. This allows in an instrument editor application to
5399         * easily create variations of an instrument, which will be stored in
5400         * the same .gig file, sharing i.e. the same samples.
5401         *
5402         * Note that all sample pointers referenced by @a orig are simply copied as
5403         * memory address. Thus the respective samples are shared, not duplicated!
5404         *
5405         * You have to call Save() to make this persistent to the file.
5406         *
5407         * @param orig - original instrument to be copied
5408         * @returns duplicated copy of the given instrument
5409         */
5410        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
5411            Instrument* instr = AddInstrument();
5412            instr->CopyAssign(orig);
5413            return instr;
5414        }
5415        
5416        /** @brief Add content of another existing file.
5417         *
5418         * Duplicates the samples, groups and instruments of the original file
5419         * given by @a pFile and adds them to @c this File. In case @c this File is
5420         * a new one that you haven't saved before, then you have to call
5421         * SetFileName() before calling AddContentOf(), because this method will
5422         * automatically save this file during operation, which is required for
5423         * writing the sample waveform data by disk streaming.
5424         *
5425         * @param pFile - original file whose's content shall be copied from
5426         */
5427        void File::AddContentOf(File* pFile) {
5428            static int iCallCount = -1;
5429            iCallCount++;
5430            std::map<Group*,Group*> mGroups;
5431            std::map<Sample*,Sample*> mSamples;
5432            
5433            // clone sample groups
5434            for (int i = 0; pFile->GetGroup(i); ++i) {
5435                Group* g = AddGroup();
5436                g->Name =
5437                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5438                mGroups[pFile->GetGroup(i)] = g;
5439            }
5440            
5441            // clone samples (not waveform data here yet)
5442            for (int i = 0; pFile->GetSample(i); ++i) {
5443                Sample* s = AddSample();
5444                s->CopyAssignMeta(pFile->GetSample(i));
5445                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5446                mSamples[pFile->GetSample(i)] = s;
5447            }
5448            
5449            //BUG: For some reason this method only works with this additional
5450            //     Save() call in between here.
5451            //
5452            // Important: The correct one of the 2 Save() methods has to be called
5453            // here, depending on whether the file is completely new or has been
5454            // saved to disk already, otherwise it will result in data corruption.
5455            if (pRIFF->IsNew())
5456                Save(GetFileName());
5457            else
5458                Save();
5459            
5460            // clone instruments
5461            // (passing the crosslink table here for the cloned samples)
5462            for (int i = 0; pFile->GetInstrument(i); ++i) {
5463                Instrument* instr = AddInstrument();
5464                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5465            }
5466            
5467            // Mandatory: file needs to be saved to disk at this point, so this
5468            // file has the correct size and data layout for writing the samples'
5469            // waveform data to disk.
5470            Save();
5471            
5472            // clone samples' waveform data
5473            // (using direct read & write disk streaming)
5474            for (int i = 0; pFile->GetSample(i); ++i) {
5475                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5476            }
5477        }
5478    
5479      /** @brief Delete an instrument.      /** @brief Delete an instrument.
5480       *       *
# Line 3287  namespace { Line 5577  namespace {
5577          return NULL;          return NULL;
5578      }      }
5579    
5580        /**
5581         * Returns the group with the given group name.
5582         *
5583         * Note: group names don't have to be unique in the gig format! So there
5584         * can be multiple groups with the same name. This method will simply
5585         * return the first group found with the given name.
5586         *
5587         * @param name - name of the sought group
5588         * @returns sought group or NULL if there's no group with that name
5589         */
5590        Group* File::GetGroup(String name) {
5591            if (!pGroups) LoadGroups();
5592            GroupsIterator = pGroups->begin();
5593            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
5594                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
5595            return NULL;
5596        }
5597    
5598      Group* File::AddGroup() {      Group* File::AddGroup() {
5599          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5600          // there must always be at least one group          // there must always be at least one group
# Line 3350  namespace { Line 5658  namespace {
5658                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
5659                  while (ck) {                  while (ck) {
5660                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {
5661                            if (pVersion && pVersion->major == 3 &&
5662                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
5663    
5664                          pGroups->push_back(new Group(this, ck));                          pGroups->push_back(new Group(this, ck));
5665                      }                      }
5666                      ck = lst3gnl->GetNextSubChunk();                      ck = lst3gnl->GetNextSubChunk();
# Line 3364  namespace { Line 5675  namespace {
5675          }          }
5676      }      }
5677    
5678        /** @brief Get instrument script group (by index).
5679         *
5680         * Returns the real-time instrument script group with the given index.
5681         *
5682         * @param index - number of the sought group (0..n)
5683         * @returns sought script group or NULL if there's no such group
5684         */
5685        ScriptGroup* File::GetScriptGroup(uint index) {
5686            if (!pScriptGroups) LoadScriptGroups();
5687            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5688            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5689                if (i == index) return *it;
5690            return NULL;
5691        }
5692    
5693        /** @brief Get instrument script group (by name).
5694         *
5695         * Returns the first real-time instrument script group found with the given
5696         * group name. Note that group names may not necessarily be unique.
5697         *
5698         * @param name - name of the sought script group
5699         * @returns sought script group or NULL if there's no such group
5700         */
5701        ScriptGroup* File::GetScriptGroup(const String& name) {
5702            if (!pScriptGroups) LoadScriptGroups();
5703            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5704            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5705                if ((*it)->Name == name) return *it;
5706            return NULL;
5707        }
5708    
5709        /** @brief Add new instrument script group.
5710         *
5711         * Adds a new, empty real-time instrument script group to the file.
5712         *
5713         * You have to call Save() to make this persistent to the file.
5714         *
5715         * @return new empty script group
5716         */
5717        ScriptGroup* File::AddScriptGroup() {
5718            if (!pScriptGroups) LoadScriptGroups();
5719            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
5720            pScriptGroups->push_back(pScriptGroup);
5721            return pScriptGroup;
5722        }
5723    
5724        /** @brief Delete an instrument script group.
5725         *
5726         * This will delete the given real-time instrument script group and all its
5727         * instrument scripts it contains. References inside instruments that are
5728         * using the deleted scripts will be removed from the respective instruments
5729         * accordingly.
5730         *
5731         * You have to call Save() to make this persistent to the file.
5732         *
5733         * @param pScriptGroup - script group to delete
5734         * @throws gig::Exception if given script group could not be found
5735         */
5736        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
5737            if (!pScriptGroups) LoadScriptGroups();
5738            std::list<ScriptGroup*>::iterator iter =
5739                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
5740            if (iter == pScriptGroups->end())
5741                throw gig::Exception("Could not delete script group, could not find given script group");
5742            pScriptGroups->erase(iter);
5743            for (int i = 0; pScriptGroup->GetScript(i); ++i)
5744                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
5745            if (pScriptGroup->pList)
5746                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
5747            delete pScriptGroup;
5748        }
5749    
5750        void File::LoadScriptGroups() {
5751            if (pScriptGroups) return;
5752            pScriptGroups = new std::list<ScriptGroup*>;
5753            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
5754            if (lstLS) {
5755                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
5756                     lst = lstLS->GetNextSubList())
5757                {
5758                    if (lst->GetListType() == LIST_TYPE_RTIS) {
5759                        pScriptGroups->push_back(new ScriptGroup(this, lst));
5760                    }
5761                }
5762            }
5763        }
5764    
5765      /**      /**
5766       * Apply all the gig file's current instruments, samples, groups and settings       * Apply all the gig file's current instruments, samples, groups and settings
5767       * to the respective RIFF chunks. You have to call Save() to make changes       * to the respective RIFF chunks. You have to call Save() to make changes
# Line 3377  namespace { Line 5775  namespace {
5775      void File::UpdateChunks() {      void File::UpdateChunks() {
5776          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
5777    
5778            b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
5779    
5780            // update own gig format extension chunks
5781            // (not part of the GigaStudio 4 format)
5782            //
5783            // This must be performed before writing the chunks for instruments,
5784            // because the instruments' script slots will write the file offsets
5785            // of the respective instrument script chunk as reference.
5786            if (pScriptGroups) {
5787                RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
5788                if (pScriptGroups->empty()) {
5789                    if (lst3LS) pRIFF->DeleteSubChunk(lst3LS);
5790                } else {
5791                    if (!lst3LS) lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
5792    
5793                    // Update instrument script (group) chunks.
5794    
5795                    for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5796                         it != pScriptGroups->end(); ++it)
5797                    {
5798                        (*it)->UpdateChunks();
5799                    }
5800                }
5801            }
5802    
5803          // first update base class's chunks          // first update base class's chunks
5804          DLS::File::UpdateChunks();          DLS::File::UpdateChunks();
5805    
# Line 3392  namespace { Line 5815  namespace {
5815    
5816          // update group's chunks          // update group's chunks
5817          if (pGroups) {          if (pGroups) {
5818                // make sure '3gri' and '3gnl' list chunks exist
5819                // (before updating the Group chunks)
5820                RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
5821                if (!_3gri) {
5822                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
5823                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5824                }
5825                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5826                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5827    
5828                // v3: make sure the file has 128 3gnm chunks
5829                // (before updating the Group chunks)
5830                if (pVersion && pVersion->major == 3) {
5831                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
5832                    for (int i = 0 ; i < 128 ; i++) {
5833                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
5834                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
5835                    }
5836                }
5837    
5838              std::list<Group*>::iterator iter = pGroups->begin();              std::list<Group*>::iterator iter = pGroups->begin();
5839              std::list<Group*>::iterator end  = pGroups->end();              std::list<Group*>::iterator end  = pGroups->end();
5840              for (; iter != end; ++iter) {              for (; iter != end; ++iter) {
# Line 3440  namespace { Line 5883  namespace {
5883              int totnbusedchannels = 0;              int totnbusedchannels = 0;
5884              int totnbregions = 0;              int totnbregions = 0;
5885              int totnbdimregions = 0;              int totnbdimregions = 0;
5886                int totnbloops = 0;
5887              int instrumentIdx = 0;              int instrumentIdx = 0;
5888    
5889              memset(&pData[48], 0, sublen - 48);              memset(&pData[48], 0, sublen - 48);
# Line 3449  namespace { Line 5893  namespace {
5893                  int nbusedsamples = 0;                  int nbusedsamples = 0;
5894                  int nbusedchannels = 0;                  int nbusedchannels = 0;
5895                  int nbdimregions = 0;                  int nbdimregions = 0;
5896                    int nbloops = 0;
5897    
5898                  memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);                  memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
5899    
# Line 3472  namespace { Line 5917  namespace {
5917                                  }                                  }
5918                              }                              }
5919                          }                          }
5920                            if (d->SampleLoops) nbloops++;
5921                      }                      }
5922                      nbdimregions += region->DimensionRegions;                      nbdimregions += region->DimensionRegions;
5923                  }                  }
# Line 3482  namespace { Line 5928  namespace {
5928                  store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);                  store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
5929                  store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);                  store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
5930                  store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);                  store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
5931                  // next 12 bytes unknown                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
5932                    // next 8 bytes unknown
5933                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
5934                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
5935                  // next 4 bytes unknown                  // next 4 bytes unknown
5936    
5937                  totnbregions += instrument->Regions;                  totnbregions += instrument->Regions;
5938                  totnbdimregions += nbdimregions;                  totnbdimregions += nbdimregions;
5939                    totnbloops += nbloops;
5940                  instrumentIdx++;                  instrumentIdx++;
5941              }              }
5942              // first 4 bytes unknown - sometimes 0, sometimes length of einf part              // first 4 bytes unknown - sometimes 0, sometimes length of einf part
# Line 3498  namespace { Line 5946  namespace {
5946              store32(&pData[12], Instruments);              store32(&pData[12], Instruments);
5947              store32(&pData[16], totnbregions);              store32(&pData[16], totnbregions);
5948              store32(&pData[20], totnbdimregions);              store32(&pData[20], totnbdimregions);
5949              // next 12 bytes unknown              store32(&pData[24], totnbloops);
5950              // next 4 bytes unknown, always 0?              // next 8 bytes unknown
5951                // next 4 bytes unknown, not always 0
5952              store32(&pData[40], pSamples->size());              store32(&pData[40], pSamples->size());
5953              // next 4 bytes unknown              // next 4 bytes unknown
5954          }          }
# Line 3516  namespace { Line 5965  namespace {
5965          } else if (newFile) {          } else if (newFile) {
5966              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5967              _3crc->LoadChunkData();              _3crc->LoadChunkData();
5968    
5969                // the order of einf and 3crc is not the same in v2 and v3
5970                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5971          }          }
5972      }      }
5973        
5974        void File::UpdateFileOffsets() {
5975            DLS::File::UpdateFileOffsets();
5976    
5977            for (Instrument* instrument = GetFirstInstrument(); instrument;
5978                 instrument = GetNextInstrument())
5979            {
5980                instrument->UpdateScriptFileOffsets();
5981            }
5982        }
5983    
5984        /**
5985         * Enable / disable automatic loading. By default this properyt is
5986         * enabled and all informations are loaded automatically. However
5987         * loading all Regions, DimensionRegions and especially samples might
5988         * take a long time for large .gig files, and sometimes one might only
5989         * be interested in retrieving very superficial informations like the
5990         * amount of instruments and their names. In this case one might disable
5991         * automatic loading to avoid very slow response times.
5992         *
5993         * @e CAUTION: by disabling this property many pointers (i.e. sample
5994         * references) and informations will have invalid or even undefined
5995         * data! This feature is currently only intended for retrieving very
5996         * superficial informations in a very fast way. Don't use it to retrieve
5997         * details like synthesis informations or even to modify .gig files!
5998         */
5999        void File::SetAutoLoad(bool b) {
6000            bAutoLoad = b;
6001        }
6002    
6003        /**
6004         * Returns whether automatic loading is enabled.
6005         * @see SetAutoLoad()
6006         */
6007        bool File::GetAutoLoad() {
6008            return bAutoLoad;
6009        }
6010    
6011    
6012    

Legend:
Removed from v.1218  
changed lines
  Added in v.2639

  ViewVC Help
Powered by ViewVC