/[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 1199 by persson, Sun May 20 10:11:39 2007 UTC revision 2394 by schoenebeck, Mon Jan 7 23:23:58 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 278  namespace { Line 342  namespace {
342    
343    
344    
 // *************** CRC ***************  
 // *  
   
     const uint32_t* CRC::table(initTable());  
   
     uint32_t* CRC::initTable() {  
         uint32_t* res = new uint32_t[256];  
   
         for (int i = 0 ; i < 256 ; i++) {  
             uint32_t c = i;  
             for (int j = 0 ; j < 8 ; j++) {  
                 c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;  
             }  
             res[i] = c;  
         }  
         return res;  
     }  
   
   
   
345  // *************** Sample ***************  // *************** Sample ***************
346  // *  // *
347    
# Line 323  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 362  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 631  namespace { Line 677  namespace {
677          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
678          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
679          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
680            SetPos(0); // reset read position to begin of sample
681          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
682          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
683          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 668  namespace { Line 715  namespace {
715          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
716          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
717          RAMCache.Size   = 0;          RAMCache.Size   = 0;
718            RAMCache.NullExtensionSize = 0;
719      }      }
720    
721      /** @brief Resize sample.      /** @brief Resize sample.
# Line 862  namespace { Line 910  namespace {
910                                  }                                  }
911    
912                                  // reverse the sample frames for backward playback                                  // reverse the sample frames for backward playback
913                                  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!
914                                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
915                              }                              }
916                          } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
917                          break;                          break;
# Line 1152  namespace { Line 1201  namespace {
1201       *       *
1202       * Note: there is currently no support for writing compressed samples.       * Note: there is currently no support for writing compressed samples.
1203       *       *
1204         * For 16 bit samples, the data in the source buffer should be
1205         * int16_t (using native endianness). For 24 bit, the buffer
1206         * should contain three bytes per sample, little-endian.
1207         *
1208       * @param pBuffer     - source buffer       * @param pBuffer     - source buffer
1209       * @param SampleCount - number of sample points to write       * @param SampleCount - number of sample points to write
1210       * @throws DLS::Exception if current sample size is too small       * @throws DLS::Exception if current sample size is too small
# Line 1160  namespace { Line 1213  namespace {
1213       */       */
1214      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1215          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)");
1216    
1217            // if this is the first write in this sample, reset the
1218            // checksum calculator
1219          if (pCkData->GetPos() == 0) {          if (pCkData->GetPos() == 0) {
1220              crc.reset();              __resetCRC(crc);
1221          }          }
1222          unsigned long res = DLS::Sample::Write(pBuffer, SampleCount);          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1223          crc.update((unsigned char *)pBuffer, SampleCount * FrameSize);          unsigned long res;
1224            if (BitDepth == 24) {
1225                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1226            } else { // 16 bit
1227                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1228                                    : pCkData->Write(pBuffer, SampleCount, 2);
1229            }
1230            __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1231    
1232            // if this is the last write, update the checksum chunk in the
1233            // file
1234          if (pCkData->GetPos() == pCkData->GetSize()) {          if (pCkData->GetPos() == pCkData->GetSize()) {
1235              File* pFile = static_cast<File*>(GetParent());              File* pFile = static_cast<File*>(GetParent());
1236              pFile->SetSampleChecksum(this, crc.getValue());              pFile->SetSampleChecksum(this, __encodeCRC(crc));
1237          }          }
1238          return res;          return res;
1239      }      }
# Line 1246  namespace { Line 1311  namespace {
1311      uint                               DimensionRegion::Instances       = 0;      uint                               DimensionRegion::Instances       = 0;
1312      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1313    
1314      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1315          Instances++;          Instances++;
1316    
1317          pSample = NULL;          pSample = NULL;
1318            pRegion = pParent;
1319    
1320            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1321            else memset(&Crossfade, 0, 4);
1322    
         memcpy(&Crossfade, &SamplerOptions, 4);  
