/[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 1098 by schoenebeck, Thu Mar 15 00:32:06 2007 UTC revision 1875 by schoenebeck, Thu Mar 26 13:32:59 2009 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-2009 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 254  namespace { Line 255  namespace {
255  }  }
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  ***************
323    // *
324    
325        static split_type_t __resolveSplitType(dimension_t dimension) {
326            return (
327                dimension == dimension_layer ||
328                dimension == dimension_samplechannel ||
329                dimension == dimension_releasetrigger ||
330                dimension == dimension_keyboard ||
331                dimension == dimension_roundrobin ||
332                dimension == dimension_random ||
333                dimension == dimension_smartmidi ||
334                dimension == dimension_roundrobinkeyboard
335            ) ? split_type_bit : split_type_normal;
336        }
337    
338        static int __resolveZoneSize(dimension_def_t& dimension_definition) {
339            return (dimension_definition.split_type == split_type_normal)
340            ? int(128.0 / dimension_definition.zones) : 0;
341        }
342    
343    
344    
345  // *************** Sample ***************  // *************** Sample ***************
346  // *  // *
347    
# Line 279  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          pInfo->UseFixedLengthStrings = true;          static const DLS::Info::string_length_t fixedStringLengths[] = {
371                { CHUNK_ID_INAM, 64 },
372                { 0, 0 }
373            };
374            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 314  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;
414              SMPTEOffset   = 0;              SMPTEOffset   = 0;
415              Loops         = 0;              Loops         = 0;
416              LoopID        = 0;              LoopID        = 0;
417                LoopType      = loop_type_normal;
418              LoopStart     = 0;              LoopStart     = 0;
419              LoopEnd       = 0;              LoopEnd       = 0;
420              LoopFraction  = 0;              LoopFraction  = 0;
# Line 374  namespace { Line 470  namespace {
470    
471          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
472          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
473          if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);          if (!pCkSmpl) {
474                pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
475                memset(pCkSmpl->LoadChunkData(), 0, 60);
476            }
477          // update 'smpl' chunk          // update 'smpl' chunk
478          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
479          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
480          memcpy(&pData[0], &Manufacturer, 4);          store32(&pData[0], Manufacturer);
481          memcpy(&pData[4], &Product, 4);          store32(&pData[4], Product);
482          memcpy(&pData[8], &SamplePeriod, 4);          store32(&pData[8], SamplePeriod);
483          memcpy(&pData[12], &MIDIUnityNote, 4);          store32(&pData[12], MIDIUnityNote);
484          memcpy(&pData[16], &FineTune, 4);          store32(&pData[16], FineTune);
485          memcpy(&pData[20], &SMPTEFormat, 4);          store32(&pData[20], SMPTEFormat);
486          memcpy(&pData[24], &SMPTEOffset, 4);          store32(&pData[24], SMPTEOffset);
487          memcpy(&pData[28], &Loops, 4);          store32(&pData[28], Loops);
488    
489          // we skip 'manufByt' for now (4 bytes)          // we skip 'manufByt' for now (4 bytes)
490    
491          memcpy(&pData[36], &LoopID, 4);          store32(&pData[36], LoopID);
492          memcpy(&pData[40], &LoopType, 4);          store32(&pData[40], LoopType);
493          memcpy(&pData[44], &LoopStart, 4);          store32(&pData[44], LoopStart);
494          memcpy(&pData[48], &LoopEnd, 4);          store32(&pData[48], LoopEnd);
495          memcpy(&pData[52], &LoopFraction, 4);          store32(&pData[52], LoopFraction);
496          memcpy(&pData[56], &LoopPlayCount, 4);          store32(&pData[56], LoopPlayCount);
497    
498          // make sure '3gix' chunk exists          // make sure '3gix' chunk exists
499          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
# Line 414  namespace { Line 513  namespace {
513          }          }
514          // update '3gix' chunk          // update '3gix' chunk
515          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
516          memcpy(&pData[0], &iSampleGroup, 2);          store16(&pData[0], iSampleGroup);
517      }      }
518    
519      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
# Line 578  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 615  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 809  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 1099  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 1107  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          return DLS::Sample::Write(pBuffer, SampleCount);  
1217            // if this is the first write in this sample, reset the
1218            // checksum calculator
1219            if (pCkData->GetPos() == 0) {
1220                __resetCRC(crc);
1221            }
1222            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1223            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()) {
1235                File* pFile = static_cast<File*>(GetParent());
1236                pFile->SetSampleChecksum(this, __encodeCRC(crc));
1237            }
1238            return res;
1239      }      }
1240    
1241      /**      /**
# Line 1183  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 1352  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 1369  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 1423  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            *this = src; // default memberwise shallow copy of all parameters
1585            pParentList = _3ewl; // restore the chunk pointer
1586    
1587          // even stranger GSt: two of the velocity response curves for          // deep copy of owned structures
1588          // filter cutoff are not used, instead another special curve          if (src.VelocityTable) {
1589          // is chosen. This curve is not used anywhere else.              VelocityTable = new uint8_t[128];
1590          if ((curveType == curve_type_nonlinear && depth == 0) ||              for (int k = 0 ; k < 128 ; k++)
1591              (curveType == curve_type_special   && depth == 4)) {                  VelocityTable[k] = src.VelocityTable[k];
             curveType = curve_type_special;  
             depth = 5;  
1592          }          }
1593          pVelocityCutoffTable = GetVelocityTable(curveType, depth,          if (src.pSampleLoops) {
1594                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);              pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1595                for (int k = 0 ; k < src.SampleLoops ; k++)
1596                    pSampleLoops[k] = src.pSampleLoops[k];
1597            }
1598        }
1599    
1600        /**
1601         * Updates the respective member variable and updates @c SampleAttenuation
1602         * which depends on this value.
1603         */
1604        void DimensionRegion::SetGain(int32_t gain) {
1605            DLS::Sampler::SetGain(gain);
1606          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
         VelocityTable = 0;  
1607      }      }
1608    
1609      /**      /**
# Line 1472  namespace { Line 1617  namespace {
1617          // first update base class's chunk          // first update base class's chunk
1618          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks();
1619    
1620            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1621            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1622            pData[12] = Crossfade.in_start;
1623            pData[13] = Crossfade.in_end;
1624            pData[14] = Crossfade.out_start;
1625            pData[15] = Crossfade.out_end;
1626    
1627          // make sure '3ewa' chunk exists          // make sure '3ewa' chunk exists
1628          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1629          if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);          if (!_3ewa) {
1630          uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();              File* pFile = (File*) GetParent()->GetParent()->GetParent();
1631                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1632                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1633            }
1634            pData = (uint8_t*) _3ewa->LoadChunkData();
1635    
1636          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1637    
1638          const uint32_t chunksize = _3ewa->GetSize();          const uint32_t chunksize = _3ewa->GetNewSize();
1639          memcpy(&pData[0], &chunksize, 4); // unknown, always chunk size?          store32(&pData[0], chunksize); // unknown, always chunk size?
1640    
1641          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1642          memcpy(&pData[4], &lfo3freq, 4);          store32(&pData[4], lfo3freq);
1643    
1644          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1645          memcpy(&pData[8], &eg3attack, 4);          store32(&pData[8], eg3attack);
1646    
1647          // next 2 bytes unknown          // next 2 bytes unknown
1648    
1649          memcpy(&pData[14], &LFO1InternalDepth, 2);          store16(&pData[14], LFO1InternalDepth);
1650    
1651          // next 2 bytes unknown          // next 2 bytes unknown
1652    
1653          memcpy(&pData[18], &LFO3InternalDepth, 2);          store16(&pData[18], LFO3InternalDepth);
1654    
1655          // next 2 bytes unknown          // next 2 bytes unknown
1656    
1657          memcpy(&pData[22], &LFO1ControlDepth, 2);          store16(&pData[22], LFO1ControlDepth);
1658    
1659          // next 2 bytes unknown          // next 2 bytes unknown
1660    
1661          memcpy(&pData[26], &LFO3ControlDepth, 2);          store16(&pData[26], LFO3ControlDepth);
1662    
1663          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1664          memcpy(&pData[28], &eg1attack, 4);          store32(&pData[28], eg1attack);
1665    
1666          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1667          memcpy(&pData[32], &eg1decay1, 4);          store32(&pData[32], eg1decay1);
1668    
1669          // next 2 bytes unknown          // next 2 bytes unknown
1670    
1671          memcpy(&pData[38], &EG1Sustain, 2);          store16(&pData[38], EG1Sustain);
1672    
1673          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1674          memcpy(&pData[40], &eg1release, 4);          store32(&pData[40], eg1release);
1675    
1676          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1677          memcpy(&pData[44], &eg1ctl, 1);          pData[44] = eg1ctl;
1678    
1679          const uint8_t eg1ctrloptions =          const uint8_t eg1ctrloptions =
1680              (EG1ControllerInvert) ? 0x01 : 0x00 |              (EG1ControllerInvert ? 0x01 : 0x00) |
1681              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1682              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1683              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1684          memcpy(&pData[45], &eg1ctrloptions, 1);          pData[45] = eg1ctrloptions;
1685    
1686          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1687          memcpy(&pData[46], &eg2ctl, 1);          pData[46] = eg2ctl;
1688    
1689          const uint8_t eg2ctrloptions =          const uint8_t eg2ctrloptions =
1690              (EG2ControllerInvert) ? 0x01 : 0x00 |              (EG2ControllerInvert ? 0x01 : 0x00) |
1691              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1692              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1693              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1694          memcpy(&pData[47], &eg2ctrloptions, 1);          pData[47] = eg2ctrloptions;
1695    
1696          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1697          memcpy(&pData[48], &lfo1freq, 4);          store32(&pData[48], lfo1freq);
1698    
1699          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1700          memcpy(&pData[52], &eg2attack, 4);          store32(&pData[52], eg2attack);
1701    
1702          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1703          memcpy(&pData[56], &eg2decay1, 4);          store32(&pData[56], eg2decay1);
1704    
1705          // next 2 bytes unknown          // next 2 bytes unknown
1706    
1707          memcpy(&pData[62], &EG2Sustain, 2);          store16(&pData[62], EG2Sustain);
1708    
1709          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1710          memcpy(&pData[64], &eg2release, 4);          store32(&pData[64], eg2release);
1711    
1712          // next 2 bytes unknown          // next 2 bytes unknown
1713    
1714          memcpy(&pData[70], &LFO2ControlDepth, 2);          store16(&pData[70], LFO2ControlDepth);
1715    
1716          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1717          memcpy(&pData[72], &lfo2freq, 4);          store32(&pData[72], lfo2freq);
1718    
1719          // next 2 bytes unknown          // next 2 bytes unknown
1720    
1721          memcpy(&pData[78], &LFO2InternalDepth, 2);          store16(&pData[78], LFO2InternalDepth);
1722    
1723          const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);          const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1724          memcpy(&pData[80], &eg1decay2, 4);          store32(&pData[80], eg1decay2);
1725    
1726          // next 2 bytes unknown          // next 2 bytes unknown
1727    
1728          memcpy(&pData[86], &EG1PreAttack, 2);          store16(&pData[86], EG1PreAttack);
1729    
1730          const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);          const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1731          memcpy(&pData[88], &eg2decay2, 4);          store32(&pData[88], eg2decay2);
1732    
1733          // next 2 bytes unknown          // next 2 bytes unknown
1734    
1735          memcpy(&pData[94], &EG2PreAttack, 2);          store16(&pData[94], EG2PreAttack);
1736    
1737          {          {
1738              if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");              if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
# Line 1594  namespace { Line 1750  namespace {
1750                  default:                  default:
1751                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1752              }              }
1753              memcpy(&pData[96], &velocityresponse, 1);              pData[96] = velocityresponse;
1754          }          }
1755    
1756          {          {
# Line 1613  namespace { Line 1769  namespace {
1769                  default:                  default:
1770                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1771              }              }
1772              memcpy(&pData[97], &releasevelocityresponse, 1);              pData[97] = releasevelocityresponse;
1773          }          }
1774    
1775          memcpy(&pData[98], &VelocityResponseCurveScaling, 1);          pData[98] = VelocityResponseCurveScaling;
1776    
1777          memcpy(&pData[99], &AttenuationControllerThreshold, 1);          pData[99] = AttenuationControllerThreshold;
1778    
1779          // next 4 bytes unknown          // next 4 bytes unknown
1780    
1781          memcpy(&pData[104], &SampleStartOffset, 2);          store16(&pData[104], SampleStartOffset);
1782    
1783          // next 2 bytes unknown          // next 2 bytes unknown
1784    
# Line 1641  namespace { Line 1797  namespace {
1797                  default:                  default:
1798                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1799              }              }
1800              memcpy(&pData[108], &pitchTrackDimensionBypass, 1);              pData[108] = pitchTrackDimensionBypass;
1801          }          }
1802    
1803          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1804          memcpy(&pData[109], &pan, 1);          pData[109] = pan;
1805    
1806          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1807          memcpy(&pData[110], &selfmask, 1);          pData[110] = selfmask;
1808    
1809          // next byte unknown          // next byte unknown
1810    
# Line 1657  namespace { Line 1813  namespace {
1813              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1814              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1815              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1816              memcpy(&pData[112], &lfo3ctrl, 1);              pData[112] = lfo3ctrl;
1817          }          }
1818    
1819          const uint8_t attenctl = EncodeLeverageController(AttenuationController);          const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1820          memcpy(&pData[113], &attenctl, 1);          pData[113] = attenctl;
1821    
1822          {          {
1823              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1824              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1825              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1826              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1827              memcpy(&pData[114], &lfo2ctrl, 1);              pData[114] = lfo2ctrl;
1828          }          }
1829    
1830          {          {
# Line 1677  namespace { Line 1833  namespace {
1833              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1834              if (VCFResonanceController != vcf_res_ctrl_none)              if (VCFResonanceController != vcf_res_ctrl_none)
1835                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1836              memcpy(&pData[115], &lfo1ctrl, 1);              pData[115] = lfo1ctrl;
1837          }          }
1838    
1839          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1840                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1841          memcpy(&pData[116], &eg3depth, 1);          store16(&pData[116], eg3depth);
1842    
1843          // next 2 bytes unknown          // next 2 bytes unknown
1844    
1845          const uint8_t channeloffset = ChannelOffset * 4;          const uint8_t channeloffset = ChannelOffset * 4;
1846          memcpy(&pData[120], &channeloffset, 1);          pData[120] = channeloffset;
1847    
1848          {          {
1849              uint8_t regoptions = 0;              uint8_t regoptions = 0;
1850              if (MSDecode)      regoptions |= 0x01; // bit 0              if (MSDecode)      regoptions |= 0x01; // bit 0
1851              if (SustainDefeat) regoptions |= 0x02; // bit 1              if (SustainDefeat) regoptions |= 0x02; // bit 1
1852              memcpy(&pData[121], &regoptions, 1);              pData[121] = regoptions;
1853          }          }
1854    
1855          // next 2 bytes unknown          // next 2 bytes unknown
1856    
1857          memcpy(&pData[124], &VelocityUpperLimit, 1);          pData[124] = VelocityUpperLimit;
1858    
1859          // next 3 bytes unknown          // next 3 bytes unknown
1860    
1861          memcpy(&pData[128], &ReleaseTriggerDecay, 1);          pData[128] = ReleaseTriggerDecay;
1862    
1863          // next 2 bytes unknown          // next 2 bytes unknown
1864    
1865          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1866          memcpy(&pData[131], &eg1hold, 1);          pData[131] = eg1hold;
1867    
1868          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */          const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
1869                                    (VCFCutoff & 0x7f);   /* lower 7 bits */                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
1870          memcpy(&pData[132], &vcfcutoff, 1);          pData[132] = vcfcutoff;
1871    
1872          memcpy(&pData[133], &VCFCutoffController, 1);          pData[133] = VCFCutoffController;
1873    
1874          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
1875                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
1876          memcpy(&pData[134], &vcfvelscale, 1);          pData[134] = vcfvelscale;
1877    
1878          // next byte unknown          // next byte unknown
1879    
1880          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */          const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
1881                                       (VCFResonance & 0x7f); /* lower 7 bits */                                       (VCFResonance & 0x7f); /* lower 7 bits */
1882          memcpy(&pData[136], &vcfresonance, 1);          pData[136] = vcfresonance;
1883    
1884          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
1885                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
1886          memcpy(&pData[137], &vcfbreakpoint, 1);          pData[137] = vcfbreakpoint;
1887    
1888          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1889                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
1890          memcpy(&pData[138], &vcfvelocity, 1);          pData[138] = vcfvelocity;
1891    
1892          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1893          memcpy(&pData[139], &vcftype, 1);          pData[139] = vcftype;
1894    
1895          if (chunksize >= 148) {          if (chunksize >= 148) {
1896              memcpy(&pData[140], DimensionUpperLimits, 8);              memcpy(&pData[140], DimensionUpperLimits, 8);
1897          }          }
1898      }      }
1899    
1900        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
1901            curve_type_t curveType = releaseVelocityResponseCurve;
1902            uint8_t depth = releaseVelocityResponseDepth;
1903            // this models a strange behaviour or bug in GSt: two of the
1904            // velocity response curves for release time are not used even
1905            // if specified, instead another curve is chosen.
1906            if ((curveType == curve_type_nonlinear && depth == 0) ||
1907                (curveType == curve_type_special   && depth == 4)) {
1908                curveType = curve_type_nonlinear;
1909                depth = 3;
1910            }
1911            return GetVelocityTable(curveType, depth, 0);
1912        }
1913    
1914        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
1915                                                        uint8_t vcfVelocityDynamicRange,
1916                                                        uint8_t vcfVelocityScale,
1917                                                        vcf_cutoff_ctrl_t vcfCutoffController)
1918        {
1919            curve_type_t curveType = vcfVelocityCurve;
1920            uint8_t depth = vcfVelocityDynamicRange;
1921            // even stranger GSt: two of the velocity response curves for
1922            // filter cutoff are not used, instead another special curve
1923            // is chosen. This curve is not used anywhere else.
1924            if ((curveType == curve_type_nonlinear && depth == 0) ||
1925                (curveType == curve_type_special   && depth == 4)) {
1926                curveType = curve_type_special;
1927                depth = 5;
1928            }
1929            return GetVelocityTable(curveType, depth,
1930                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
1931                                        ? vcfVelocityScale : 0);
1932        }
1933    
1934      // 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
1935      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)
1936      {      {
# Line 1756  namespace { Line 1946  namespace {
1946          return table;          return table;
1947      }      }
1948    
1949        Region* DimensionRegion::GetParent() const {
1950            return pRegion;
1951        }
1952    
1953      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
1954          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
1955          switch (EncodedController) {          switch (EncodedController) {
# Line 1963  namespace { Line 2157  namespace {
2157                      default:                      default:
2158                          throw gig::Exception("leverage controller number is not supported by the gig format");                          throw gig::Exception("leverage controller number is not supported by the gig format");
2159                  }                  }
2160                    break;
2161              default:              default:
2162                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2163          }          }
# Line 2008  namespace { Line 2203  namespace {
2203          return pVelocityCutoffTable[MIDIKeyVelocity];          return pVelocityCutoffTable[MIDIKeyVelocity];
2204      }      }
2205    
2206        /**
2207         * Updates the respective member variable and the lookup table / cache
2208         * that depends on this value.
2209         */
2210        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2211            pVelocityAttenuationTable =
2212                GetVelocityTable(
2213                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2214                );
2215            VelocityResponseCurve = curve;
2216        }
2217    
2218        /**
2219         * Updates the respective member variable and the lookup table / cache
2220         * that depends on this value.
2221         */
2222        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2223            pVelocityAttenuationTable =
2224                GetVelocityTable(
2225                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2226                );
2227            VelocityResponseDepth = depth;
2228        }
2229    
2230        /**
2231         * Updates the respective member variable and the lookup table / cache
2232         * that depends on this value.
2233         */
2234        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2235            pVelocityAttenuationTable =
2236                GetVelocityTable(
2237                    VelocityResponseCurve, VelocityResponseDepth, scaling
2238                );
2239            VelocityResponseCurveScaling = scaling;
2240        }
2241    
2242        /**
2243         * Updates the respective member variable and the lookup table / cache
2244         * that depends on this value.
2245         */
2246        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2247            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2248            ReleaseVelocityResponseCurve = curve;
2249        }
2250    
2251        /**
2252         * Updates the respective member variable and the lookup table / cache
2253         * that depends on this value.
2254         */
2255        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2256            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2257            ReleaseVelocityResponseDepth = depth;
2258        }
2259    
2260        /**
2261         * Updates the respective member variable and the lookup table / cache
2262         * that depends on this value.
2263         */
2264        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2265            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2266            VCFCutoffController = controller;
2267        }
2268    
2269        /**
2270         * Updates the respective member variable and the lookup table / cache
2271         * that depends on this value.
2272         */
2273        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2274            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2275            VCFVelocityCurve = curve;
2276        }
2277    
2278        /**
2279         * Updates the respective member variable and the lookup table / cache
2280         * that depends on this value.
2281         */
2282        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2283            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2284            VCFVelocityDynamicRange = range;
2285        }
2286    
2287        /**
2288         * Updates the respective member variable and the lookup table / cache
2289         * that depends on this value.
2290         */
2291        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2292            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2293            VCFVelocityScale = scaling;
2294        }
2295    
2296      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) {
2297    
2298          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 2080  namespace { Line 2365  namespace {
2365  // *  // *
2366    
2367      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
         pInfo->UseFixedLengthStrings = true;  
   
2368          // Initialization          // Initialization
2369          Dimensions = 0;          Dimensions = 0;
2370          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
# Line 2093  namespace { Line 2376  namespace {
2376    
2377          // Actual Loading          // Actual Loading
2378    
2379            if (!file->GetAutoLoad()) return;
2380    
2381          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2382    
2383          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2101  namespace { Line 2386  namespace {
2386              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2387                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2388                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2389                  _3lnk->ReadUint8(); // probably the position of the dimension                  _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2390                  _3lnk->ReadUint8(); // unknown                  _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2391                  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)
2392                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2393                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
# Line 2115  namespace { Line 2400  namespace {
2400                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2401                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2402                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2403                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2404                                                             dimension == dimension_samplechannel ||                      pDimensionDefinitions[i].zone_size  = __resolveZoneSize(pDimensionDefinitions[i]);
                                                            dimension == dimension_releasetrigger ||  
                                                            dimension == dimension_keyboard ||  
                                                            dimension == dimension_roundrobin ||  
                                                            dimension == dimension_random ||  
                                                            dimension == dimension_smartmidi ||  
                                                            dimension == dimension_roundrobinkeyboard) ? split_type_bit  
                                                                                                       : split_type_normal;  
                     pDimensionDefinitions[i].zone_size  =  
                         (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones  
                                                                                    : 0;  
2405                      Dimensions++;                      Dimensions++;
2406    
2407                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
# Line 2146  namespace { Line 2421  namespace {
2421              else              else
2422                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
2423    
2424              // load sample references              // load sample references (if auto loading is enabled)
2425              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
2426                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
2427                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2428                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2429                    }
2430                    GetSample(); // load global region sample reference
2431                }
2432            } else {
2433                DimensionRegions = 0;
2434                for (int i = 0 ; i < 8 ; i++) {
2435                    pDimensionDefinitions[i].dimension  = dimension_none;
2436                    pDimensionDefinitions[i].bits       = 0;
2437                    pDimensionDefinitions[i].zones      = 0;
2438              }              }
             GetSample(); // load global region sample reference  
2439          }          }
2440    
2441          // make sure there is at least one dimension region          // make sure there is at least one dimension region
# Line 2159  namespace { Line 2443  namespace {
2443              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2444              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2445              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2446              pDimensionRegions[0] = new DimensionRegion(_3ewl);              pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
2447              DimensionRegions = 1;              DimensionRegions = 1;
2448          }          }
2449      }      }
# Line 2174  namespace { Line 2458  namespace {
2458       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
2459       */       */
2460      void Region::UpdateChunks() {      void Region::UpdateChunks() {
2461            // in the gig format we don't care about the Region's sample reference
2462            // but we still have to provide some existing one to not corrupt the
2463            // file, so to avoid the latter we simply always assign the sample of
2464            // the first dimension region of this region
2465            pSample = pDimensionRegions[0]->pSample;
2466    
2467          // first update base class's chunks          // first update base class's chunks
2468          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks();
2469    
# Line 2183  namespace { Line 2473  namespace {
2473          }          }
2474    
2475          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
2476          const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;          bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
2477          const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;          const int iMaxDimensions =  version3 ? 8 : 5;
2478            const int iMaxDimensionRegions = version3 ? 256 : 32;
2479    
2480          // make sure '3lnk' chunk exists          // make sure '3lnk' chunk exists
2481          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2482          if (!_3lnk) {          if (!_3lnk) {
2483              const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;              const int _3lnkChunkSize = version3 ? 1092 : 172;
2484              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2485                memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
2486    
2487                // move 3prg to last position
2488                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);
2489          }          }
2490    
2491          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
2492          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2493          memcpy(&pData[0], &DimensionRegions, 4);          store32(&pData[0], DimensionRegions);
2494            int shift = 0;
2495          for (int i = 0; i < iMaxDimensions; i++) {          for (int i = 0; i < iMaxDimensions; i++) {
2496              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2497              pData[5 + i * 8] = pDimensionDefinitions[i].bits;              pData[5 + i * 8] = pDimensionDefinitions[i].bits;
2498              // next 2 bytes unknown              pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
2499                pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
2500              pData[8 + i * 8] = pDimensionDefinitions[i].zones;              pData[8 + i * 8] = pDimensionDefinitions[i].zones;
2501              // next 3 bytes unknown              // next 3 bytes unknown, always zero?
2502    
2503                shift += pDimensionDefinitions[i].bits;
2504          }          }
2505    
2506          // update wave pool table in '3lnk' chunk          // update wave pool table in '3lnk' chunk
2507          const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;          const int iWavePoolOffset = version3 ? 68 : 44;
2508          for (uint i = 0; i < iMaxDimensionRegions; i++) {          for (uint i = 0; i < iMaxDimensionRegions; i++) {
2509              int iWaveIndex = -1;              int iWaveIndex = -1;
2510              if (i < DimensionRegions) {              if (i < DimensionRegions) {
# Line 2218  namespace { Line 2517  namespace {
2517                          break;                          break;
2518                      }                      }
2519                  }                  }
                 if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");  
