/[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 1192 by persson, Thu May 17 10:12:08 2007 UTC revision 2482 by schoenebeck, Mon Nov 25 02:22:38 2013 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-2013 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    
# Line 255  namespace { Line 256  namespace {
256    
257    
258    
259    // *************** Internal CRC-32 (Cyclic Redundancy Check) functions  ***************
260    // *
261    
262        static uint32_t* __initCRCTable() {
263            static uint32_t res[256];
264    
265            for (int i = 0 ; i < 256 ; i++) {
266                uint32_t c = i;
267                for (int j = 0 ; j < 8 ; j++) {
268                    c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
269                }
270                res[i] = c;
271            }
272            return res;
273        }
274    
275        static const uint32_t* __CRCTable = __initCRCTable();
276    
277        /**
278         * Initialize a CRC variable.
279         *
280         * @param crc - variable to be initialized
281         */
282        inline static void __resetCRC(uint32_t& crc) {
283            crc = 0xffffffff;
284        }
285    
286        /**
287         * Used to calculate checksums of the sample data in a gig file. The
288         * checksums are stored in the 3crc chunk of the gig file and
289         * automatically updated when a sample is written with Sample::Write().
290         *
291         * One should call __resetCRC() to initialize the CRC variable to be
292         * used before calling this function the first time.
293         *
294         * After initializing the CRC variable one can call this function
295         * arbitrary times, i.e. to split the overall CRC calculation into
296         * steps.
297         *
298         * Once the whole data was processed by __calculateCRC(), one should
299         * call __encodeCRC() to get the final CRC result.
300         *
301         * @param buf     - pointer to data the CRC shall be calculated of
302         * @param bufSize - size of the data to be processed
303         * @param crc     - variable the CRC sum shall be stored to
304         */
305        static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
306            for (int i = 0 ; i < bufSize ; i++) {
307                crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
308            }
309        }
310    
311        /**
312         * Returns the final CRC result.
313         *
314         * @param crc - variable previously passed to __calculateCRC()
315         */
316        inline static uint32_t __encodeCRC(const uint32_t& crc) {
317            return crc ^ 0xffffffff;
318        }
319    
320    
321    
322  // *************** Other Internal functions  ***************  // *************** Other Internal functions  ***************
323  // *  // *
324    
# Line 303  namespace { Line 367  namespace {
367       *                         is located, 0 otherwise       *                         is located, 0 otherwise
368       */       */
369      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
370          static const DLS::Info::FixedStringLength fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
371              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
372              { 0, 0 }              { 0, 0 }
373          };          };
374          pInfo->FixedStringLengths = fixedStringLengths;          pInfo->SetFixedStringLengths(fixedStringLengths);
375          Instances++;          Instances++;
376          FileNo = fileNo;          FileNo = fileNo;
377    
378            __resetCRC(crc);
379    
380          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
381          if (pCk3gix) {          if (pCk3gix) {
382              uint16_t iSampleGroup = pCk3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
# Line 342  namespace { Line 408  namespace {
408              Manufacturer  = 0;              Manufacturer  = 0;
409              Product       = 0;              Product       = 0;
410              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
411              MIDIUnityNote = 64;              MIDIUnityNote = 60;
412              FineTune      = 0;              FineTune      = 0;
413              SMPTEFormat   = smpte_format_no_offset;              SMPTEFormat   = smpte_format_no_offset;
414              SMPTEOffset   = 0;              SMPTEOffset   = 0;
# Line 388  namespace { Line 454  namespace {
454      }      }
455    
456      /**      /**
457         * Make a (semi) deep copy of the Sample object given by @a orig (without
458         * the actual waveform data) and assign it to this object.
459         *
460         * Discussion: copying .gig samples is a bit tricky. It requires three
461         * steps:
462         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
463         *    its new sample waveform data size.
464         * 2. Saving the file (done by File::Save()) so that it gains correct size
465         *    and layout for writing the actual wave form data directly to disc
466         *    in next step.
467         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
468         *
469         * @param orig - original Sample object to be copied from
470         */
471        void Sample::CopyAssignMeta(const Sample* orig) {
472            // handle base classes
473            DLS::Sample::CopyAssignCore(orig);
474            
475            // handle actual own attributes of this class
476            Manufacturer = orig->Manufacturer;
477            Product = orig->Product;
478            SamplePeriod = orig->SamplePeriod;
479            MIDIUnityNote = orig->MIDIUnityNote;
480            FineTune = orig->FineTune;
481            SMPTEFormat = orig->SMPTEFormat;
482            SMPTEOffset = orig->SMPTEOffset;
483            Loops = orig->Loops;
484            LoopID = orig->LoopID;
485            LoopType = orig->LoopType;
486            LoopStart = orig->LoopStart;
487            LoopEnd = orig->LoopEnd;
488            LoopSize = orig->LoopSize;
489            LoopFraction = orig->LoopFraction;
490            LoopPlayCount = orig->LoopPlayCount;
491            
492            // schedule resizing this sample to the given sample's size
493            Resize(orig->GetSize());
494        }
495    
496        /**
497         * Should be called after CopyAssignMeta() and File::Save() sequence.
498         * Read more about it in the discussion of CopyAssignMeta(). This method
499         * copies the actual waveform data by disk streaming.
500         *
501         * @e CAUTION: this method is currently not thread safe! During this
502         * operation the sample must not be used for other purposes by other
503         * threads!
504         *
505         * @param orig - original Sample object to be copied from
506         */
507        void Sample::CopyAssignWave(const Sample* orig) {
508            const int iReadAtOnce = 32*1024;
509            char* buf = new char[iReadAtOnce * orig->FrameSize];
510            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
511            unsigned long restorePos = pOrig->GetPos();
512            pOrig->SetPos(0);
513            SetPos(0);
514            for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;
515                               n = pOrig->Read(buf, iReadAtOnce))
516            {
517                Write(buf, n);
518            }
519            pOrig->SetPos(restorePos);
520            delete [] buf;
521        }
522    
523        /**
524       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
525       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
526       *       *
# Line 611  namespace { Line 744  namespace {
744          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
745          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
746          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
747            SetPos(0); // reset read position to begin of sample
748          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
749          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
750          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 648  namespace { Line 782  namespace {
782          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
783          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
784          RAMCache.Size   = 0;          RAMCache.Size   = 0;
785            RAMCache.NullExtensionSize = 0;
786      }      }
787    
788      /** @brief Resize sample.      /** @brief Resize sample.
# Line 740  namespace { Line 875  namespace {
875      /**      /**
876       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
877       */       */
878      unsigned long Sample::GetPos() {      unsigned long Sample::GetPos() const {
879          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
880          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
881      }      }
# Line 842  namespace { Line 977  namespace {
977                                  }                                  }
978    
979                                  // reverse the sample frames for backward playback                                  // reverse the sample frames for backward playback
980                                  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!
981                                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
982                              }                              }
983                          } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
984                          break;                          break;
# Line 1132  namespace { Line 1268  namespace {
1268       *       *
1269       * Note: there is currently no support for writing compressed samples.       * Note: there is currently no support for writing compressed samples.
1270       *       *
1271         * For 16 bit samples, the data in the source buffer should be
1272         * int16_t (using native endianness). For 24 bit, the buffer
1273         * should contain three bytes per sample, little-endian.
1274         *
1275       * @param pBuffer     - source buffer       * @param pBuffer     - source buffer
1276       * @param SampleCount - number of sample points to write       * @param SampleCount - number of sample points to write
1277       * @throws DLS::Exception if current sample size is too small       * @throws DLS::Exception if current sample size is too small
# Line 1140  namespace { Line 1280  namespace {
1280       */       */
1281      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1282          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1283          return DLS::Sample::Write(pBuffer, SampleCount);  
1284            // if this is the first write in this sample, reset the
1285            // checksum calculator
1286            if (pCkData->GetPos() == 0) {
1287                __resetCRC(crc);
1288            }
1289            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1290            unsigned long res;
1291            if (BitDepth == 24) {
1292                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1293            } else { // 16 bit
1294                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1295                                    : pCkData->Write(pBuffer, SampleCount, 2);
1296            }
1297            __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1298    
1299            // if this is the last write, update the checksum chunk in the
1300            // file
1301            if (pCkData->GetPos() == pCkData->GetSize()) {
1302                File* pFile = static_cast<File*>(GetParent());
1303                pFile->SetSampleChecksum(this, __encodeCRC(crc));
1304            }
1305            return res;
1306      }      }
1307    
1308      /**      /**
# Line 1216  namespace { Line 1378  namespace {
1378      uint                               DimensionRegion::Instances       = 0;      uint                               DimensionRegion::Instances       = 0;
1379      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1380    
1381      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1382          Instances++;          Instances++;
1383    
1384          pSample = NULL;          pSample = NULL;
1385            pRegion = pParent;
1386    
1387            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1388            else memset(&Crossfade, 0, 4);
1389    
         memcpy(&Crossfade, &SamplerOptions, 4);  
1390          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1391    
1392          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
# Line 1335  namespace { Line 1500  namespace {
1500                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1501              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1502              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1503                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1504              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1505              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1506              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1385  namespace { Line 1550  namespace {
1550              LFO1ControlDepth                = 0;              LFO1ControlDepth                = 0;
1551              LFO3ControlDepth                = 0;              LFO3ControlDepth                = 0;
1552              EG1Attack                       = 0.0;              EG1Attack                       = 0.0;
1553              EG1Decay1                       = 0.0;              EG1Decay1                       = 0.005;
1554              EG1Sustain                      = 0;              EG1Sustain                      = 1000;
1555              EG1Release                      = 0.0;              EG1Release                      = 0.3;
1556              EG1Controller.type              = eg1_ctrl_t::type_none;              EG1Controller.type              = eg1_ctrl_t::type_none;
1557              EG1Controller.controller_number = 0;              EG1Controller.controller_number = 0;
1558              EG1ControllerInvert             = false;              EG1ControllerInvert             = false;
# Line 1402  namespace { Line 1567  namespace {
1567              EG2ControllerReleaseInfluence   = 0;              EG2ControllerReleaseInfluence   = 0;
1568              LFO1Frequency                   = 1.0;              LFO1Frequency                   = 1.0;
1569              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1570              EG2Decay1                       = 0.0;              EG2Decay1                       = 0.005;
1571              EG2Sustain                      = 0;              EG2Sustain                      = 1000;
1572              EG2Release                      = 0.0;              EG2Release                      = 0.3;
1573              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1574              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1575              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
1576              EG1Decay2                       = 0.0;              EG1Decay2                       = 0.0;
1577              EG1InfiniteSustain              = false;              EG1InfiniteSustain              = true;
1578              EG1PreAttack                    = 1000;              EG1PreAttack                    = 0;
1579              EG2Decay2                       = 0.0;              EG2Decay2                       = 0.0;
1580              EG2InfiniteSustain              = false;              EG2InfiniteSustain              = true;
1581              EG2PreAttack                    = 1000;              EG2PreAttack                    = 0;
1582              VelocityResponseCurve           = curve_type_nonlinear;              VelocityResponseCurve           = curve_type_nonlinear;
1583              VelocityResponseDepth           = 3;              VelocityResponseDepth           = 3;
1584              ReleaseVelocityResponseCurve    = curve_type_nonlinear;              ReleaseVelocityResponseCurve    = curve_type_nonlinear;
# Line 1456  namespace { Line 1621  namespace {
1621              VCFVelocityDynamicRange         = 0x04;              VCFVelocityDynamicRange         = 0x04;
1622              VCFVelocityCurve                = curve_type_linear;              VCFVelocityCurve                = curve_type_linear;
1623              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1624              memset(DimensionUpperLimits, 0, 8);              memset(DimensionUpperLimits, 127, 8);
1625          }          }
1626    
1627          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1628                                                       VelocityResponseDepth,                                                       VelocityResponseDepth,
1629                                                       VelocityResponseCurveScaling);                                                       VelocityResponseCurveScaling);
1630    
1631          curve_type_t curveType = ReleaseVelocityResponseCurve;          pVelocityReleaseTable = GetReleaseVelocityTable(
1632          uint8_t depth = ReleaseVelocityResponseDepth;                                      ReleaseVelocityResponseCurve,
1633                                        ReleaseVelocityResponseDepth
1634                                    );
1635    
1636            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1637                                                          VCFVelocityDynamicRange,
1638                                                          VCFVelocityScale,
1639                                                          VCFCutoffController);
1640    
1641          // this models a strange behaviour or bug in GSt: two of the          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1642          // velocity response curves for release time are not used even          VelocityTable = 0;
1643          // 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);  
1644    
1645          curveType = VCFVelocityCurve;      /*
1646          depth = VCFVelocityDynamicRange;       * Constructs a DimensionRegion by copying all parameters from
1647         * another DimensionRegion
1648         */
1649        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1650            Instances++;
1651            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1652            *this = src; // default memberwise shallow copy of all parameters
1653            pParentList = _3ewl; // restore the chunk pointer
1654    
1655            // deep copy of owned structures
1656            if (src.VelocityTable) {
1657                VelocityTable = new uint8_t[128];
1658                for (int k = 0 ; k < 128 ; k++)
1659                    VelocityTable[k] = src.VelocityTable[k];
1660            }
1661            if (src.pSampleLoops) {
1662                pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1663                for (int k = 0 ; k < src.SampleLoops ; k++)
1664                    pSampleLoops[k] = src.pSampleLoops[k];
1665            }
1666        }
1667        
1668        /**
1669         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1670         * and assign it to this object.
1671         *
1672         * Note that all sample pointers referenced by @a orig are simply copied as
1673         * memory address. Thus the respective samples are shared, not duplicated!
1674         *
1675         * @param orig - original DimensionRegion object to be copied from
1676         */
1677        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1678            CopyAssign(orig, NULL);
1679        }
1680    
1681          // even stranger GSt: two of the velocity response curves for      /**
1682          // filter cutoff are not used, instead another special curve       * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1683          // is chosen. This curve is not used anywhere else.       * and assign it to this object.
1684          if ((curveType == curve_type_nonlinear && depth == 0) ||       *
1685              (curveType == curve_type_special   && depth == 4)) {       * @param orig - original DimensionRegion object to be copied from
1686              curveType = curve_type_special;       * @param mSamples - crosslink map between the foreign file's samples and
1687              depth = 5;       *                   this file's samples
1688         */
1689        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1690            // delete all allocated data first
1691            if (VelocityTable) delete [] VelocityTable;
1692            if (pSampleLoops) delete [] pSampleLoops;
1693            
1694            // backup parent list pointer
1695            RIFF::List* p = pParentList;
1696            
1697            gig::Sample* pOriginalSample = pSample;
1698            gig::Region* pOriginalRegion = pRegion;
1699            
1700            //NOTE: copy code copied from assignment constructor above, see comment there as well
1701            
1702            *this = *orig; // default memberwise shallow copy of all parameters
1703            pParentList = p; // restore the chunk pointer
1704            
1705            // only take the raw sample reference & parent region reference if the
1706            // two DimensionRegion objects are part of the same file
1707            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1708                pRegion = pOriginalRegion;
1709                pSample = pOriginalSample;
1710            }
1711            
1712            if (mSamples && mSamples->count(orig->pSample)) {
1713                pSample = mSamples->find(orig->pSample)->second;
1714            }
1715    
1716            // deep copy of owned structures
1717            if (orig->VelocityTable) {
1718                VelocityTable = new uint8_t[128];
1719                for (int k = 0 ; k < 128 ; k++)
1720                    VelocityTable[k] = orig->VelocityTable[k];
1721            }
1722            if (orig->pSampleLoops) {
1723                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1724                for (int k = 0 ; k < orig->SampleLoops ; k++)
1725                    pSampleLoops[k] = orig->pSampleLoops[k];
1726          }          }
1727          pVelocityCutoffTable = GetVelocityTable(curveType, depth,      }
                                                 VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);  