1323          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1324    
1325          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
# Line 1415  namespace { Line 1483  namespace {
1483              LFO1ControlDepth                = 0;              LFO1ControlDepth                = 0;
1484              LFO3ControlDepth                = 0;              LFO3ControlDepth                = 0;
1485              EG1Attack                       = 0.0;              EG1Attack                       = 0.0;
1486              EG1Decay1                       = 0.0;              EG1Decay1                       = 0.005;
1487              EG1Sustain                      = 0;              EG1Sustain                      = 1000;
1488              EG1Release                      = 0.0;              EG1Release                      = 0.3;
1489              EG1Controller.type              = eg1_ctrl_t::type_none;              EG1Controller.type              = eg1_ctrl_t::type_none;
1490              EG1Controller.controller_number = 0;              EG1Controller.controller_number = 0;
1491              EG1ControllerInvert             = false;              EG1ControllerInvert             = false;
# Line 1432  namespace { Line 1500  namespace {
1500              EG2ControllerReleaseInfluence   = 0;              EG2ControllerReleaseInfluence   = 0;
1501              LFO1Frequency                   = 1.0;              LFO1Frequency                   = 1.0;
1502              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1503              EG2Decay1                       = 0.0;              EG2Decay1                       = 0.005;
1504              EG2Sustain                      = 0;              EG2Sustain                      = 1000;
1505              EG2Release                      = 0.0;              EG2Release                      = 0.3;
1506              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1507              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1508              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
1509              EG1Decay2                       = 0.0;              EG1Decay2                       = 0.0;
1510              EG1InfiniteSustain              = false;              EG1InfiniteSustain              = true;
1511              EG1PreAttack                    = 1000;              EG1PreAttack                    = 0;
1512              EG2Decay2                       = 0.0;              EG2Decay2                       = 0.0;
1513              EG2InfiniteSustain              = false;              EG2InfiniteSustain              = true;
1514              EG2PreAttack                    = 1000;              EG2PreAttack                    = 0;
1515              VelocityResponseCurve           = curve_type_nonlinear;              VelocityResponseCurve           = curve_type_nonlinear;
1516              VelocityResponseDepth           = 3;              VelocityResponseDepth           = 3;
1517              ReleaseVelocityResponseCurve    = curve_type_nonlinear;              ReleaseVelocityResponseCurve    = curve_type_nonlinear;
# Line 1486  namespace { Line 1554  namespace {
1554              VCFVelocityDynamicRange         = 0x04;              VCFVelocityDynamicRange         = 0x04;
1555              VCFVelocityCurve                = curve_type_linear;              VCFVelocityCurve                = curve_type_linear;
1556              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1557              memset(DimensionUpperLimits, 0, 8);              memset(DimensionUpperLimits, 127, 8);
1558          }          }
1559    
1560          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1561                                                       VelocityResponseDepth,                                                       VelocityResponseDepth,
1562                                                       VelocityResponseCurveScaling);                                                       VelocityResponseCurveScaling);
1563    
1564          curve_type_t curveType = ReleaseVelocityResponseCurve;          pVelocityReleaseTable = GetReleaseVelocityTable(
1565          uint8_t depth = ReleaseVelocityResponseDepth;                                      ReleaseVelocityResponseCurve,
1566                                        ReleaseVelocityResponseDepth
1567                                    );
1568    
1569            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1570                                                          VCFVelocityDynamicRange,
1571                                                          VCFVelocityScale,
1572                                                          VCFCutoffController);
1573    
1574          // this models a strange behaviour or bug in GSt: two of the          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1575          // velocity response curves for release time are not used even          VelocityTable = 0;
1576          // 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);  
1577    
1578          curveType = VCFVelocityCurve;      /*
1579          depth = VCFVelocityDynamicRange;       * Constructs a DimensionRegion by copying all parameters from
1580         * another DimensionRegion
1581         */
1582        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1583            Instances++;
1584            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1585            *this = src; // default memberwise shallow copy of all parameters
1586            pParentList = _3ewl; // restore the chunk pointer
1587    
1588          // even stranger GSt: two of the velocity response curves for          // deep copy of owned structures
1589          // filter cutoff are not used, instead another special curve          if (src.VelocityTable) {
1590          // is chosen. This curve is not used anywhere else.              VelocityTable = new uint8_t[128];
1591          if ((curveType == curve_type_nonlinear && depth == 0) ||              for (int k = 0 ; k < 128 ; k++)
1592              (curveType == curve_type_special   && depth == 4)) {                  VelocityTable[k] = src.VelocityTable[k];
1593              curveType = curve_type_special;          }
1594              depth = 5;          if (src.pSampleLoops) {
1595                pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1596                for (int k = 0 ; k < src.SampleLoops ; k++)
1597                    pSampleLoops[k] = src.pSampleLoops[k];
1598            }
1599        }
1600        
1601        /**
1602         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1603         * and assign it to this object.
1604         *
1605         * Note that all sample pointers referenced by @a orig are simply copied as
1606         * memory address. Thus the respective samples are shared, not duplicated!
1607         *
1608         * @param orig - original DimensionRegion object to be copied from
1609         */
1610        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1611            // delete all allocated data first
1612            if (VelocityTable) delete [] VelocityTable;
1613            if (pSampleLoops) delete [] pSampleLoops;
1614            
1615            // backup parent list pointer
1616            RIFF::List* p = pParentList;
1617            
1618            //NOTE: copy code copied from assignment constructor above, see comment there as well
1619            
1620            *this = *orig; // default memberwise shallow copy of all parameters
1621            pParentList = p; // restore the chunk pointer
1622    
1623            // deep copy of owned structures
1624            if (orig->VelocityTable) {
1625                VelocityTable = new uint8_t[128];
1626                for (int k = 0 ; k < 128 ; k++)
1627                    VelocityTable[k] = orig->VelocityTable[k];
1628            }
1629            if (orig->pSampleLoops) {
1630                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1631                for (int k = 0 ; k < orig->SampleLoops ; k++)
1632                    pSampleLoops[k] = orig->pSampleLoops[k];
1633          }          }
1634          pVelocityCutoffTable = GetVelocityTable(curveType, depth,      }
                                                 VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);  