2520              }              }
2521              memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
2522          }          }
2523      }      }
2524    
# Line 2231  namespace { Line 2529  namespace {
2529              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
2530              while (_3ewl) {              while (_3ewl) {
2531                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
2532                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
2533                      dimensionRegionNr++;                      dimensionRegionNr++;
2534                  }                  }
2535                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 2240  namespace { Line 2538  namespace {
2538          }          }
2539      }      }
2540    
2541        void Region::SetKeyRange(uint16_t Low, uint16_t High) {
2542            // update KeyRange struct and make sure regions are in correct order
2543            DLS::Region::SetKeyRange(Low, High);
2544            // update Region key table for fast lookup
2545            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
2546        }
2547    
2548      void Region::UpdateVelocityTable() {      void Region::UpdateVelocityTable() {
2549          // get velocity dimension's index          // get velocity dimension's index
2550          int veldim = -1;          int veldim = -1;
# Line 2345  namespace { Line 2650  namespace {
2650              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2651                  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");
2652    
2653            // pos is where the new dimension should be placed, normally
2654            // last in list, except for the samplechannel dimension which
2655            // has to be first in list
2656            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
2657            int bitpos = 0;
2658            for (int i = 0 ; i < pos ; i++)
2659                bitpos += pDimensionDefinitions[i].bits;
2660    
2661            // make room for the new dimension
2662            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
2663            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
2664                for (int j = Dimensions ; j > pos ; j--) {
2665                    pDimensionRegions[i]->DimensionUpperLimits[j] =
2666                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
2667                }
2668            }
2669    
2670          // assign definition of new dimension          // assign definition of new dimension
2671          pDimensionDefinitions[Dimensions] = *pDimDef;          pDimensionDefinitions[pos] = *pDimDef;
2672    
2673          // create new dimension region(s) for this new dimension          // auto correct certain dimension definition fields (where possible)
2674          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {          pDimensionDefinitions[pos].split_type  =
2675              //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values              __resolveSplitType(pDimensionDefinitions[pos].dimension);
2676              RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);          pDimensionDefinitions[pos].zone_size =
2677              pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);              __resolveZoneSize(pDimensionDefinitions[pos]);
2678              DimensionRegions++;  
2679            // create new dimension region(s) for this new dimension, and make
2680            // sure that the dimension regions are placed correctly in both the
2681            // RIFF list and the pDimensionRegions array
2682            RIFF::Chunk* moveTo = NULL;
2683            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2684            for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
2685                for (int k = 0 ; k < (1 << bitpos) ; k++) {
2686                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
2687                }
2688                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
2689                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
2690                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
2691                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
2692                        // create a new dimension region and copy all parameter values from
2693                        // an existing dimension region
2694                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
2695                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
2696    
2697                        DimensionRegions++;
2698                    }
2699                }
2700                moveTo = pDimensionRegions[i]->pParentList;
2701            }
2702    
2703            // initialize the upper limits for this dimension
2704            int mask = (1 << bitpos) - 1;
2705            for (int z = 0 ; z < pDimDef->zones ; z++) {
2706                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
2707                for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
2708                    pDimensionRegions[((i & ~mask) << pDimDef->bits) |
2709                                      (z << bitpos) |
2710                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
2711                }
2712          }          }
2713    
2714          Dimensions++;          Dimensions++;
# Line 2396  namespace { Line 2751  namespace {
2751          for (int i = iDimensionNr + 1; i < Dimensions; i++)          for (int i = iDimensionNr + 1; i < Dimensions; i++)
2752              iUpperBits += pDimensionDefinitions[i].bits;              iUpperBits += pDimensionDefinitions[i].bits;
2753    
2754            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2755    
2756          // delete dimension regions which belong to the given dimension          // delete dimension regions which belong to the given dimension
2757          // (that is where the dimension's bit > 0)          // (that is where the dimension's bit > 0)
2758          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
# Line 2404  namespace { Line 2761  namespace {
2761                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2762                                      iObsoleteBit << iLowerBits |                                      iObsoleteBit << iLowerBits |
2763                                      iLowerBit;                                      iLowerBit;
2764    
2765                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
2766                      delete pDimensionRegions[iToDelete];                      delete pDimensionRegions[iToDelete];
2767                      pDimensionRegions[iToDelete] = NULL;                      pDimensionRegions[iToDelete] = NULL;
2768                      DimensionRegions--;                      DimensionRegions--;
# Line 2424  namespace { Line 2783  namespace {
2783              }              }
2784          }          }
2785    
2786            // remove the this dimension from the upper limits arrays
2787            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
2788                DimensionRegion* d = pDimensionRegions[j];
2789                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2790                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
2791                }
2792                d->DimensionUpperLimits[Dimensions - 1] = 127;
2793            }
2794    
2795          // 'remove' dimension definition          // 'remove' dimension definition
2796          for (int i = iDimensionNr + 1; i < Dimensions; i++) {          for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2797              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
# Line 2559  namespace { Line 2927  namespace {
2927      }      }
2928    
2929    
2930    // *************** MidiRule ***************
2931    // *
2932    
2933    MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
2934        _3ewg->SetPos(36);
2935        Triggers = _3ewg->ReadUint8();
2936        _3ewg->SetPos(40);
2937        ControllerNumber = _3ewg->ReadUint8();
2938        _3ewg->SetPos(46);
2939        for (int i = 0 ; i < Triggers ; i++) {
2940            pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
2941            pTriggers[i].Descending = _3ewg->ReadUint8();
2942            pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
2943            pTriggers[i].Key = _3ewg->ReadUint8();
2944            pTriggers[i].NoteOff = _3ewg->ReadUint8();
2945            pTriggers[i].Velocity = _3ewg->ReadUint8();
2946            pTriggers[i].OverridePedal = _3ewg->ReadUint8();
2947            _3ewg->ReadUint8();
2948        }
2949    }
2950    
2951    
2952  // *************** Instrument ***************  // *************** Instrument ***************
2953  // *  // *
2954    
2955      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) {
2956          pInfo->UseFixedLengthStrings = true;          static const DLS::Info::string_length_t fixedStringLengths[] = {
2957                { CHUNK_ID_INAM, 64 },
2958                { CHUNK_ID_ISFT, 12 },
2959                { 0, 0 }
2960            };
2961            pInfo->SetFixedStringLengths(fixedStringLengths);
2962    
2963          // Initialization          // Initialization
2964          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
2965            EffectSend = 0;
2966            Attenuation = 0;
2967            FineTune = 0;
2968            PitchbendRange = 0;
2969            PianoReleaseMode = false;
2970            DimensionKeyRange.low = 0;
2971            DimensionKeyRange.high = 0;
2972            pMidiRules = new MidiRule*[3];
2973            pMidiRules[0] = NULL;
2974    
2975          // Loading          // Loading
2976          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2582  namespace { Line 2985  namespace {
2985                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
2986                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
2987                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
2988    
2989                    if (_3ewg->GetSize() > 32) {
2990                        // read MIDI rules
2991                        int i = 0;
2992                        _3ewg->SetPos(32);
2993                        uint8_t id1 = _3ewg->ReadUint8();
2994                        uint8_t id2 = _3ewg->ReadUint8();
2995    
2996                        if (id1 == 4 && id2 == 16) {
2997                            pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
2998                        }
2999                        //TODO: all the other types of rules
3000    
3001                        pMidiRules[i] = NULL;
3002                    }
3003              }              }
3004          }          }
3005    
3006          if (!pRegions) pRegions = new RegionList;          if (pFile->GetAutoLoad()) {
3007          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);              if (!pRegions) pRegions = new RegionList;
3008          if (lrgn) {              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
3009              RIFF::List* rgn = lrgn->GetFirstSubList();              if (lrgn) {
3010              while (rgn) {                  RIFF::List* rgn = lrgn->GetFirstSubList();
3011                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  while (rgn) {
3012                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                      if (rgn->GetListType() == LIST_TYPE_RGN) {
3013                      pRegions->push_back(new Region(this, rgn));                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
3014                            pRegions->push_back(new Region(this, rgn));
3015                        }
3016                        rgn = lrgn->GetNextSubList();
3017                  }                  }
3018                  rgn = lrgn->GetNextSubList();                  // Creating Region Key Table for fast lookup
3019                    UpdateRegionKeyTable();
3020              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
3021          }          }
3022    
3023          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
3024      }      }
3025    
3026      void Instrument::UpdateRegionKeyTable() {      void Instrument::UpdateRegionKeyTable() {
3027            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3028          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
3029          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
3030          for (; iter != end; ++iter) {          for (; iter != end; ++iter) {
# Line 2615  namespace { Line 3036  namespace {
3036      }      }
3037    
3038      Instrument::~Instrument() {      Instrument::~Instrument() {
3039            delete[] pMidiRules;
3040      }      }
3041    
3042      /**      /**
# Line 2643  namespace { Line 3065  namespace {
3065          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
3066          // make sure '3ewg' RIFF chunk exists          // make sure '3ewg' RIFF chunk exists
3067          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
3068          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);          if (!_3ewg)  {
3069                File* pFile = (File*) GetParent();
3070    
3071                // 3ewg is bigger in gig3, as it includes the iMIDI rules
3072                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
3073                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
3074                memset(_3ewg->LoadChunkData(), 0, size);
3075            }
3076          // update '3ewg' RIFF chunk          // update '3ewg' RIFF chunk
3077          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
3078          memcpy(&pData[0], &EffectSend, 2);          store16(&pData[0], EffectSend);
3079          memcpy(&pData[2], &Attenuation, 4);          store32(&pData[2], Attenuation);
3080          memcpy(&pData[6], &FineTune, 2);          store16(&pData[6], FineTune);
3081          memcpy(&pData[8], &PitchbendRange, 2);          store16(&pData[8], PitchbendRange);
3082          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |          const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
3083                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
3084          memcpy(&pData[10], &dimkeystart, 1);          pData[10] = dimkeystart;
3085          memcpy(&pData[11], &DimensionKeyRange.high, 1);          pData[11] = DimensionKeyRange.high;
3086      }      }
3087    
3088      /**      /**
# Line 2664  namespace { Line 3093  namespace {
3093       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
3094       */       */
3095      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
3096          if (!pRegions || !pRegions->size() || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
3097          return RegionKeyTable[Key];          return RegionKeyTable[Key];
3098    
3099          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
# Line 2722  namespace { Line 3151  namespace {
3151          UpdateRegionKeyTable();          UpdateRegionKeyTable();
3152      }      }
3153    
3154        /**
3155         * Returns a MIDI rule of the instrument.
3156         *
3157         * The list of MIDI rules, at least in gig v3, always contains at
3158         * most two rules. The second rule can only be the DEF filter
3159         * (which currently isn't supported by libgig).
3160         *
3161         * @param i - MIDI rule number
3162         * @returns   pointer address to MIDI rule number i or NULL if there is none
3163         */
3164        MidiRule* Instrument::GetMidiRule(int i) {
3165            return pMidiRules[i];
3166        }
3167    
3168    
3169  // *************** Group ***************  // *************** Group ***************
# Line 2740  namespace { Line 3182  namespace {
3182      }      }
3183    
3184      Group::~Group() {      Group::~Group() {
3185            // remove the chunk associated with this group (if any)
3186            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
3187      }      }
3188    
3189      /** @brief Update chunks with current group settings.      /** @brief Update chunks with current group settings.
# Line 2753  namespace { Line 3197  namespace {
3197      void Group::UpdateChunks() {      void Group::UpdateChunks() {
3198          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
3199          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
3200          if (!_3gri) _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);          if (!_3gri) {
3201                _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
3202                pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
3203            }
3204          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
3205          if (!_3gnl) _3gnl = pFile->pRIFF->AddSubList(LIST_TYPE_3GNL);          if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
3206    
3207            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
3208                // v3 has a fixed list of 128 strings, find a free one
3209                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
3210                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
3211                        pNameChunk = ck;
3212                        break;
3213                    }
3214                }
3215            }
3216    
3217          // 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
3218          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);          ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
3219      }      }
# Line 2831  namespace { Line 3289  namespace {
3289  // *************** File ***************  // *************** File ***************
3290  // *  // *
3291    
3292        /// Reflects Gigasampler file format version 2.0 (1998-06-28).
3293        const DLS::version_t File::VERSION_2 = {
3294            0, 2, 19980628 & 0xffff, 19980628 >> 16
3295        };
3296    
3297        /// Reflects Gigasampler file format version 3.0 (2003-03-31).
3298        const DLS::version_t File::VERSION_3 = {
3299            0, 3, 20030331 & 0xffff, 20030331 >> 16
3300        };
3301    
3302        static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
3303            { CHUNK_ID_IARL, 256 },
3304            { CHUNK_ID_IART, 128 },
3305            { CHUNK_ID_ICMS, 128 },
3306            { CHUNK_ID_ICMT, 1024 },
3307            { CHUNK_ID_ICOP, 128 },
3308            { CHUNK_ID_ICRD, 128 },
3309            { CHUNK_ID_IENG, 128 },
3310            { CHUNK_ID_IGNR, 128 },
3311            { CHUNK_ID_IKEY, 128 },
3312            { CHUNK_ID_IMED, 128 },
3313            { CHUNK_ID_INAM, 128 },
3314            { CHUNK_ID_IPRD, 128 },
3315            { CHUNK_ID_ISBJ, 128 },
3316            { CHUNK_ID_ISFT, 128 },
3317            { CHUNK_ID_ISRC, 128 },
3318            { CHUNK_ID_ISRF, 128 },
3319            { CHUNK_ID_ITCH, 128 },
3320            { 0, 0 }
3321        };
3322    
3323      File::File() : DLS::File() {      File::File() : DLS::File() {
3324            bAutoLoad = true;
3325            *pVersion = VERSION_3;
3326          pGroups = NULL;          pGroups = NULL;
3327          pInfo->UseFixedLengthStrings = true;          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3328            pInfo->ArchivalLocation = String(256, ' ');
3329    
3330            // add some mandatory chunks to get the file chunks in right
3331            // order (INFO chunk will be moved to first position later)
3332            pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
3333            pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
3334            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
3335    
3336            GenerateDLSID();
3337      }      }
3338    
3339      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
3340            bAutoLoad = true;
3341          pGroups = NULL;          pGroups = NULL;
3342          pInfo->UseFixedLengthStrings = true;          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3343      }      }
3344    
3345      File::~File() {      File::~File() {
# Line 2880  namespace { Line 3381  namespace {
3381         // create new Sample object and its respective 'wave' list chunk         // create new Sample object and its respective 'wave' list chunk
3382         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
3383         Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);         Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
3384    
3385           // add mandatory chunks to get the chunks in right order
3386           wave->AddSubChunk(CHUNK_ID_FMT, 16);
3387           wave->AddSubList(LIST_TYPE_INFO);
3388    
3389         pSamples->push_back(pSample);         pSamples->push_back(pSample);
3390         return pSample;         return pSample;
3391      }      }
3392    
3393      /** @brief Delete a sample.      /** @brief Delete a sample.
3394       *       *
3395       * 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
3396       * to call Save() to make this persistent to the file.       * references to this sample from Regions and DimensionRegions will be
3397         * removed. You have to call Save() to make this persistent to the file.
3398       *       *
3399       * @param pSample - sample to delete       * @param pSample - sample to delete
3400       * @throws gig::Exception if given sample could not be found       * @throws gig::Exception if given sample could not be found
# Line 2899  namespace { Line 3406  namespace {
3406          if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation          if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
3407          pSamples->erase(iter);          pSamples->erase(iter);
3408          delete pSample;          delete pSample;
3409    
3410            SampleList::iterator tmp = SamplesIterator;
3411            // remove all references to the sample
3412            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
3413                 instrument = GetNextInstrument()) {
3414                for (Region* region = instrument->GetFirstRegion() ; region ;
3415                     region = instrument->GetNextRegion()) {
3416    
3417                    if (region->GetSample() == pSample) region->SetSample(NULL);
3418    
3419                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
3420                        gig::DimensionRegion *d = region->pDimensionRegions[i];
3421                        if (d->pSample == pSample) d->pSample = NULL;
3422                    }
3423                }
3424            }
3425            SamplesIterator = tmp; // restore iterator
3426      }      }
3427    
3428      void File::LoadSamples() {      void File::LoadSamples() {
# Line 2908  namespace { Line 3432  namespace {
3432      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
3433          // Groups must be loaded before samples, because samples will try          // Groups must be loaded before samples, because samples will try
3434          // to resolve the group they belong to          // to resolve the group they belong to
3435          LoadGroups();          if (!pGroups) LoadGroups();
3436    
3437          if (!pSamples) pSamples = new SampleList;          if (!pSamples) pSamples = new SampleList;
3438    
# Line 2989  namespace { Line 3513  namespace {
3513              progress_t subprogress;              progress_t subprogress;
3514              __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
3515              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
3516              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
3517                    GetFirstSample(&subprogress); // now force all samples to be loaded
3518              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
3519    
3520              // instrument loading subtask              // instrument loading subtask
# Line 3022  namespace { Line 3547  namespace {
3547         __ensureMandatoryChunksExist();         __ensureMandatoryChunksExist();
3548         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
3549         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
3550    
3551           // add mandatory chunks to get the chunks in right order
3552           lstInstr->AddSubList(LIST_TYPE_INFO);
3553           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
3554    
3555         Instrument* pInstrument = new Instrument(this, lstInstr);         Instrument* pInstrument = new Instrument(this, lstInstr);
3556           pInstrument->GenerateDLSID();
3557    
3558           lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
3559    
3560           // this string is needed for the gig to be loadable in GSt:
3561           pInstrument->pInfo->Software = "Endless Wave";
3562    
3563         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
3564         return pInstrument;         return pInstrument;
3565      }      }
# Line 3073  namespace { Line 3610  namespace {
3610          }          }
3611      }      }
3612    
3613        /// Updates the 3crc chunk with the checksum of a sample. The
3614        /// update is done directly to disk, as this method is called
3615        /// after File::Save()
3616        void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
3617            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
3618            if (!_3crc) return;
3619    
3620            // get the index of the sample
3621            int iWaveIndex = -1;
3622            File::SampleList::iterator iter = pSamples->begin();
3623            File::SampleList::iterator end  = pSamples->end();
3624            for (int index = 0; iter != end; ++iter, ++index) {
3625                if (*iter == pSample) {
3626                    iWaveIndex = index;
3627                    break;
3628                }
3629            }
3630            if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
3631    
3632            // write the CRC-32 checksum to disk
3633            _3crc->SetPos(iWaveIndex * 8);
3634            uint32_t tmp = 1;
3635            _3crc->WriteUint32(&tmp); // unknown, always 1?
3636            _3crc->WriteUint32(&crc);
3637        }
3638    
3639      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
3640          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
3641          // there must always be at least one group          // there must always be at least one group
# Line 3165  namespace { Line 3728  namespace {
3728                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
3729                  while (ck) {                  while (ck) {
3730                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {
3731                            if (pVersion && pVersion->major == 3 &&
3732                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
3733    
3734                          pGroups->push_back(new Group(this, ck));                          pGroups->push_back(new Group(this, ck));
3735                      }                      }
3736                      ck = lst3gnl->GetNextSubChunk();                      ck = lst3gnl->GetNextSubChunk();
# Line 3190  namespace { Line 3756  namespace {
3756       * @throws Exception - on errors       * @throws Exception - on errors
3757       */       */
3758      void File::UpdateChunks() {      void File::UpdateChunks() {
3759            bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
3760    
3761            b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
3762    
3763          // first update base class's chunks          // first update base class's chunks
3764          DLS::File::UpdateChunks();          DLS::File::UpdateChunks();
3765    
3766            if (newFile) {
3767                // INFO was added by Resource::UpdateChunks - make sure it
3768                // is placed first in file
3769                RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
3770                RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
3771                if (first != info) {
3772                    pRIFF->MoveSubChunk(info, first);
3773                }
3774            }
3775    
3776          // update group's chunks          // update group's chunks
3777          if (pGroups) {          if (pGroups) {
3778              std::list<Group*>::iterator iter = pGroups->begin();              std::list<Group*>::iterator iter = pGroups->begin();
# Line 3200  namespace { Line 3780  namespace {
3780              for (; iter != end; ++iter) {              for (; iter != end; ++iter) {
3781                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks();
3782              }              }
3783          }  
3784                // v3: make sure the file has 128 3gnm chunks
3785                if (pVersion && pVersion->major == 3) {
3786                    RIFF::List* _3gnl = pRIFF->GetSubList(LIST_TYPE_3GRI)->GetSubList(LIST_TYPE_3GNL);
3787                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
3788                    for (int i = 0 ; i < 128 ; i++) {
3789                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
3790                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
3791                    }
3792                }
3793            }
3794    
3795            // update einf chunk
3796    
3797            // The einf chunk contains statistics about the gig file, such
3798            // as the number of regions and samples used by each
3799            // instrument. It is divided in equally sized parts, where the
3800            // first part contains information about the whole gig file,
3801            // and the rest of the parts map to each instrument in the
3802            // file.
3803            //
3804            // At the end of each part there is a bit map of each sample
3805            // in the file, where a set bit means that the sample is used
3806            // by the file/instrument.
3807            //
3808            // Note that there are several fields with unknown use. These
3809            // are set to zero.
3810    
3811            int sublen = pSamples->size() / 8 + 49;
3812            int einfSize = (Instruments + 1) * sublen;
3813    
3814            RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
3815            if (einf) {
3816                if (einf->GetSize() != einfSize) {
3817                    einf->Resize(einfSize);
3818                    memset(einf->LoadChunkData(), 0, einfSize);
3819                }
3820            } else if (newFile) {
3821                einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
3822            }
3823            if (einf) {
3824                uint8_t* pData = (uint8_t*) einf->LoadChunkData();
3825    
3826                std::map<gig::Sample*,int> sampleMap;
3827                int sampleIdx = 0;
3828                for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
3829                    sampleMap[pSample] = sampleIdx++;
3830                }
3831    
3832                int totnbusedsamples = 0;
3833                int totnbusedchannels = 0;
3834                int totnbregions = 0;
3835                int totnbdimregions = 0;
3836                int totnbloops = 0;
3837                int instrumentIdx = 0;
3838    
3839                memset(&pData[48], 0, sublen - 48);
3840    
3841                for (Instrument* instrument = GetFirstInstrument() ; instrument ;
3842                     instrument = GetNextInstrument()) {
3843                    int nbusedsamples = 0;
3844                    int nbusedchannels = 0;
3845                    int nbdimregions = 0;
3846                    int nbloops = 0;
3847    
3848                    memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
3849    
3850                    for (Region* region = instrument->GetFirstRegion() ; region ;
3851                         region = instrument->GetNextRegion()) {
3852                        for (int i = 0 ; i < region->DimensionRegions ; i++) {
3853                            gig::DimensionRegion *d = region->pDimensionRegions[i];
3854                            if (d->pSample) {
3855                                int sampleIdx = sampleMap[d->pSample];
3856                                int byte = 48 + sampleIdx / 8;
3857                                int bit = 1 << (sampleIdx & 7);
3858                                if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
3859                                    pData[(instrumentIdx + 1) * sublen + byte] |= bit;
3860                                    nbusedsamples++;
3861                                    nbusedchannels += d->pSample->Channels;
3862    
3863                                    if ((pData[byte] & bit) == 0) {
3864                                        pData[byte] |= bit;
3865                                        totnbusedsamples++;
3866                                        totnbusedchannels += d->pSample->Channels;
3867                                    }
3868                                }
3869                            }
3870                            if (d->SampleLoops) nbloops++;
3871                        }
3872                        nbdimregions += region->DimensionRegions;
3873                    }
3874                    // first 4 bytes unknown - sometimes 0, sometimes length of einf part
3875                    // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
3876                    store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
3877                    store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
3878                    store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
3879                    store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
3880                    store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
3881                    store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
3882                    // next 8 bytes unknown
3883                    store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
3884                    store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
3885                    // next 4 bytes unknown
3886    
3887                    totnbregions += instrument->Regions;
3888                    totnbdimregions += nbdimregions;
3889                    totnbloops += nbloops;
3890                    instrumentIdx++;
3891                }
3892                // first 4 bytes unknown - sometimes 0, sometimes length of einf part
3893                // store32(&pData[0], sublen);
3894                store32(&pData[4], totnbusedchannels);
3895                store32(&pData[8], totnbusedsamples);
3896                store32(&pData[12], Instruments);
3897                store32(&pData[16], totnbregions);
3898                store32(&pData[20], totnbdimregions);
3899                store32(&pData[24], totnbloops);
3900                // next 8 bytes unknown
3901                // next 4 bytes unknown, not always 0
3902                store32(&pData[40], pSamples->size());
3903                // next 4 bytes unknown
3904            }
3905    
3906            // update 3crc chunk
3907    
3908            // The 3crc chunk contains CRC-32 checksums for the
3909            // samples. The actual checksum values will be filled in
3910            // later, by Sample::Write.
3911    
3912            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
3913            if (_3crc) {
3914                _3crc->Resize(pSamples->size() * 8);
3915            } else if (newFile) {
3916                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
3917                _3crc->LoadChunkData();
3918    
3919                // the order of einf and 3crc is not the same in v2 and v3
3920                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
3921            }
3922        }
3923    
3924        /**
3925         * Enable / disable automatic loading. By default this properyt is
3926         * enabled and all informations are loaded automatically. However
3927         * loading all Regions, DimensionRegions and especially samples might
3928         * take a long time for large .gig files, and sometimes one might only
3929         * be interested in retrieving very superficial informations like the
3930         * amount of instruments and their names. In this case one might disable
3931         * automatic loading to avoid very slow response times.
3932         *
3933         * @e CAUTION: by disabling this property many pointers (i.e. sample
3934         * references) and informations will have invalid or even undefined
3935         * data! This feature is currently only intended for retrieving very
3936         * superficial informations in a very fast way. Don't use it to retrieve
3937         * details like synthesis informations or even to modify .gig files!
3938         */
3939        void File::SetAutoLoad(bool b) {
3940            bAutoLoad = b;
3941        }
3942    
3943        /**
3944         * Returns whether automatic loading is enabled.
3945         * @see SetAutoLoad()
3946         */
3947        bool File::GetAutoLoad() {
3948            return bAutoLoad;
3949      }      }
3950    
3951    

Legend:
Removed from v.1098  
changed lines
  Added in v.1875

  ViewVC Help
Powered by ViewVC