1728    
1729        /**
1730         * Updates the respective member variable and updates @c SampleAttenuation
1731         * which depends on this value.
1732         */
1733        void DimensionRegion::SetGain(int32_t gain) {
1734            DLS::Sampler::SetGain(gain);
1735          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
         VelocityTable = 0;  
1736      }      }
1737    
1738      /**      /**
# Line 1505  namespace { Line 1746  namespace {
1746          // first update base class's chunk          // first update base class's chunk
1747          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks();
1748    
1749            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1750            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1751            pData[12] = Crossfade.in_start;
1752            pData[13] = Crossfade.in_end;
1753            pData[14] = Crossfade.out_start;
1754            pData[15] = Crossfade.out_end;
1755    
1756          // make sure '3ewa' chunk exists          // make sure '3ewa' chunk exists
1757          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1758          if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);          if (!_3ewa) {
1759          uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();              File* pFile = (File*) GetParent()->GetParent()->GetParent();
1760                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1761                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1762            }
1763            pData = (uint8_t*) _3ewa->LoadChunkData();
1764    
1765          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1766    
# Line 1554  namespace { Line 1806  namespace {
1806          pData[44] = eg1ctl;          pData[44] = eg1ctl;
1807    
1808          const uint8_t eg1ctrloptions =          const uint8_t eg1ctrloptions =
1809              (EG1ControllerInvert) ? 0x01 : 0x00 |              (EG1ControllerInvert ? 0x01 : 0x00) |
1810              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1811              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1812              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
# Line 1564  namespace { Line 1816  namespace {
1816          pData[46] = eg2ctl;          pData[46] = eg2ctl;
1817    
1818          const uint8_t eg2ctrloptions =          const uint8_t eg2ctrloptions =
1819              (EG2ControllerInvert) ? 0x01 : 0x00 |              (EG2ControllerInvert ? 0x01 : 0x00) |
1820              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1821              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1822              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
# Line 1714  namespace { Line 1966  namespace {
1966          }          }
1967    
1968          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1969                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1970          pData[116] = eg3depth;          store16(&pData[116], eg3depth);
1971    
1972          // next 2 bytes unknown          // next 2 bytes unknown
1973    
# Line 1742  namespace { Line 1994  namespace {
1994          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1995          pData[131] = eg1hold;          pData[131] = eg1hold;
1996    
1997          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */          const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
1998                                    (VCFCutoff & 0x7f);   /* lower 7 bits */                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
1999          pData[132] = vcfcutoff;          pData[132] = vcfcutoff;
2000    
2001          pData[133] = VCFCutoffController;          pData[133] = VCFCutoffController;
2002    
2003          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
2004                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
2005          pData[134] = vcfvelscale;          pData[134] = vcfvelscale;
2006    
2007          // next byte unknown          // next byte unknown
2008    
2009          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */          const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
2010                                       (VCFResonance & 0x7f); /* lower 7 bits */                                       (VCFResonance & 0x7f); /* lower 7 bits */
2011          pData[136] = vcfresonance;          pData[136] = vcfresonance;
2012    
2013          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
2014                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2015          pData[137] = vcfbreakpoint;          pData[137] = vcfbreakpoint;
2016    
2017          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2018                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2019          pData[138] = vcfvelocity;          pData[138] = vcfvelocity;
2020    
# Line 1774  namespace { Line 2026  namespace {
2026          }          }
2027      }      }
2028    
2029        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2030            curve_type_t curveType = releaseVelocityResponseCurve;
2031            uint8_t depth = releaseVelocityResponseDepth;
2032            // this models a strange behaviour or bug in GSt: two of the
2033            // velocity response curves for release time are not used even
2034            // if specified, instead another curve is chosen.
2035            if ((curveType == curve_type_nonlinear && depth == 0) ||
2036                (curveType == curve_type_special   && depth == 4)) {
2037                curveType = curve_type_nonlinear;
2038                depth = 3;
2039            }
2040            return GetVelocityTable(curveType, depth, 0);
2041        }
2042    
2043        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2044                                                        uint8_t vcfVelocityDynamicRange,
2045                                                        uint8_t vcfVelocityScale,
2046                                                        vcf_cutoff_ctrl_t vcfCutoffController)
2047        {
2048            curve_type_t curveType = vcfVelocityCurve;
2049            uint8_t depth = vcfVelocityDynamicRange;
2050            // even stranger GSt: two of the velocity response curves for
2051            // filter cutoff are not used, instead another special curve
2052            // is chosen. This curve is not used anywhere else.
2053            if ((curveType == curve_type_nonlinear && depth == 0) ||
2054                (curveType == curve_type_special   && depth == 4)) {
2055                curveType = curve_type_special;
2056                depth = 5;
2057            }
2058            return GetVelocityTable(curveType, depth,
2059                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2060                                        ? vcfVelocityScale : 0);
2061        }
2062    
2063      // 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
2064      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)
2065      {      {
# Line 1789  namespace { Line 2075  namespace {
2075          return table;          return table;
2076      }      }
2077    
2078        Region* DimensionRegion::GetParent() const {
2079            return pRegion;
2080        }
2081    
2082      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2083          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2084          switch (EncodedController) {          switch (EncodedController) {
# Line 2042  namespace { Line 2332  namespace {
2332          return pVelocityCutoffTable[MIDIKeyVelocity];          return pVelocityCutoffTable[MIDIKeyVelocity];
2333      }      }
2334    
2335        /**
2336         * Updates the respective member variable and the lookup table / cache
2337         * that depends on this value.
2338         */
2339        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2340            pVelocityAttenuationTable =
2341                GetVelocityTable(
2342                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2343                );
2344            VelocityResponseCurve = curve;
2345        }
2346    
2347        /**
2348         * Updates the respective member variable and the lookup table / cache
2349         * that depends on this value.
2350         */
2351        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2352            pVelocityAttenuationTable =
2353                GetVelocityTable(
2354                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2355                );
2356            VelocityResponseDepth = depth;
2357        }
2358    
2359        /**
2360         * Updates the respective member variable and the lookup table / cache
2361         * that depends on this value.
2362         */
2363        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2364            pVelocityAttenuationTable =
2365                GetVelocityTable(
2366                    VelocityResponseCurve, VelocityResponseDepth, scaling
2367                );
2368            VelocityResponseCurveScaling = scaling;
2369        }
2370    
2371        /**
2372         * Updates the respective member variable and the lookup table / cache
2373         * that depends on this value.
2374         */
2375        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2376            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2377            ReleaseVelocityResponseCurve = curve;
2378        }
2379    
2380        /**
2381         * Updates the respective member variable and the lookup table / cache
2382         * that depends on this value.
2383         */
2384        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2385            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2386            ReleaseVelocityResponseDepth = depth;
2387        }
2388    
2389        /**
2390         * Updates the respective member variable and the lookup table / cache
2391         * that depends on this value.
2392         */
2393        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2394            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2395            VCFCutoffController = controller;
2396        }
2397    
2398        /**
2399         * Updates the respective member variable and the lookup table / cache
2400         * that depends on this value.
2401         */
2402        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2403            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2404            VCFVelocityCurve = curve;
2405        }
2406    
2407        /**
2408         * Updates the respective member variable and the lookup table / cache
2409         * that depends on this value.
2410         */
2411        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2412            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2413            VCFVelocityDynamicRange = range;
2414        }
2415    
2416        /**
2417         * Updates the respective member variable and the lookup table / cache
2418         * that depends on this value.
2419         */
2420        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2421            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2422            VCFVelocityScale = scaling;
2423        }
2424    
2425      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) {
2426    
2427          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 2125  namespace { Line 2505  namespace {
2505    
2506          // Actual Loading          // Actual Loading
2507    
2508            if (!file->GetAutoLoad()) return;
2509    
2510          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2511    
2512          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2133  namespace { Line 2515  namespace {
2515              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2516                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2517                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2518                  _3lnk->ReadUint8(); // probably the position of the dimension                  _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2519                  _3lnk->ReadUint8(); // unknown                  _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2520                  uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)                  uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2521                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2522                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
# Line 2168  namespace { Line 2550  namespace {
2550              else              else
2551                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
2552    
2553              // load sample references              // load sample references (if auto loading is enabled)
2554              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
2555                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
2556                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2557                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2558                    }
2559                    GetSample(); // load global region sample reference
2560              }              }
             GetSample(); // load global region sample reference  
2561          } else {          } else {
2562              DimensionRegions = 0;              DimensionRegions = 0;
2563              for (int i = 0 ; i < 8 ; i++) {              for (int i = 0 ; i < 8 ; i++) {
# Line 2188  namespace { Line 2572  namespace {
2572              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2573              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2574              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2575              pDimensionRegions[0] = new DimensionRegion(_3ewl);              pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
2576              DimensionRegions = 1;              DimensionRegions = 1;
2577          }          }
2578      }      }
# Line 2218  namespace { Line 2602  namespace {
2602          }          }
2603    
2604          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
2605          const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;          bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
2606          const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;          const int iMaxDimensions =  version3 ? 8 : 5;
2607            const int iMaxDimensionRegions = version3 ? 256 : 32;
2608    
2609          // make sure '3lnk' chunk exists          // make sure '3lnk' chunk exists
2610          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2611          if (!_3lnk) {          if (!_3lnk) {
2612              const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;              const int _3lnkChunkSize = version3 ? 1092 : 172;
2613              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2614              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
2615    
# Line 2235  namespace { Line 2620  namespace {
2620          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
2621          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2622          store32(&pData[0], DimensionRegions);          store32(&pData[0], DimensionRegions);
2623            int shift = 0;
2624          for (int i = 0; i < iMaxDimensions; i++) {          for (int i = 0; i < iMaxDimensions; i++) {
2625              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2626              pData[5 + i * 8] = pDimensionDefinitions[i].bits;              pData[5 + i * 8] = pDimensionDefinitions[i].bits;
2627              // next 2 bytes unknown              pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
2628                pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
2629              pData[8 + i * 8] = pDimensionDefinitions[i].zones;              pData[8 + i * 8] = pDimensionDefinitions[i].zones;
2630              // next 3 bytes unknown              // next 3 bytes unknown, always zero?
2631    
2632                shift += pDimensionDefinitions[i].bits;
2633          }          }
2634    
2635          // update wave pool table in '3lnk' chunk          // update wave pool table in '3lnk' chunk
2636          const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;          const int iWavePoolOffset = version3 ? 68 : 44;
2637          for (uint i = 0; i < iMaxDimensionRegions; i++) {          for (uint i = 0; i < iMaxDimensionRegions; i++) {
2638              int iWaveIndex = -1;              int iWaveIndex = -1;
2639              if (i < DimensionRegions) {              if (i < DimensionRegions) {
# Line 2257  namespace { Line 2646  namespace {
2646                          break;                          break;
2647                      }                      }
2648                  }                  }
                 if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");  
2649              }              }
2650              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
2651          }          }
# Line 2270  namespace { Line 2658  namespace {
2658              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
2659              while (_3ewl) {              while (_3ewl) {
2660                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
2661                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
2662                      dimensionRegionNr++;                      dimensionRegionNr++;
2663                  }                  }
2664                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 2279  namespace { Line 2667  namespace {
2667          }          }
2668      }      }
2669    
2670        void Region::SetKeyRange(uint16_t Low, uint16_t High) {
2671            // update KeyRange struct and make sure regions are in correct order
2672            DLS::Region::SetKeyRange(Low, High);
2673            // update Region key table for fast lookup
2674            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
2675        }
2676    
2677      void Region::UpdateVelocityTable() {      void Region::UpdateVelocityTable() {
2678          // get velocity dimension's index          // get velocity dimension's index
2679          int veldim = -1;          int veldim = -1;
# Line 2384  namespace { Line 2779  namespace {
2779              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2780                  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");
2781    
2782            // pos is where the new dimension should be placed, normally
2783            // last in list, except for the samplechannel dimension which
2784            // has to be first in list
2785            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
2786            int bitpos = 0;
2787            for (int i = 0 ; i < pos ; i++)
2788                bitpos += pDimensionDefinitions[i].bits;
2789    
2790            // make room for the new dimension
2791            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
2792            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
2793                for (int j = Dimensions ; j > pos ; j--) {
2794                    pDimensionRegions[i]->DimensionUpperLimits[j] =
2795                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
2796                }
2797            }
2798    
2799          // assign definition of new dimension          // assign definition of new dimension
2800          pDimensionDefinitions[Dimensions] = *pDimDef;          pDimensionDefinitions[pos] = *pDimDef;
2801    
2802          // auto correct certain dimension definition fields (where possible)          // auto correct certain dimension definition fields (where possible)
2803          pDimensionDefinitions[Dimensions].split_type  =          pDimensionDefinitions[pos].split_type  =
2804              __resolveSplitType(pDimensionDefinitions[Dimensions].dimension);              __resolveSplitType(pDimensionDefinitions[pos].dimension);
2805          pDimensionDefinitions[Dimensions].zone_size =          pDimensionDefinitions[pos].zone_size =
2806              __resolveZoneSize(pDimensionDefinitions[Dimensions]);              __resolveZoneSize(pDimensionDefinitions[pos]);
2807    
2808          // create new dimension region(s) for this new dimension          // create new dimension region(s) for this new dimension, and make
2809          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {          // sure that the dimension regions are placed correctly in both the
2810              //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
2811              RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);          RIFF::Chunk* moveTo = NULL;
2812              pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);          RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2813              DimensionRegions++;          for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
2814                for (int k = 0 ; k < (1 << bitpos) ; k++) {
2815                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
2816                }
2817                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
2818                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
2819                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
2820                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
2821                        // create a new dimension region and copy all parameter values from
2822                        // an existing dimension region
2823                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
2824                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
2825    
2826                        DimensionRegions++;
2827                    }
2828                }
2829                moveTo = pDimensionRegions[i]->pParentList;
2830            }
2831    
2832            // initialize the upper limits for this dimension
2833            int mask = (1 << bitpos) - 1;
2834            for (int z = 0 ; z < pDimDef->zones ; z++) {
2835                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
2836                for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
2837                    pDimensionRegions[((i & ~mask) << pDimDef->bits) |
2838                                      (z << bitpos) |
2839                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
2840                }
2841          }          }
2842    
2843          Dimensions++;          Dimensions++;
# Line 2441  namespace { Line 2880  namespace {
2880          for (int i = iDimensionNr + 1; i < Dimensions; i++)          for (int i = iDimensionNr + 1; i < Dimensions; i++)
2881              iUpperBits += pDimensionDefinitions[i].bits;              iUpperBits += pDimensionDefinitions[i].bits;
2882    
2883            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2884    
2885          // delete dimension regions which belong to the given dimension          // delete dimension regions which belong to the given dimension
2886          // (that is where the dimension's bit > 0)          // (that is where the dimension's bit > 0)
2887          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
# Line 2449  namespace { Line 2890  namespace {
2890                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2891                                      iObsoleteBit << iLowerBits |                                      iObsoleteBit << iLowerBits |
2892                                      iLowerBit;                                      iLowerBit;
2893    
2894                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
2895                      delete pDimensionRegions[iToDelete];                      delete pDimensionRegions[iToDelete];
2896                      pDimensionRegions[iToDelete] = NULL;                      pDimensionRegions[iToDelete] = NULL;
2897                      DimensionRegions--;                      DimensionRegions--;
# Line 2469  namespace { Line 2912  namespace {
2912              }              }
2913          }          }
2914    
2915            // remove the this dimension from the upper limits arrays
2916            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
2917                DimensionRegion* d = pDimensionRegions[j];
2918                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2919                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
2920                }
2921                d->DimensionUpperLimits[Dimensions - 1] = 127;
2922            }
2923    
2924          // 'remove' dimension definition          // 'remove' dimension definition
2925          for (int i = iDimensionNr + 1; i < Dimensions; i++) {          for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2926              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
# Line 2602  namespace { Line 3054  namespace {
3054          }          }
3055          return NULL;          return NULL;
3056      }      }
3057        
3058        /**
3059         * Make a (semi) deep copy of the Region object given by @a orig
3060         * and assign it to this object.
3061         *
3062         * Note that all sample pointers referenced by @a orig are simply copied as
3063         * memory address. Thus the respective samples are shared, not duplicated!
3064         *
3065         * @param orig - original Region object to be copied from
3066         */
3067        void Region::CopyAssign(const Region* orig) {
3068            CopyAssign(orig, NULL);
3069        }
3070        
3071        /**
3072         * Make a (semi) deep copy of the Region object given by @a orig and
3073         * assign it to this object
3074         *
3075         * @param mSamples - crosslink map between the foreign file's samples and
3076         *                   this file's samples
3077         */
3078        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3079            // handle base classes
3080            DLS::Region::CopyAssign(orig);
3081            
3082            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3083                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3084            }
3085            
3086            // handle own member variables
3087            for (int i = Dimensions - 1; i >= 0; --i) {
3088                DeleteDimension(&pDimensionDefinitions[i]);
3089            }
3090            Layers = 0; // just to be sure
3091            for (int i = 0; i < orig->Dimensions; i++) {
3092                // we need to copy the dim definition here, to avoid the compiler
3093                // complaining about const-ness issue
3094                dimension_def_t def = orig->pDimensionDefinitions[i];
3095                AddDimension(&def);
3096            }
3097            for (int i = 0; i < 256; i++) {
3098                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3099                    pDimensionRegions[i]->CopyAssign(
3100                        orig->pDimensionRegions[i],
3101                        mSamples
3102                    );
3103                }
3104            }
3105            Layers = orig->Layers;
3106        }
3107    
3108    
3109    // *************** MidiRule ***************
3110    // *
3111    
3112        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3113            _3ewg->SetPos(36);
3114            Triggers = _3ewg->ReadUint8();
3115            _3ewg->SetPos(40);
3116            ControllerNumber = _3ewg->ReadUint8();
3117            _3ewg->SetPos(46);
3118            for (int i = 0 ; i < Triggers ; i++) {
3119                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3120                pTriggers[i].Descending = _3ewg->ReadUint8();
3121                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3122                pTriggers[i].Key = _3ewg->ReadUint8();
3123                pTriggers[i].NoteOff = _3ewg->ReadUint8();
3124                pTriggers[i].Velocity = _3ewg->ReadUint8();
3125                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3126                _3ewg->ReadUint8();
3127            }
3128        }
3129    
3130        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3131            ControllerNumber(0),
3132            Triggers(0) {
3133        }
3134    
3135        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3136            pData[32] = 4;
3137            pData[33] = 16;
3138            pData[36] = Triggers;
3139            pData[40] = ControllerNumber;
3140            for (int i = 0 ; i < Triggers ; i++) {
3141                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3142                pData[47 + i * 8] = pTriggers[i].Descending;
3143                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3144                pData[49 + i * 8] = pTriggers[i].Key;
3145                pData[50 + i * 8] = pTriggers[i].NoteOff;
3146                pData[51 + i * 8] = pTriggers[i].Velocity;
3147                pData[52 + i * 8] = pTriggers[i].OverridePedal;
3148            }
3149        }
3150    
3151        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3152            _3ewg->SetPos(36);
3153            LegatoSamples = _3ewg->ReadUint8(); // always 12
3154            _3ewg->SetPos(40);
3155            BypassUseController = _3ewg->ReadUint8();
3156            BypassKey = _3ewg->ReadUint8();
3157            BypassController = _3ewg->ReadUint8();
3158            ThresholdTime = _3ewg->ReadUint16();
3159            _3ewg->ReadInt16();
3160            ReleaseTime = _3ewg->ReadUint16();
3161            _3ewg->ReadInt16();
3162            KeyRange.low = _3ewg->ReadUint8();
3163            KeyRange.high = _3ewg->ReadUint8();
3164            _3ewg->SetPos(64);
3165            ReleaseTriggerKey = _3ewg->ReadUint8();
3166            AltSustain1Key = _3ewg->ReadUint8();
3167            AltSustain2Key = _3ewg->ReadUint8();
3168        }
3169    
3170        MidiRuleLegato::MidiRuleLegato() :
3171            LegatoSamples(12),
3172            BypassUseController(false),
3173            BypassKey(0),
3174            BypassController(1),
3175            ThresholdTime(20),
3176            ReleaseTime(20),
3177            ReleaseTriggerKey(0),
3178            AltSustain1Key(0),
3179            AltSustain2Key(0)
3180        {
3181            KeyRange.low = KeyRange.high = 0;
3182        }
3183    
3184        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
3185            pData[32] = 0;
3186            pData[33] = 16;
3187            pData[36] = LegatoSamples;
3188            pData[40] = BypassUseController;
3189            pData[41] = BypassKey;
3190            pData[42] = BypassController;
3191            store16(&pData[43], ThresholdTime);
3192            store16(&pData[47], ReleaseTime);
3193            pData[51] = KeyRange.low;
3194            pData[52] = KeyRange.high;
3195            pData[64] = ReleaseTriggerKey;
3196            pData[65] = AltSustain1Key;
3197            pData[66] = AltSustain2Key;
3198        }
3199    
3200        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
3201            _3ewg->SetPos(36);
3202            Articulations = _3ewg->ReadUint8();
3203            int flags = _3ewg->ReadUint8();
3204            Polyphonic = flags & 8;
3205            Chained = flags & 4;
3206            Selector = (flags & 2) ? selector_controller :
3207                (flags & 1) ? selector_key_switch : selector_none;
3208            Patterns = _3ewg->ReadUint8();
3209            _3ewg->ReadUint8(); // chosen row
3210            _3ewg->ReadUint8(); // unknown
3211            _3ewg->ReadUint8(); // unknown
3212            _3ewg->ReadUint8(); // unknown
3213            KeySwitchRange.low = _3ewg->ReadUint8();
3214            KeySwitchRange.high = _3ewg->ReadUint8();
3215            Controller = _3ewg->ReadUint8();
3216            PlayRange.low = _3ewg->ReadUint8();
3217            PlayRange.high = _3ewg->ReadUint8();
3218    
3219            int n = std::min(int(Articulations), 32);
3220            for (int i = 0 ; i < n ; i++) {
3221                _3ewg->ReadString(pArticulations[i], 32);
3222            }
3223            _3ewg->SetPos(1072);
3224            n = std::min(int(Patterns), 32);
3225            for (int i = 0 ; i < n ; i++) {
3226                _3ewg->ReadString(pPatterns[i].Name, 16);
3227                pPatterns[i].Size = _3ewg->ReadUint8();
3228                _3ewg->Read(&pPatterns[i][0], 1, 32);
3229            }
3230        }
3231    
3232        MidiRuleAlternator::MidiRuleAlternator() :
3233            Articulations(0),
3234            Patterns(0),
3235            Selector(selector_none),
3236            Controller(0),
3237            Polyphonic(false),
3238            Chained(false)
3239        {
3240            PlayRange.low = PlayRange.high = 0;
3241            KeySwitchRange.low = KeySwitchRange.high = 0;
3242        }
3243    
3244        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
3245            pData[32] = 3;
3246            pData[33] = 16;
3247            pData[36] = Articulations;
3248            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
3249                (Selector == selector_controller ? 2 :
3250                 (Selector == selector_key_switch ? 1 : 0));
3251            pData[38] = Patterns;
3252    
3253            pData[43] = KeySwitchRange.low;
3254            pData[44] = KeySwitchRange.high;
3255            pData[45] = Controller;
3256            pData[46] = PlayRange.low;
3257            pData[47] = PlayRange.high;
3258    
3259            char* str = reinterpret_cast<char*>(pData);
3260            int pos = 48;
3261            int n = std::min(int(Articulations), 32);
3262            for (int i = 0 ; i < n ; i++, pos += 32) {
3263                strncpy(&str[pos], pArticulations[i].c_str(), 32);
3264            }
3265    
3266            pos = 1072;
3267            n = std::min(int(Patterns), 32);
3268            for (int i = 0 ; i < n ; i++, pos += 49) {
3269                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
3270                pData[pos + 16] = pPatterns[i].Size;
3271                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
3272            }
3273        }
3274    
3275  // *************** Instrument ***************  // *************** Instrument ***************
3276  // *  // *
3277    
3278      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) {
3279          static const DLS::Info::FixedStringLength fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
3280              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
3281              { CHUNK_ID_ISFT, 12 },              { CHUNK_ID_ISFT, 12 },
3282              { 0, 0 }              { 0, 0 }
3283          };          };
3284          pInfo->FixedStringLengths = fixedStringLengths;          pInfo->SetFixedStringLengths(fixedStringLengths);
3285    
3286          // Initialization          // Initialization
3287          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
# Line 2625  namespace { Line 3292  namespace {
3292          PianoReleaseMode = false;          PianoReleaseMode = false;
3293          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
3294          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
3295            pMidiRules = new MidiRule*[3];
3296            pMidiRules[0] = NULL;
3297    
3298          // Loading          // Loading
3299          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2639  namespace { Line 3308  namespace {
3308                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
3309                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
3310                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
3311    
3312                    if (_3ewg->GetSize() > 32) {
3313                        // read MIDI rules
3314                        int i = 0;
3315                        _3ewg->SetPos(32);
3316                        uint8_t id1 = _3ewg->ReadUint8();
3317                        uint8_t id2 = _3ewg->ReadUint8();
3318    
3319                        if (id2 == 16) {
3320                            if (id1 == 4) {
3321                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
3322                            } else if (id1 == 0) {
3323                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
3324                            } else if (id1 == 3) {
3325                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
3326                            } else {
3327                                pMidiRules[i++] = new MidiRuleUnknown;
3328                            }
3329                        }
3330                        else if (id1 != 0 || id2 != 0) {
3331                            pMidiRules[i++] = new MidiRuleUnknown;
3332                        }
3333                        //TODO: all the other types of rules
3334    
3335                        pMidiRules[i] = NULL;
3336                    }
3337              }              }
3338          }          }
3339    
3340          if (!pRegions) pRegions = new RegionList;          if (pFile->GetAutoLoad()) {
3341          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);              if (!pRegions) pRegions = new RegionList;
3342          if (lrgn) {              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
3343              RIFF::List* rgn = lrgn->GetFirstSubList();              if (lrgn) {
3344              while (rgn) {                  RIFF::List* rgn = lrgn->GetFirstSubList();
3345                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  while (rgn) {
3346                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                      if (rgn->GetListType() == LIST_TYPE_RGN) {
3347                      pRegions->push_back(new Region(this, rgn));                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
3348                            pRegions->push_back(new Region(this, rgn));
3349                        }
3350                        rgn = lrgn->GetNextSubList();
3351                  }                  }
3352                  rgn = lrgn->GetNextSubList();                  // Creating Region Key Table for fast lookup
3353                    UpdateRegionKeyTable();
3354              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
3355          }          }
3356    
3357          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
3358      }      }
3359    
3360      void Instrument::UpdateRegionKeyTable() {      void Instrument::UpdateRegionKeyTable() {
3361            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3362          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
3363          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
3364          for (; iter != end; ++iter) {          for (; iter != end; ++iter) {
# Line 2672  namespace { Line 3370  namespace {
3370      }      }
3371    
3372      Instrument::~Instrument() {      Instrument::~Instrument() {
3373            for (int i = 0 ; pMidiRules[i] ; i++) {
3374                delete pMidiRules[i];
3375            }
3376            delete[] pMidiRules;
3377      }      }
3378    
3379      /**      /**
# Line 2700  namespace { Line 3402  namespace {
3402          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
3403          // make sure '3ewg' RIFF chunk exists          // make sure '3ewg' RIFF chunk exists
3404          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
3405          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);          if (!_3ewg)  {
3406                File* pFile = (File*) GetParent();
3407    
3408                // 3ewg is bigger in gig3, as it includes the iMIDI rules
3409                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
3410                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
3411                memset(_3ewg->LoadChunkData(), 0, size);
3412            }
3413          // update '3ewg' RIFF chunk          // update '3ewg' RIFF chunk
3414          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
3415          store16(&pData[0], EffectSend);          store16(&pData[0], EffectSend);
3416          store32(&pData[2], Attenuation);          store32(&pData[2], Attenuation);
3417          store16(&pData[6], FineTune);          store16(&pData[6], FineTune);
3418          store16(&pData[8], PitchbendRange);          store16(&pData[8], PitchbendRange);
3419          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |          const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
3420                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
3421          pData[10] = dimkeystart;          pData[10] = dimkeystart;
3422          pData[11] = DimensionKeyRange.high;          pData[11] = DimensionKeyRange.high;
3423    
3424            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
3425                pData[32] = 0;
3426                pData[33] = 0;
3427            } else {
3428                for (int i = 0 ; pMidiRules[i] ; i++) {
3429                    pMidiRules[i]->UpdateChunks(pData);
3430                }
3431            }
3432      }      }
3433    
3434      /**      /**
# Line 2721  namespace { Line 3439  namespace {
3439       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
3440       */       */
3441      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
3442          if (!pRegions || !pRegions->size() || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
3443          return RegionKeyTable[Key];          return RegionKeyTable[Key];
3444    
3445          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
# Line 2779  namespace { Line 3497  namespace {
3497          UpdateRegionKeyTable();          UpdateRegionKeyTable();
3498      }      }
3499    
3500        /**
3501         * Returns a MIDI rule of the instrument.
3502         *
3503         * The list of MIDI rules, at least in gig v3, always contains at
3504         * most two rules. The second rule can only be the DEF filter
3505         * (which currently isn't supported by libgig).
3506         *
3507         * @param i - MIDI rule number
3508         * @returns   pointer address to MIDI rule number i or NULL if there is none
3509         */
3510        MidiRule* Instrument::GetMidiRule(int i) {
3511            return pMidiRules[i];
3512        }
3513    
3514        /**
3515         * Adds the "controller trigger" MIDI rule to the instrument.
3516         *
3517         * @returns the new MIDI rule
3518         */
3519        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
3520            delete pMidiRules[0];
3521            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
3522            pMidiRules[0] = r;
3523            pMidiRules[1] = 0;
3524            return r;
3525        }
3526    
3527        /**
3528         * Adds the legato MIDI rule to the instrument.
3529         *
3530         * @returns the new MIDI rule
3531         */
3532        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
3533            delete pMidiRules[0];
3534            MidiRuleLegato* r = new MidiRuleLegato;
3535            pMidiRules[0] = r;
3536            pMidiRules[1] = 0;
3537            return r;
3538        }
3539    
3540        /**
3541         * Adds the alternator MIDI rule to the instrument.
3542         *
3543         * @returns the new MIDI rule
3544         */
3545        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
3546            delete pMidiRules[0];
3547            MidiRuleAlternator* r = new MidiRuleAlternator;
3548            pMidiRules[0] = r;
3549            pMidiRules[1] = 0;
3550            return r;
3551        }
3552    
3553        /**
3554         * Deletes a MIDI rule from the instrument.
3555         *
3556         * @param i - MIDI rule number
3557         */
3558        void Instrument::DeleteMidiRule(int i) {
3559            delete pMidiRules[i];
3560            pMidiRules[i] = 0;
3561        }
3562    
3563        /**
3564         * Make a (semi) deep copy of the Instrument object given by @a orig
3565         * and assign it to this object.
3566         *
3567         * Note that all sample pointers referenced by @a orig are simply copied as
3568         * memory address. Thus the respective samples are shared, not duplicated!
3569         *
3570         * @param orig - original Instrument object to be copied from
3571         */
3572        void Instrument::CopyAssign(const Instrument* orig) {
3573            CopyAssign(orig, NULL);
3574        }
3575            
3576        /**
3577         * Make a (semi) deep copy of the Instrument object given by @a orig
3578         * and assign it to this object.
3579         *
3580         * @param orig - original Instrument object to be copied from
3581         * @param mSamples - crosslink map between the foreign file's samples and
3582         *                   this file's samples
3583         */
3584        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
3585            // handle base class
3586            // (without copying DLS region stuff)
3587            DLS::Instrument::CopyAssignCore(orig);
3588            
3589            // handle own member variables
3590            Attenuation = orig->Attenuation;
3591            EffectSend = orig->EffectSend;
3592            FineTune = orig->FineTune;
3593            PitchbendRange = orig->PitchbendRange;
3594            PianoReleaseMode = orig->PianoReleaseMode;
3595            DimensionKeyRange = orig->DimensionKeyRange;
3596            
3597            // free old midi rules
3598            for (int i = 0 ; pMidiRules[i] ; i++) {
3599                delete pMidiRules[i];
3600            }
3601            //TODO: MIDI rule copying
3602            pMidiRules[0] = NULL;
3603            
3604            // delete all old regions
3605            while (Regions) DeleteRegion(GetFirstRegion());
3606            // create new regions and copy them from original
3607            {
3608                RegionList::const_iterator it = orig->pRegions->begin();
3609                for (int i = 0; i < orig->Regions; ++i, ++it) {
3610                    Region* dstRgn = AddRegion();
3611                    //NOTE: Region does semi-deep copy !
3612                    dstRgn->CopyAssign(
3613                        static_cast<gig::Region*>(*it),
3614                        mSamples
3615                    );
3616                }
3617            }
3618    
3619            UpdateRegionKeyTable();
3620        }
3621    
3622    
3623  // *************** Group ***************  // *************** Group ***************
# Line 2818  namespace { Line 3657  namespace {
3657          }          }
3658          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
3659          if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);          if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
3660    
3661            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
3662                // v3 has a fixed list of 128 strings, find a free one
3663                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
3664                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
3665                        pNameChunk = ck;
3666                        break;
3667                    }
3668                }
3669            }
3670    
3671          // 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
3672          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
3673      }      }
# Line 2893  namespace { Line 3743  namespace {
3743  // *************** File ***************  // *************** File ***************
3744  // *  // *
3745    
3746      const DLS::Info::FixedStringLength File::FixedStringLengths[] = {      /// Reflects Gigasampler file format version 2.0 (1998-06-28).
3747        const DLS::version_t File::VERSION_2 = {
3748            0, 2, 19980628 & 0xffff, 19980628 >> 16
3749        };
3750    
3751        /// Reflects Gigasampler file format version 3.0 (2003-03-31).
3752        const DLS::version_t File::VERSION_3 = {
3753            0, 3, 20030331 & 0xffff, 20030331 >> 16
3754        };
3755    
3756        static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
3757          { CHUNK_ID_IARL, 256 },          { CHUNK_ID_IARL, 256 },
3758          { CHUNK_ID_IART, 128 },          { CHUNK_ID_IART, 128 },
3759          { CHUNK_ID_ICMS, 128 },          { CHUNK_ID_ICMS, 128 },
# Line 2915  namespace { Line 3775  namespace {
3775      };      };
3776    
3777      File::File() : DLS::File() {      File::File() : DLS::File() {
3778            bAutoLoad = true;
3779            *pVersion = VERSION_3;
3780          pGroups = NULL;          pGroups = NULL;
3781          pInfo->FixedStringLengths = FixedStringLengths;          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3782          pInfo->ArchivalLocation = String(256, ' ');          pInfo->ArchivalLocation = String(256, ' ');
3783    
3784          // add some mandatory chunks to get the file chunks in right          // add some mandatory chunks to get the file chunks in right
3785          // order (INFO chunk will be moved to first position later)          // order (INFO chunk will be moved to first position later)
3786          pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);          pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
3787          pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);          pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
3788            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
3789    
3790            GenerateDLSID();
3791      }      }
3792    
3793      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
3794            bAutoLoad = true;
3795          pGroups = NULL;          pGroups = NULL;
3796          pInfo->FixedStringLengths = FixedStringLengths;          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3797      }      }
3798    
3799      File::~File() {      File::~File() {
# Line 2954  namespace { Line 3820  namespace {
3820          SamplesIterator++;          SamplesIterator++;
3821          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
3822      }      }
3823        
3824        /**
3825         * Returns Sample object of @a index.
3826         *
3827         * @returns sample object or NULL if index is out of bounds
3828         */
3829        Sample* File::GetSample(uint index) {
3830            if (!pSamples) LoadSamples();
3831            if (!pSamples) return NULL;
3832            DLS::File::SampleList::iterator it = pSamples->begin();
3833            for (int i = 0; i < index; ++i) {
3834                ++it;
3835                if (it == pSamples->end()) return NULL;
3836            }
3837            if (it == pSamples->end()) return NULL;
3838            return static_cast<gig::Sample*>( *it );
3839        }
3840    
3841      /** @brief Add a new sample.      /** @brief Add a new sample.
3842       *       *
# Line 2980  namespace { Line 3863  namespace {
3863    
3864      /** @brief Delete a sample.      /** @brief Delete a sample.
3865       *       *
3866       * 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
3867       * to call Save() to make this persistent to the file.       * references to this sample from Regions and DimensionRegions will be
3868         * removed. You have to call Save() to make this persistent to the file.
3869       *       *
3870       * @param pSample - sample to delete       * @param pSample - sample to delete
3871       * @throws gig::Exception if given sample could not be found       * @throws gig::Exception if given sample could not be found
# Line 2993  namespace { Line 3877  namespace {
3877          if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation          if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
3878          pSamples->erase(iter);          pSamples->erase(iter);
3879          delete pSample;          delete pSample;
3880    
3881            SampleList::iterator tmp = SamplesIterator;
3882            // remove all references to the sample
3883            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
3884                 instrument = GetNextInstrument()) {
3885                for (Region* region = instrument->GetFirstRegion() ; region ;
3886                     region = instrument->GetNextRegion()) {
3887    
3888                    if (region->GetSample() == pSample) region->SetSample(NULL);
3889    
3890                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
3891                        gig::DimensionRegion *d = region->pDimensionRegions[i];
3892                        if (d->pSample == pSample) d->pSample = NULL;
3893                    }
3894                }
3895            }
3896            SamplesIterator = tmp; // restore iterator
3897      }      }
3898    
3899      void File::LoadSamples() {      void File::LoadSamples() {
# Line 3083  namespace { Line 3984  namespace {
3984              progress_t subprogress;              progress_t subprogress;
3985              __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
3986              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
3987              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
3988                    GetFirstSample(&subprogress); // now force all samples to be loaded
3989              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
3990    
3991              // instrument loading subtask              // instrument loading subtask
# Line 3119  namespace { Line 4021  namespace {
4021    
4022         // add mandatory chunks to get the chunks in right order         // add mandatory chunks to get the chunks in right order
4023         lstInstr->AddSubList(LIST_TYPE_INFO);         lstInstr->AddSubList(LIST_TYPE_INFO);
4024           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
4025    
4026         Instrument* pInstrument = new Instrument(this, lstInstr);         Instrument* pInstrument = new Instrument(this, lstInstr);
4027           pInstrument->GenerateDLSID();
4028    
4029         lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);         lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
4030    
# Line 3130  namespace { Line 4034  namespace {
4034         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
4035         return pInstrument;         return pInstrument;
4036      }      }
4037        
4038        /** @brief Add a duplicate of an existing instrument.
4039         *
4040         * Duplicates the instrument definition given by @a orig and adds it
4041         * to this file. This allows in an instrument editor application to
4042         * easily create variations of an instrument, which will be stored in
4043         * the same .gig file, sharing i.e. the same samples.
4044         *
4045         * Note that all sample pointers referenced by @a orig are simply copied as
4046         * memory address. Thus the respective samples are shared, not duplicated!
4047         *
4048         * You have to call Save() to make this persistent to the file.
4049         *
4050         * @param orig - original instrument to be copied
4051         * @returns duplicated copy of the given instrument
4052         */
4053        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
4054            Instrument* instr = AddInstrument();
4055            instr->CopyAssign(orig);
4056            return instr;
4057        }
4058        
4059        /** @brief Add content of another existing file.
4060         *
4061         * Duplicates the samples, groups and instruments of the original file
4062         * given by @a pFile and adds them to @c this File. In case @c this File is
4063         * a new one that you haven't saved before, then you have to call
4064         * SetFileName() before calling AddContentOf(), because this method will
4065         * automatically save this file during operation, which is required for
4066         * writing the sample waveform data by disk streaming.
4067         *
4068         * @param pFile - original file whose's content shall be copied from
4069         */
4070        void File::AddContentOf(File* pFile) {
4071            static int iCallCount = -1;
4072            iCallCount++;
4073            std::map<Group*,Group*> mGroups;
4074            std::map<Sample*,Sample*> mSamples;
4075            
4076            // clone sample groups
4077            for (int i = 0; pFile->GetGroup(i); ++i) {
4078                Group* g = AddGroup();
4079                g->Name =
4080                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
4081                mGroups[pFile->GetGroup(i)] = g;
4082            }
4083            
4084            // clone samples (not waveform data here yet)
4085            for (int i = 0; pFile->GetSample(i); ++i) {
4086                Sample* s = AddSample();
4087                s->CopyAssignMeta(pFile->GetSample(i));
4088                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
4089                mSamples[pFile->GetSample(i)] = s;
4090            }
4091            
4092            //BUG: For some reason this method only works with this additional
4093            //     Save() call in between here.
4094            //
4095            // Important: The correct one of the 2 Save() methods has to be called
4096            // here, depending on whether the file is completely new or has been
4097            // saved to disk already, otherwise it will result in data corruption.
4098            if (pRIFF->IsNew())
4099                Save(GetFileName());
4100            else
4101                Save();
4102            
4103            // clone instruments
4104            // (passing the crosslink table here for the cloned samples)
4105            for (int i = 0; pFile->GetInstrument(i); ++i) {
4106                Instrument* instr = AddInstrument();
4107                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
4108            }
4109            
4110            // Mandatory: file needs to be saved to disk at this point, so this
4111            // file has the correct size and data layout for writing the samples'
4112            // waveform data to disk.
4113            Save();
4114            
4115            // clone samples' waveform data
4116            // (using direct read & write disk streaming)
4117            for (int i = 0; pFile->GetSample(i); ++i) {
4118                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
4119            }
4120        }
4121    
4122      /** @brief Delete an instrument.      /** @brief Delete an instrument.
4123       *       *
# Line 3177  namespace { Line 4165  namespace {
4165          }          }
4166      }      }
4167    
4168        /// Updates the 3crc chunk with the checksum of a sample. The
4169        /// update is done directly to disk, as this method is called
4170        /// after File::Save()
4171        void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
4172            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
4173            if (!_3crc) return;
4174    
4175            // get the index of the sample
4176            int iWaveIndex = -1;
4177            File::SampleList::iterator iter = pSamples->begin();
4178            File::SampleList::iterator end  = pSamples->end();
4179            for (int index = 0; iter != end; ++iter, ++index) {
4180                if (*iter == pSample) {
4181                    iWaveIndex = index;
4182                    break;
4183                }
4184            }
4185            if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
4186    
4187            // write the CRC-32 checksum to disk
4188            _3crc->SetPos(iWaveIndex * 8);
4189            uint32_t tmp = 1;
4190            _3crc->WriteUint32(&tmp); // unknown, always 1?
4191            _3crc->WriteUint32(&crc);
4192        }
4193    
4194      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
4195          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
4196          // there must always be at least one group          // there must always be at least one group
# Line 3269  namespace { Line 4283  namespace {
4283                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
4284                  while (ck) {                  while (ck) {
4285                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {
4286                            if (pVersion && pVersion->major == 3 &&
4287                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
4288    
4289                          pGroups->push_back(new Group(this, ck));                          pGroups->push_back(new Group(this, ck));
4290                      }                      }
4291                      ck = lst3gnl->GetNextSubChunk();                      ck = lst3gnl->GetNextSubChunk();
# Line 3294  namespace { Line 4311  namespace {
4311       * @throws Exception - on errors       * @throws Exception - on errors
4312       */       */
4313      void File::UpdateChunks() {      void File::UpdateChunks() {
4314          RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
4315    
4316            b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
4317    
4318          // first update base class's chunks          // first update base class's chunks
4319          DLS::File::UpdateChunks();          DLS::File::UpdateChunks();
4320    
4321          if (!info) {          if (newFile) {
4322              // INFO was added by Resource::UpdateChunks - make sure it              // INFO was added by Resource::UpdateChunks - make sure it
4323              // is placed first in file              // is placed first in file
4324              info = pRIFF->GetSubList(LIST_TYPE_INFO);              RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
4325              RIFF::Chunk* first = pRIFF->GetFirstSubChunk();              RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
4326              if (first != info) {              if (first != info) {
4327                  pRIFF->MoveSubChunk(info, first);                  pRIFF->MoveSubChunk(info, first);
# Line 3311  namespace { Line 4330  namespace {
4330    
4331          // update group's chunks          // update group's chunks
4332          if (pGroups) {          if (pGroups) {
4333                // make sure '3gri' and '3gnl' list chunks exist
4334                // (before updating the Group chunks)
4335                RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
4336                if (!_3gri) {
4337                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
4338                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
4339                }
4340                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
4341                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
4342    
4343                // v3: make sure the file has 128 3gnm chunks
4344                // (before updating the Group chunks)
4345                if (pVersion && pVersion->major == 3) {
4346                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
4347                    for (int i = 0 ; i < 128 ; i++) {
4348                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
4349                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
4350                    }
4351                }
4352    
4353              std::list<Group*>::iterator iter = pGroups->begin();              std::list<Group*>::iterator iter = pGroups->begin();
4354              std::list<Group*>::iterator end  = pGroups->end();              std::list<Group*>::iterator end  = pGroups->end();
4355              for (; iter != end; ++iter) {              for (; iter != end; ++iter) {
4356                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks();
4357              }              }
4358          }          }
4359    
4360            // update einf chunk
4361    
4362            // The einf chunk contains statistics about the gig file, such
4363            // as the number of regions and samples used by each
4364            // instrument. It is divided in equally sized parts, where the
4365            // first part contains information about the whole gig file,
4366            // and the rest of the parts map to each instrument in the
4367            // file.
4368            //
4369            // At the end of each part there is a bit map of each sample
4370            // in the file, where a set bit means that the sample is used
4371            // by the file/instrument.
4372            //
4373            // Note that there are several fields with unknown use. These
4374            // are set to zero.
4375    
4376            int sublen = pSamples->size() / 8 + 49;
4377            int einfSize = (Instruments + 1) * sublen;
4378    
4379            RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
4380            if (einf) {
4381                if (einf->GetSize() != einfSize) {
4382                    einf->Resize(einfSize);
4383                    memset(einf->LoadChunkData(), 0, einfSize);
4384                }
4385            } else if (newFile) {
4386                einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
4387            }
4388            if (einf) {
4389                uint8_t* pData = (uint8_t*) einf->LoadChunkData();
4390    
4391                std::map<gig::Sample*,int> sampleMap;
4392                int sampleIdx = 0;
4393                for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
4394                    sampleMap[pSample] = sampleIdx++;
4395                }
4396    
4397                int totnbusedsamples = 0;
4398                int totnbusedchannels = 0;
4399                int totnbregions = 0;
4400                int totnbdimregions = 0;
4401                int totnbloops = 0;
4402                int instrumentIdx = 0;
4403    
4404                memset(&pData[48], 0, sublen - 48);
4405    
4406                for (Instrument* instrument = GetFirstInstrument() ; instrument ;
4407                     instrument = GetNextInstrument()) {
4408                    int nbusedsamples = 0;
4409                    int nbusedchannels = 0;
4410                    int nbdimregions = 0;
4411                    int nbloops = 0;
4412    
4413                    memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
4414    
4415                    for (Region* region = instrument->GetFirstRegion() ; region ;
4416                         region = instrument->GetNextRegion()) {
4417                        for (int i = 0 ; i < region->DimensionRegions ; i++) {
4418                            gig::DimensionRegion *d = region->pDimensionRegions[i];
4419                            if (d->pSample) {
4420                                int sampleIdx = sampleMap[d->pSample];
4421                                int byte = 48 + sampleIdx / 8;
4422                                int bit = 1 << (sampleIdx & 7);
4423                                if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
4424                                    pData[(instrumentIdx + 1) * sublen + byte] |= bit;
4425                                    nbusedsamples++;
4426                                    nbusedchannels += d->pSample->Channels;
4427    
4428                                    if ((pData[byte] & bit) == 0) {
4429                                        pData[byte] |= bit;
4430                                        totnbusedsamples++;
4431                                        totnbusedchannels += d->pSample->Channels;
4432                                    }
4433                                }
4434                            }
4435                            if (d->SampleLoops) nbloops++;
4436                        }
4437                        nbdimregions += region->DimensionRegions;
4438                    }
4439                    // first 4 bytes unknown - sometimes 0, sometimes length of einf part
4440                    // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
4441                    store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
4442                    store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
4443                    store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
4444                    store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
4445                    store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
4446                    store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
4447                    // next 8 bytes unknown
4448                    store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
4449                    store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
4450                    // next 4 bytes unknown
4451    
4452                    totnbregions += instrument->Regions;
4453                    totnbdimregions += nbdimregions;
4454                    totnbloops += nbloops;
4455                    instrumentIdx++;
4456                }
4457                // first 4 bytes unknown - sometimes 0, sometimes length of einf part
4458                // store32(&pData[0], sublen);
4459                store32(&pData[4], totnbusedchannels);
4460                store32(&pData[8], totnbusedsamples);
4461                store32(&pData[12], Instruments);
4462                store32(&pData[16], totnbregions);
4463                store32(&pData[20], totnbdimregions);
4464                store32(&pData[24], totnbloops);
4465                // next 8 bytes unknown
4466                // next 4 bytes unknown, not always 0
4467                store32(&pData[40], pSamples->size());
4468                // next 4 bytes unknown
4469            }
4470    
4471            // update 3crc chunk
4472    
4473            // The 3crc chunk contains CRC-32 checksums for the
4474            // samples. The actual checksum values will be filled in
4475            // later, by Sample::Write.
4476    
4477            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
4478            if (_3crc) {
4479                _3crc->Resize(pSamples->size() * 8);
4480            } else if (newFile) {
4481                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
4482                _3crc->LoadChunkData();
4483    
4484                // the order of einf and 3crc is not the same in v2 and v3
4485                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
4486            }
4487        }
4488    
4489        /**
4490         * Enable / disable automatic loading. By default this properyt is
4491         * enabled and all informations are loaded automatically. However
4492         * loading all Regions, DimensionRegions and especially samples might
4493         * take a long time for large .gig files, and sometimes one might only
4494         * be interested in retrieving very superficial informations like the
4495         * amount of instruments and their names. In this case one might disable
4496         * automatic loading to avoid very slow response times.
4497         *
4498         * @e CAUTION: by disabling this property many pointers (i.e. sample
4499         * references) and informations will have invalid or even undefined
4500         * data! This feature is currently only intended for retrieving very
4501         * superficial informations in a very fast way. Don't use it to retrieve
4502         * details like synthesis informations or even to modify .gig files!
4503         */
4504        void File::SetAutoLoad(bool b) {
4505            bAutoLoad = b;
4506        }
4507    
4508        /**
4509         * Returns whether automatic loading is enabled.
4510         * @see SetAutoLoad()
4511         */
4512        bool File::GetAutoLoad() {
4513            return bAutoLoad;
4514      }      }
4515    
4516    

Legend:
Removed from v.1192  
changed lines
  Added in v.2482

  ViewVC Help
Powered by ViewVC