1635    
1636        /**
1637         * Updates the respective member variable and updates @c SampleAttenuation
1638         * which depends on this value.
1639         */
1640        void DimensionRegion::SetGain(int32_t gain) {
1641            DLS::Sampler::SetGain(gain);
1642          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
         VelocityTable = 0;  
1643      }      }
1644    
1645      /**      /**
# Line 1535  namespace { Line 1653  namespace {
1653          // first update base class's chunk          // first update base class's chunk
1654          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks();
1655    
1656            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1657            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1658            pData[12] = Crossfade.in_start;
1659            pData[13] = Crossfade.in_end;
1660            pData[14] = Crossfade.out_start;
1661            pData[15] = Crossfade.out_end;
1662    
1663          // make sure '3ewa' chunk exists          // make sure '3ewa' chunk exists
1664          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1665          if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);          if (!_3ewa) {
1666          uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();              File* pFile = (File*) GetParent()->GetParent()->GetParent();
1667                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1668                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1669            }
1670            pData = (uint8_t*) _3ewa->LoadChunkData();
1671    
1672          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1673    
# Line 1584  namespace { Line 1713  namespace {
1713          pData[44] = eg1ctl;          pData[44] = eg1ctl;
1714    
1715          const uint8_t eg1ctrloptions =          const uint8_t eg1ctrloptions =
1716              (EG1ControllerInvert) ? 0x01 : 0x00 |              (EG1ControllerInvert ? 0x01 : 0x00) |
1717              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1718              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1719              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
# Line 1594  namespace { Line 1723  namespace {
1723          pData[46] = eg2ctl;          pData[46] = eg2ctl;
1724    
1725          const uint8_t eg2ctrloptions =          const uint8_t eg2ctrloptions =
1726              (EG2ControllerInvert) ? 0x01 : 0x00 |              (EG2ControllerInvert ? 0x01 : 0x00) |
1727              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1728              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1729              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
# Line 1745  namespace { Line 1874  namespace {
1874    
1875          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1876                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1877          pData[116] = eg3depth;          store16(&pData[116], eg3depth);
1878    
1879          // next 2 bytes unknown          // next 2 bytes unknown
1880    
# Line 1772  namespace { Line 1901  namespace {
1901          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1902          pData[131] = eg1hold;          pData[131] = eg1hold;
1903    
1904          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */          const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
1905                                    (VCFCutoff & 0x7f);   /* lower 7 bits */                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
1906          pData[132] = vcfcutoff;          pData[132] = vcfcutoff;
1907    
1908          pData[133] = VCFCutoffController;          pData[133] = VCFCutoffController;
1909    
1910          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
1911                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
1912          pData[134] = vcfvelscale;          pData[134] = vcfvelscale;
1913    
1914          // next byte unknown          // next byte unknown
1915    
1916          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */          const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
1917                                       (VCFResonance & 0x7f); /* lower 7 bits */                                       (VCFResonance & 0x7f); /* lower 7 bits */
1918          pData[136] = vcfresonance;          pData[136] = vcfresonance;
1919    
1920          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
1921                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
1922          pData[137] = vcfbreakpoint;          pData[137] = vcfbreakpoint;
1923    
1924          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
1925                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
1926          pData[138] = vcfvelocity;          pData[138] = vcfvelocity;
1927    
# Line 1804  namespace { Line 1933  namespace {
1933          }          }
1934      }      }
1935    
1936        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
1937            curve_type_t curveType = releaseVelocityResponseCurve;
1938            uint8_t depth = releaseVelocityResponseDepth;
1939            // this models a strange behaviour or bug in GSt: two of the
1940            // velocity response curves for release time are not used even
1941            // if specified, instead another curve is chosen.
1942            if ((curveType == curve_type_nonlinear && depth == 0) ||
1943                (curveType == curve_type_special   && depth == 4)) {
1944                curveType = curve_type_nonlinear;
1945                depth = 3;
1946            }
1947            return GetVelocityTable(curveType, depth, 0);
1948        }
1949    
1950        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
1951                                                        uint8_t vcfVelocityDynamicRange,
1952                                                        uint8_t vcfVelocityScale,
1953                                                        vcf_cutoff_ctrl_t vcfCutoffController)
1954        {
1955            curve_type_t curveType = vcfVelocityCurve;
1956            uint8_t depth = vcfVelocityDynamicRange;
1957            // even stranger GSt: two of the velocity response curves for
1958            // filter cutoff are not used, instead another special curve
1959            // is chosen. This curve is not used anywhere else.
1960            if ((curveType == curve_type_nonlinear && depth == 0) ||
1961                (curveType == curve_type_special   && depth == 4)) {
1962                curveType = curve_type_special;
1963                depth = 5;
1964            }
1965            return GetVelocityTable(curveType, depth,
1966                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
1967                                        ? vcfVelocityScale : 0);
1968        }
1969    
1970      // 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
1971      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)
1972      {      {
# Line 1819  namespace { Line 1982  namespace {
1982          return table;          return table;
1983      }      }
1984    
1985        Region* DimensionRegion::GetParent() const {
1986            return pRegion;
1987        }
1988    
1989      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
1990          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
1991          switch (EncodedController) {          switch (EncodedController) {
# Line 2072  namespace { Line 2239  namespace {
2239          return pVelocityCutoffTable[MIDIKeyVelocity];          return pVelocityCutoffTable[MIDIKeyVelocity];
2240      }      }
2241    
2242        /**
2243         * Updates the respective member variable and the lookup table / cache
2244         * that depends on this value.
2245         */
2246        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2247            pVelocityAttenuationTable =
2248                GetVelocityTable(
2249                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2250                );
2251            VelocityResponseCurve = curve;
2252        }
2253    
2254        /**
2255         * Updates the respective member variable and the lookup table / cache
2256         * that depends on this value.
2257         */
2258        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2259            pVelocityAttenuationTable =
2260                GetVelocityTable(
2261                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2262                );
2263            VelocityResponseDepth = depth;
2264        }
2265    
2266        /**
2267         * Updates the respective member variable and the lookup table / cache
2268         * that depends on this value.
2269         */
2270        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2271            pVelocityAttenuationTable =
2272                GetVelocityTable(
2273                    VelocityResponseCurve, VelocityResponseDepth, scaling
2274                );
2275            VelocityResponseCurveScaling = scaling;
2276        }
2277    
2278        /**
2279         * Updates the respective member variable and the lookup table / cache
2280         * that depends on this value.
2281         */
2282        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2283            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2284            ReleaseVelocityResponseCurve = curve;
2285        }
2286    
2287        /**
2288         * Updates the respective member variable and the lookup table / cache
2289         * that depends on this value.
2290         */
2291        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2292            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2293            ReleaseVelocityResponseDepth = depth;
2294        }
2295    
2296        /**
2297         * Updates the respective member variable and the lookup table / cache
2298         * that depends on this value.
2299         */
2300        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2301            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2302            VCFCutoffController = controller;
2303        }
2304    
2305        /**
2306         * Updates the respective member variable and the lookup table / cache
2307         * that depends on this value.
2308         */
2309        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2310            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2311            VCFVelocityCurve = curve;
2312        }
2313    
2314        /**
2315         * Updates the respective member variable and the lookup table / cache
2316         * that depends on this value.
2317         */
2318        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2319            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2320            VCFVelocityDynamicRange = range;
2321        }
2322    
2323        /**
2324         * Updates the respective member variable and the lookup table / cache
2325         * that depends on this value.
2326         */
2327        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2328            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2329            VCFVelocityScale = scaling;
2330        }
2331    
2332      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) {
2333    
2334          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 2155  namespace { Line 2412  namespace {
2412    
2413          // Actual Loading          // Actual Loading
2414    
2415            if (!file->GetAutoLoad()) return;
2416    
2417          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2418    
2419          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2198  namespace { Line 2457  namespace {
2457              else              else
2458                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
2459    
2460              // load sample references              // load sample references (if auto loading is enabled)
2461              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
2462                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
2463                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2464                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2465                    }
2466                    GetSample(); // load global region sample reference
2467              }              }
             GetSample(); // load global region sample reference  
2468          } else {          } else {
2469              DimensionRegions = 0;              DimensionRegions = 0;
2470              for (int i = 0 ; i < 8 ; i++) {              for (int i = 0 ; i < 8 ; i++) {
# Line 2218  namespace { Line 2479  namespace {
2479              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2480              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2481              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2482              pDimensionRegions[0] = new DimensionRegion(_3ewl);              pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
2483              DimensionRegions = 1;              DimensionRegions = 1;
2484          }          }
2485      }      }
# Line 2248  namespace { Line 2509  namespace {
2509          }          }
2510    
2511          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
2512          const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;          bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
2513          const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;          const int iMaxDimensions =  version3 ? 8 : 5;
2514            const int iMaxDimensionRegions = version3 ? 256 : 32;
2515    
2516          // make sure '3lnk' chunk exists          // make sure '3lnk' chunk exists
2517          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2518          if (!_3lnk) {          if (!_3lnk) {
2519              const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;              const int _3lnkChunkSize = version3 ? 1092 : 172;
2520              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2521              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
2522    
# Line 2269  namespace { Line 2531  namespace {
2531          for (int i = 0; i < iMaxDimensions; i++) {          for (int i = 0; i < iMaxDimensions; i++) {
2532              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2533              pData[5 + i * 8] = pDimensionDefinitions[i].bits;              pData[5 + i * 8] = pDimensionDefinitions[i].bits;
2534              pData[6 + i * 8] = shift;              pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
2535              pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);              pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
2536              pData[8 + i * 8] = pDimensionDefinitions[i].zones;              pData[8 + i * 8] = pDimensionDefinitions[i].zones;
2537              // next 3 bytes unknown, always zero?              // next 3 bytes unknown, always zero?
# Line 2278  namespace { Line 2540  namespace {
2540          }          }
2541    
2542          // update wave pool table in '3lnk' chunk          // update wave pool table in '3lnk' chunk
2543          const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;          const int iWavePoolOffset = version3 ? 68 : 44;
2544          for (uint i = 0; i < iMaxDimensionRegions; i++) {          for (uint i = 0; i < iMaxDimensionRegions; i++) {
2545              int iWaveIndex = -1;              int iWaveIndex = -1;
2546              if (i < DimensionRegions) {              if (i < DimensionRegions) {
# Line 2291  namespace { Line 2553  namespace {
2553                          break;                          break;
2554                      }                      }
2555                  }                  }
                 if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");  
2556              }              }
2557              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
2558          }          }
# Line 2304  namespace { Line 2565  namespace {
2565              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
2566              while (_3ewl) {              while (_3ewl) {
2567                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
2568                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
2569                      dimensionRegionNr++;                      dimensionRegionNr++;
2570                  }                  }
2571                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 2313  namespace { Line 2574  namespace {
2574          }          }
2575      }      }
2576    
2577        void Region::SetKeyRange(uint16_t Low, uint16_t High) {
2578            // update KeyRange struct and make sure regions are in correct order
2579            DLS::Region::SetKeyRange(Low, High);
2580            // update Region key table for fast lookup
2581            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
2582        }
2583    
2584      void Region::UpdateVelocityTable() {      void Region::UpdateVelocityTable() {
2585          // get velocity dimension's index          // get velocity dimension's index
2586          int veldim = -1;          int veldim = -1;
# Line 2418  namespace { Line 2686  namespace {
2686              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2687                  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");
2688    
2689            // pos is where the new dimension should be placed, normally
2690            // last in list, except for the samplechannel dimension which
2691            // has to be first in list
2692            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
2693            int bitpos = 0;
2694            for (int i = 0 ; i < pos ; i++)
2695                bitpos += pDimensionDefinitions[i].bits;
2696    
2697            // make room for the new dimension
2698            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
2699            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
2700                for (int j = Dimensions ; j > pos ; j--) {
2701                    pDimensionRegions[i]->DimensionUpperLimits[j] =
2702                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
2703                }
2704            }
2705    
2706          // assign definition of new dimension          // assign definition of new dimension
2707          pDimensionDefinitions[Dimensions] = *pDimDef;          pDimensionDefinitions[pos] = *pDimDef;
2708    
2709          // auto correct certain dimension definition fields (where possible)          // auto correct certain dimension definition fields (where possible)
2710          pDimensionDefinitions[Dimensions].split_type  =          pDimensionDefinitions[pos].split_type  =
2711              __resolveSplitType(pDimensionDefinitions[Dimensions].dimension);              __resolveSplitType(pDimensionDefinitions[pos].dimension);
2712          pDimensionDefinitions[Dimensions].zone_size =          pDimensionDefinitions[pos].zone_size =
2713              __resolveZoneSize(pDimensionDefinitions[Dimensions]);              __resolveZoneSize(pDimensionDefinitions[pos]);
2714    
2715          // create new dimension region(s) for this new dimension          // create new dimension region(s) for this new dimension, and make
2716          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {          // sure that the dimension regions are placed correctly in both the
2717              //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
2718              RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);          RIFF::Chunk* moveTo = NULL;
2719              RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);          RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2720              pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);          for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
2721              DimensionRegions++;              for (int k = 0 ; k < (1 << bitpos) ; k++) {
2722                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
2723                }
2724                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
2725                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
2726                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
2727                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
2728                        // create a new dimension region and copy all parameter values from
2729                        // an existing dimension region
2730                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
2731                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
2732    
2733                        DimensionRegions++;
2734                    }
2735                }
2736                moveTo = pDimensionRegions[i]->pParentList;
2737            }
2738    
2739            // initialize the upper limits for this dimension
2740            int mask = (1 << bitpos) - 1;
2741            for (int z = 0 ; z < pDimDef->zones ; z++) {
2742                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
2743                for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
2744                    pDimensionRegions[((i & ~mask) << pDimDef->bits) |
2745                                      (z << bitpos) |
2746                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
2747                }
2748          }          }
2749    
2750          Dimensions++;          Dimensions++;
# Line 2476  namespace { Line 2787  namespace {
2787          for (int i = iDimensionNr + 1; i < Dimensions; i++)          for (int i = iDimensionNr + 1; i < Dimensions; i++)
2788              iUpperBits += pDimensionDefinitions[i].bits;              iUpperBits += pDimensionDefinitions[i].bits;
2789    
2790            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2791    
2792          // delete dimension regions which belong to the given dimension          // delete dimension regions which belong to the given dimension
2793          // (that is where the dimension's bit > 0)          // (that is where the dimension's bit > 0)
2794          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
# Line 2484  namespace { Line 2797  namespace {
2797                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2798                                      iObsoleteBit << iLowerBits |                                      iObsoleteBit << iLowerBits |
2799                                      iLowerBit;                                      iLowerBit;
2800    
2801                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
2802                      delete pDimensionRegions[iToDelete];                      delete pDimensionRegions[iToDelete];
2803                      pDimensionRegions[iToDelete] = NULL;                      pDimensionRegions[iToDelete] = NULL;
2804                      DimensionRegions--;                      DimensionRegions--;
# Line 2504  namespace { Line 2819  namespace {
2819              }              }
2820          }          }
2821    
2822            // remove the this dimension from the upper limits arrays
2823            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
2824                DimensionRegion* d = pDimensionRegions[j];
2825                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2826                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
2827                }
2828                d->DimensionUpperLimits[Dimensions - 1] = 127;
2829            }
2830    
2831          // 'remove' dimension definition          // 'remove' dimension definition
2832          for (int i = iDimensionNr + 1; i < Dimensions; i++) {          for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2833              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
# Line 2637  namespace { Line 2961  namespace {
2961          }          }
2962          return NULL;          return NULL;
2963      }      }
2964        
2965        /**
2966         * Make a (semi) deep copy of the Region object given by @a orig
2967         * and assign it to this object.
2968         *
2969         * Note that all sample pointers referenced by @a orig are simply copied as
2970         * memory address. Thus the respective samples are shared, not duplicated!
2971         *
2972         * @param orig - original Region object to be copied from
2973         */
2974        void Region::CopyAssign(const Region* orig) {
2975            // handle base classes
2976            DLS::Region::CopyAssign(orig);
2977            
2978            // handle own member variables
2979            for (int i = Dimensions - 1; i >= 0; --i) {
2980                DeleteDimension(&pDimensionDefinitions[i]);
2981            }
2982            Layers = 0; // just to be sure
2983            for (int i = 0; i < orig->Dimensions; i++) {
2984                // we need to copy the dim definition here, to avoid the compiler
2985                // complaining about const-ness issue
2986                dimension_def_t def = orig->pDimensionDefinitions[i];
2987                AddDimension(&def);
2988            }
2989            for (int i = 0; i < 256; i++) {
2990                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
2991                    pDimensionRegions[i]->CopyAssign(
2992                        orig->pDimensionRegions[i]
2993                    );
2994                }
2995            }
2996            Layers = orig->Layers;
2997        }
2998    
2999    
3000    // *************** MidiRule ***************
3001    // *
3002    
3003    MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3004        _3ewg->SetPos(36);
3005        Triggers = _3ewg->ReadUint8();
3006        _3ewg->SetPos(40);
3007        ControllerNumber = _3ewg->ReadUint8();
3008        _3ewg->SetPos(46);
3009        for (int i = 0 ; i < Triggers ; i++) {
3010            pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3011            pTriggers[i].Descending = _3ewg->ReadUint8();
3012            pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3013            pTriggers[i].Key = _3ewg->ReadUint8();
3014            pTriggers[i].NoteOff = _3ewg->ReadUint8();
3015            pTriggers[i].Velocity = _3ewg->ReadUint8();
3016            pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3017            _3ewg->ReadUint8();
3018        }
3019    }
3020    
3021    
3022  // *************** Instrument ***************  // *************** Instrument ***************
3023  // *  // *
3024    
3025      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) {
3026          static const DLS::Info::FixedStringLength fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
3027              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
3028              { CHUNK_ID_ISFT, 12 },              { CHUNK_ID_ISFT, 12 },
3029              { 0, 0 }              { 0, 0 }
3030          };          };
3031          pInfo->FixedStringLengths = fixedStringLengths;          pInfo->SetFixedStringLengths(fixedStringLengths);
3032    
3033          // Initialization          // Initialization
3034          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
# Line 2660  namespace { Line 3039  namespace {
3039          PianoReleaseMode = false;          PianoReleaseMode = false;
3040          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
3041          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
3042            pMidiRules = new MidiRule*[3];
3043            pMidiRules[0] = NULL;
3044    
3045          // Loading          // Loading
3046          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2674  namespace { Line 3055  namespace {
3055                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
3056                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
3057                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
3058    
3059                    if (_3ewg->GetSize() > 32) {
3060                        // read MIDI rules
3061                        int i = 0;
3062                        _3ewg->SetPos(32);
3063                        uint8_t id1 = _3ewg->ReadUint8();
3064                        uint8_t id2 = _3ewg->ReadUint8();
3065    
3066                        if (id1 == 4 && id2 == 16) {
3067                            pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
3068                        }
3069                        //TODO: all the other types of rules
3070    
3071                        pMidiRules[i] = NULL;
3072                    }
3073              }              }
3074          }          }
3075    
3076          if (!pRegions) pRegions = new RegionList;          if (pFile->GetAutoLoad()) {
3077          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);              if (!pRegions) pRegions = new RegionList;
3078          if (lrgn) {              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
3079              RIFF::List* rgn = lrgn->GetFirstSubList();              if (lrgn) {
3080              while (rgn) {                  RIFF::List* rgn = lrgn->GetFirstSubList();
3081                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  while (rgn) {
3082                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                      if (rgn->GetListType() == LIST_TYPE_RGN) {
3083                      pRegions->push_back(new Region(this, rgn));                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
3084                            pRegions->push_back(new Region(this, rgn));
3085                        }
3086                        rgn = lrgn->GetNextSubList();
3087                  }                  }
3088                  rgn = lrgn->GetNextSubList();                  // Creating Region Key Table for fast lookup
3089                    UpdateRegionKeyTable();
3090              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
3091          }          }
3092    
3093          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
3094      }      }
3095    
3096      void Instrument::UpdateRegionKeyTable() {      void Instrument::UpdateRegionKeyTable() {
3097            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3098          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
3099          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
3100          for (; iter != end; ++iter) {          for (; iter != end; ++iter) {
# Line 2707  namespace { Line 3106  namespace {
3106      }      }
3107    
3108      Instrument::~Instrument() {      Instrument::~Instrument() {
3109            for (int i = 0 ; pMidiRules[i] ; i++) {
3110                delete pMidiRules[i];
3111            }
3112            delete[] pMidiRules;
3113      }      }
3114    
3115      /**      /**
# Line 2735  namespace { Line 3138  namespace {
3138          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
3139          // make sure '3ewg' RIFF chunk exists          // make sure '3ewg' RIFF chunk exists
3140          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
3141          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);          if (!_3ewg)  {
3142                File* pFile = (File*) GetParent();
3143    
3144                // 3ewg is bigger in gig3, as it includes the iMIDI rules
3145                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
3146                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
3147                memset(_3ewg->LoadChunkData(), 0, size);
3148            }
3149          // update '3ewg' RIFF chunk          // update '3ewg' RIFF chunk
3150          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
3151          store16(&pData[0], EffectSend);          store16(&pData[0], EffectSend);
3152          store32(&pData[2], Attenuation);          store32(&pData[2], Attenuation);
3153          store16(&pData[6], FineTune);          store16(&pData[6], FineTune);
3154          store16(&pData[8], PitchbendRange);          store16(&pData[8], PitchbendRange);
3155          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |          const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
3156                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
3157          pData[10] = dimkeystart;          pData[10] = dimkeystart;
3158          pData[11] = DimensionKeyRange.high;          pData[11] = DimensionKeyRange.high;
# Line 2756  namespace { Line 3166  namespace {
3166       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
3167       */       */
3168      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
3169          if (!pRegions || !pRegions->size() || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
3170          return RegionKeyTable[Key];          return RegionKeyTable[Key];
3171    
3172          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
# Line 2814  namespace { Line 3224  namespace {
3224          UpdateRegionKeyTable();          UpdateRegionKeyTable();
3225      }      }
3226    
3227        /**
3228         * Returns a MIDI rule of the instrument.
3229         *
3230         * The list of MIDI rules, at least in gig v3, always contains at
3231         * most two rules. The second rule can only be the DEF filter
3232         * (which currently isn't supported by libgig).
3233         *
3234         * @param i - MIDI rule number
3235         * @returns   pointer address to MIDI rule number i or NULL if there is none
3236         */
3237        MidiRule* Instrument::GetMidiRule(int i) {
3238            return pMidiRules[i];
3239        }
3240        
3241        /**
3242         * Make a (semi) deep copy of the Instrument object given by @a orig
3243         * and assign it to this object.
3244         *
3245         * Note that all sample pointers referenced by @a orig are simply copied as
3246         * memory address. Thus the respective samples are shared, not duplicated!
3247         *
3248         * @param orig - original Instrument object to be copied from
3249         */
3250        void Instrument::CopyAssign(const Instrument* orig) {
3251            // handle base class
3252            // (without copying DLS region stuff)
3253            DLS::Instrument::CopyAssignCore(orig);
3254            
3255            // handle own member variables
3256            Attenuation = orig->Attenuation;
3257            EffectSend = orig->EffectSend;
3258            FineTune = orig->FineTune;
3259            PitchbendRange = orig->PitchbendRange;
3260            PianoReleaseMode = orig->PianoReleaseMode;
3261            DimensionKeyRange = orig->DimensionKeyRange;
3262            
3263            // free old midi rules
3264            for (int i = 0 ; pMidiRules[i] ; i++) {
3265                delete pMidiRules[i];
3266            }
3267            //TODO: MIDI rule copying
3268            pMidiRules[0] = NULL;
3269            
3270            // delete all old regions
3271            while (Regions) DeleteRegion(GetFirstRegion());
3272            // create new regions and copy them from original
3273            {
3274                RegionList::const_iterator it = orig->pRegions->begin();
3275                for (int i = 0; i < orig->Regions; ++i, ++it) {
3276                    Region* dstRgn = AddRegion();
3277                    //NOTE: Region does semi-deep copy !
3278                    dstRgn->CopyAssign(
3279                        static_cast<gig::Region*>(*it)
3280                    );
3281                }
3282            }
3283    
3284            UpdateRegionKeyTable();
3285        }
3286    
3287    
3288  // *************** Group ***************  // *************** Group ***************
# Line 2853  namespace { Line 3322  namespace {
3322          }          }
3323          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
3324          if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);          if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
3325    
3326            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
3327                // v3 has a fixed list of 128 strings, find a free one
3328                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
3329                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
3330                        pNameChunk = ck;
3331                        break;
3332                    }
3333                }
3334            }
3335    
3336          // 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
3337          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
3338      }      }
# Line 2928  namespace { Line 3408  namespace {
3408  // *************** File ***************  // *************** File ***************
3409  // *  // *
3410    
3411      // File version 2.0, 1998-06-28      /// Reflects Gigasampler file format version 2.0 (1998-06-28).
3412      const DLS::version_t File::VERSION_2 = {      const DLS::version_t File::VERSION_2 = {
3413          0, 2, 19980628 & 0xffff, 19980628 >> 16          0, 2, 19980628 & 0xffff, 19980628 >> 16
3414      };      };
3415    
3416      // File version 3.0, 2003-03-31      /// Reflects Gigasampler file format version 3.0 (2003-03-31).
3417      const DLS::version_t File::VERSION_3 = {      const DLS::version_t File::VERSION_3 = {
3418          0, 3, 20030331 & 0xffff, 20030331 >> 16          0, 3, 20030331 & 0xffff, 20030331 >> 16
3419      };      };
3420    
3421      const DLS::Info::FixedStringLength File::FixedStringLengths[] = {      static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
3422          { CHUNK_ID_IARL, 256 },          { CHUNK_ID_IARL, 256 },
3423          { CHUNK_ID_IART, 128 },          { CHUNK_ID_IART, 128 },
3424          { CHUNK_ID_ICMS, 128 },          { CHUNK_ID_ICMS, 128 },
# Line 2960  namespace { Line 3440  namespace {
3440      };      };
3441    
3442      File::File() : DLS::File() {      File::File() : DLS::File() {
3443            bAutoLoad = true;
3444            *pVersion = VERSION_3;
3445          pGroups = NULL;          pGroups = NULL;
3446          pInfo->FixedStringLengths = FixedStringLengths;          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3447          pInfo->ArchivalLocation = String(256, ' ');          pInfo->ArchivalLocation = String(256, ' ');
3448    
3449          // add some mandatory chunks to get the file chunks in right          // add some mandatory chunks to get the file chunks in right
3450          // order (INFO chunk will be moved to first position later)          // order (INFO chunk will be moved to first position later)
3451          pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);          pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
3452          pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);          pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
3453            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
3454    
3455            GenerateDLSID();
3456      }      }
3457    
3458      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
3459            bAutoLoad = true;
3460          pGroups = NULL;          pGroups = NULL;
3461          pInfo->FixedStringLengths = FixedStringLengths;          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3462      }      }
3463    
3464      File::~File() {      File::~File() {
# Line 3025  namespace { Line 3511  namespace {
3511    
3512      /** @brief Delete a sample.      /** @brief Delete a sample.
3513       *       *
3514       * 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
3515       * to call Save() to make this persistent to the file.       * references to this sample from Regions and DimensionRegions will be
3516         * removed. You have to call Save() to make this persistent to the file.
3517       *       *
3518       * @param pSample - sample to delete       * @param pSample - sample to delete
3519       * @throws gig::Exception if given sample could not be found       * @throws gig::Exception if given sample could not be found
# Line 3038  namespace { Line 3525  namespace {
3525          if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation          if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
3526          pSamples->erase(iter);          pSamples->erase(iter);
3527          delete pSample;          delete pSample;
3528    
3529            SampleList::iterator tmp = SamplesIterator;
3530            // remove all references to the sample
3531            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
3532                 instrument = GetNextInstrument()) {
3533                for (Region* region = instrument->GetFirstRegion() ; region ;
3534                     region = instrument->GetNextRegion()) {
3535    
3536                    if (region->GetSample() == pSample) region->SetSample(NULL);
3537    
3538                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
3539                        gig::DimensionRegion *d = region->pDimensionRegions[i];
3540                        if (d->pSample == pSample) d->pSample = NULL;
3541                    }
3542                }
3543            }
3544            SamplesIterator = tmp; // restore iterator
3545      }      }
3546    
3547      void File::LoadSamples() {      void File::LoadSamples() {
# Line 3128  namespace { Line 3632  namespace {
3632              progress_t subprogress;              progress_t subprogress;
3633              __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
3634              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
3635              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
3636                    GetFirstSample(&subprogress); // now force all samples to be loaded
3637              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
3638    
3639              // instrument loading subtask              // instrument loading subtask
# Line 3164  namespace { Line 3669  namespace {
3669    
3670         // add mandatory chunks to get the chunks in right order         // add mandatory chunks to get the chunks in right order
3671         lstInstr->AddSubList(LIST_TYPE_INFO);         lstInstr->AddSubList(LIST_TYPE_INFO);
3672           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
3673    
3674         Instrument* pInstrument = new Instrument(this, lstInstr);         Instrument* pInstrument = new Instrument(this, lstInstr);
3675           pInstrument->GenerateDLSID();
3676    
3677         lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);         lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
3678    
# Line 3175  namespace { Line 3682  namespace {
3682         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
3683         return pInstrument;         return pInstrument;
3684      }      }
3685        
3686        /** @brief Add a duplicate of an existing instrument.
3687         *
3688         * Duplicates the instrument definition given by @a orig and adds it
3689         * to this file. This allows in an instrument editor application to
3690         * easily create variations of an instrument, which will be stored in
3691         * the same .gig file, sharing i.e. the same samples.
3692         *
3693         * Note that all sample pointers referenced by @a orig are simply copied as
3694         * memory address. Thus the respective samples are shared, not duplicated!
3695         *
3696         * You have to call Save() to make this persistent to the file.
3697         *
3698         * @param orig - original instrument to be copied
3699         * @returns duplicated copy of the given instrument
3700         */
3701        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
3702            Instrument* instr = AddInstrument();
3703            instr->CopyAssign(orig);
3704            return instr;
3705        }
3706    
3707      /** @brief Delete an instrument.      /** @brief Delete an instrument.
3708       *       *
# Line 3222  namespace { Line 3750  namespace {
3750          }          }
3751      }      }
3752    
3753        /// Updates the 3crc chunk with the checksum of a sample. The
3754        /// update is done directly to disk, as this method is called
3755        /// after File::Save()
3756      void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {      void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
3757          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
3758          if (!_3crc) return;          if (!_3crc) return;
3759    
3760            // get the index of the sample
3761          int iWaveIndex = -1;          int iWaveIndex = -1;
3762          File::SampleList::iterator iter = pSamples->begin();          File::SampleList::iterator iter = pSamples->begin();
3763          File::SampleList::iterator end  = pSamples->end();          File::SampleList::iterator end  = pSamples->end();
# Line 3236  namespace { Line 3769  namespace {
3769          }          }
3770          if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");          if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
3771    
3772            // write the CRC-32 checksum to disk
3773          _3crc->SetPos(iWaveIndex * 8);          _3crc->SetPos(iWaveIndex * 8);
3774          uint32_t tmp = 1;          uint32_t tmp = 1;
3775          _3crc->WriteUint32(&tmp); // unknown, always 1?          _3crc->WriteUint32(&tmp); // unknown, always 1?
# Line 3334  namespace { Line 3868  namespace {
3868                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
3869                  while (ck) {                  while (ck) {
3870                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {
3871                            if (pVersion && pVersion->major == 3 &&
3872                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
3873    
3874                          pGroups->push_back(new Group(this, ck));                          pGroups->push_back(new Group(this, ck));
3875                      }                      }
3876                      ck = lst3gnl->GetNextSubChunk();                      ck = lst3gnl->GetNextSubChunk();
# Line 3361  namespace { Line 3898  namespace {
3898      void File::UpdateChunks() {      void File::UpdateChunks() {
3899          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
3900    
3901            b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
3902    
3903          // first update base class's chunks          // first update base class's chunks
3904          DLS::File::UpdateChunks();          DLS::File::UpdateChunks();
3905    
# Line 3381  namespace { Line 3920  namespace {
3920              for (; iter != end; ++iter) {              for (; iter != end; ++iter) {
3921                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks();
3922              }              }
3923    
3924                // v3: make sure the file has 128 3gnm chunks
3925                if (pVersion && pVersion->major == 3) {
3926                    RIFF::List* _3gnl = pRIFF->GetSubList(LIST_TYPE_3GRI)->GetSubList(LIST_TYPE_3GNL);
3927                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
3928                    for (int i = 0 ; i < 128 ; i++) {
3929                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
3930                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
3931                    }
3932                }
3933          }          }
3934    
3935          // update einf chunk          // update einf chunk
# Line 3424  namespace { Line 3973  namespace {
3973              int totnbusedchannels = 0;              int totnbusedchannels = 0;
3974              int totnbregions = 0;              int totnbregions = 0;
3975              int totnbdimregions = 0;              int totnbdimregions = 0;
3976                int totnbloops = 0;
3977              int instrumentIdx = 0;              int instrumentIdx = 0;
3978    
3979              memset(&pData[48], 0, sublen - 48);              memset(&pData[48], 0, sublen - 48);
# Line 3433  namespace { Line 3983  namespace {
3983                  int nbusedsamples = 0;                  int nbusedsamples = 0;
3984                  int nbusedchannels = 0;                  int nbusedchannels = 0;
3985                  int nbdimregions = 0;                  int nbdimregions = 0;
3986                    int nbloops = 0;
3987    
3988                  memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);                  memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
3989    
# Line 3456  namespace { Line 4007  namespace {
4007                                  }                                  }
4008                              }                              }
4009                          }                          }
4010                            if (d->SampleLoops) nbloops++;
4011                      }                      }
4012                      nbdimregions += region->DimensionRegions;                      nbdimregions += region->DimensionRegions;
4013                  }                  }
# Line 3466  namespace { Line 4018  namespace {
4018                  store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);                  store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
4019                  store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);                  store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
4020                  store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);                  store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
4021                  // next 12 bytes unknown                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
4022                    // next 8 bytes unknown
4023                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
4024                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
4025                  // next 4 bytes unknown                  // next 4 bytes unknown
4026    
4027                  totnbregions += instrument->Regions;                  totnbregions += instrument->Regions;
4028                  totnbdimregions += nbdimregions;                  totnbdimregions += nbdimregions;
4029                    totnbloops += nbloops;
4030                  instrumentIdx++;                  instrumentIdx++;
4031              }              }
4032              // first 4 bytes unknown - sometimes 0, sometimes length of einf part              // first 4 bytes unknown - sometimes 0, sometimes length of einf part
# Line 3482  namespace { Line 4036  namespace {
4036              store32(&pData[12], Instruments);              store32(&pData[12], Instruments);
4037              store32(&pData[16], totnbregions);              store32(&pData[16], totnbregions);
4038              store32(&pData[20], totnbdimregions);              store32(&pData[20], totnbdimregions);
4039              // next 12 bytes unknown              store32(&pData[24], totnbloops);
4040              // next 4 bytes unknown, always 0?              // next 8 bytes unknown
4041                // next 4 bytes unknown, not always 0
4042              store32(&pData[40], pSamples->size());              store32(&pData[40], pSamples->size());
4043              // next 4 bytes unknown              // next 4 bytes unknown
4044          }          }
# Line 3500  namespace { Line 4055  namespace {
4055          } else if (newFile) {          } else if (newFile) {
4056              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
4057              _3crc->LoadChunkData();              _3crc->LoadChunkData();
4058    
4059                // the order of einf and 3crc is not the same in v2 and v3
4060                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
4061          }          }
4062      }      }
4063    
4064        /**
4065         * Enable / disable automatic loading. By default this properyt is
4066         * enabled and all informations are loaded automatically. However
4067         * loading all Regions, DimensionRegions and especially samples might
4068         * take a long time for large .gig files, and sometimes one might only
4069         * be interested in retrieving very superficial informations like the
4070         * amount of instruments and their names. In this case one might disable
4071         * automatic loading to avoid very slow response times.
4072         *
4073         * @e CAUTION: by disabling this property many pointers (i.e. sample
4074         * references) and informations will have invalid or even undefined
4075         * data! This feature is currently only intended for retrieving very
4076         * superficial informations in a very fast way. Don't use it to retrieve
4077         * details like synthesis informations or even to modify .gig files!
4078         */
4079        void File::SetAutoLoad(bool b) {
4080            bAutoLoad = b;
4081        }
4082    
4083        /**
4084         * Returns whether automatic loading is enabled.
4085         * @see SetAutoLoad()
4086         */
4087        bool File::GetAutoLoad() {
4088            return bAutoLoad;
4089        }
4090    
4091    
4092    
4093  // *************** Exception ***************  // *************** Exception ***************

Legend:
Removed from v.1199  
changed lines
  Added in v.2394

  ViewVC Help
Powered by ViewVC