/[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 3414 by schoenebeck, Tue Jan 30 20:17:12 2018 UTC revision 3903 by schoenebeck, Wed May 12 18:31:25 2021 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-2018 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2020 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 412  namespace { Line 412  namespace {
412    
413          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
414          if (pCk3gix) {          if (pCk3gix) {
415                pCk3gix->SetPos(0);
416    
417              uint16_t iSampleGroup = pCk3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
418              pGroup = pFile->GetGroup(iSampleGroup);              pGroup = pFile->GetGroup(iSampleGroup);
419          } else { // '3gix' chunk missing          } else { // '3gix' chunk missing
# Line 421  namespace { Line 423  namespace {
423    
424          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
425          if (pCkSmpl) {          if (pCkSmpl) {
426                pCkSmpl->SetPos(0);
427    
428              Manufacturer  = pCkSmpl->ReadInt32();              Manufacturer  = pCkSmpl->ReadInt32();
429              Product       = pCkSmpl->ReadInt32();              Product       = pCkSmpl->ReadInt32();
430              SamplePeriod  = pCkSmpl->ReadInt32();              SamplePeriod  = pCkSmpl->ReadInt32();
# Line 467  namespace { Line 471  namespace {
471          Dithered          = false;          Dithered          = false;
472          TruncatedBits     = 0;          TruncatedBits     = 0;
473          if (Compressed) {          if (Compressed) {
474                ewav->SetPos(0);
475    
476              uint32_t version = ewav->ReadInt32();              uint32_t version = ewav->ReadInt32();
477              if (version == 3 && BitDepth == 24) {              if (version > 2 && BitDepth == 24) {
478                  Dithered = ewav->ReadInt32();                  Dithered = ewav->ReadInt32();
479                  ewav->SetPos(Channels == 2 ? 84 : 64);                  ewav->SetPos(Channels == 2 ? 84 : 64);
480                  TruncatedBits = ewav->ReadInt32();                  TruncatedBits = ewav->ReadInt32();
# Line 1500  namespace { Line 1506  namespace {
1506    
1507          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1508          if (_3ewa) { // if '3ewa' chunk exists          if (_3ewa) { // if '3ewa' chunk exists
1509                _3ewa->SetPos(0);
1510    
1511              _3ewa->ReadInt32(); // unknown, always == chunk size ?              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1512              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1513              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
# Line 1732  namespace { Line 1740  namespace {
1740              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1741              memset(DimensionUpperLimits, 127, 8);              memset(DimensionUpperLimits, 127, 8);
1742          }          }
1743          // format extension for EG behavior options, these will *NOT* work with  
1744          // Gigasampler/GigaStudio !          // chunk for own format extensions, these will *NOT* work with Gigasampler/GigaStudio !
1745          RIFF::Chunk* lsde = _3ewl->GetSubChunk(CHUNK_ID_LSDE);          RIFF::Chunk* lsde = _3ewl->GetSubChunk(CHUNK_ID_LSDE);
1746          if (lsde) {          if (lsde) { // format extension for EG behavior options
1747                lsde->SetPos(0);
1748    
1749              eg_opt_t* pEGOpts[2] = { &EG1Options, &EG2Options };              eg_opt_t* pEGOpts[2] = { &EG1Options, &EG2Options };
1750              for (int i = 0; i < 2; ++i) {              for (int i = 0; i < 2; ++i) { // NOTE: we reserved a 3rd byte for a potential future EG3 option
1751                  unsigned char byte = lsde->ReadUint8();                  unsigned char byte = lsde->ReadUint8();
1752                  pEGOpts[i]->AttackCancel     = byte & 1;                  pEGOpts[i]->AttackCancel     = byte & 1;
1753                  pEGOpts[i]->AttackHoldCancel = byte & (1 << 1);                  pEGOpts[i]->AttackHoldCancel = byte & (1 << 1);
# Line 1746  namespace { Line 1756  namespace {
1756                  pEGOpts[i]->ReleaseCancel    = byte & (1 << 4);                  pEGOpts[i]->ReleaseCancel    = byte & (1 << 4);
1757              }              }
1758          }          }
1759            // format extension for sustain pedal up effect on release trigger samples
1760            if (lsde && lsde->GetSize() > 3) { // NOTE: we reserved the 3rd byte for a potential future EG3 option
1761                lsde->SetPos(3);
1762                uint8_t byte = lsde->ReadUint8();
1763                SustainReleaseTrigger   = static_cast<sust_rel_trg_t>(byte & 0x03);
1764                NoNoteOffReleaseTrigger = byte >> 7;
1765            } else {
1766                SustainReleaseTrigger   = sust_rel_trg_none;
1767                NoNoteOffReleaseTrigger = false;
1768            }
1769            // format extension for LFOs' wave form, phase displacement and for
1770            // LFO3's flip phase
1771            if (lsde && lsde->GetSize() > 4) {
1772                lsde->SetPos(4);
1773                LFO1WaveForm = static_cast<lfo_wave_t>( lsde->ReadUint16() );
1774                LFO2WaveForm = static_cast<lfo_wave_t>( lsde->ReadUint16() );
1775                LFO3WaveForm = static_cast<lfo_wave_t>( lsde->ReadUint16() );
1776                lsde->ReadUint16(); // unused 16 bits, reserved for potential future use
1777                LFO1Phase = (double) GIG_EXP_DECODE( lsde->ReadInt32() );
1778                LFO2Phase = (double) GIG_EXP_DECODE( lsde->ReadInt32() );
1779                LFO3Phase = (double) GIG_EXP_DECODE( lsde->ReadInt32() );
1780                const uint32_t flags = lsde->ReadInt32();
1781                LFO3FlipPhase = flags & 1;
1782            } else {
1783                LFO1WaveForm = lfo_wave_sine;
1784                LFO2WaveForm = lfo_wave_sine;
1785                LFO3WaveForm = lfo_wave_sine;
1786                LFO1Phase = 0.0;
1787                LFO2Phase = 0.0;
1788                LFO3Phase = 0.0;
1789                LFO3FlipPhase = false;
1790            }
1791    
1792          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1793                                                       VelocityResponseDepth,                                                       VelocityResponseDepth,
# Line 1871  namespace { Line 1913  namespace {
1913          SRLZ(EG1ControllerAttackInfluence);          SRLZ(EG1ControllerAttackInfluence);
1914          SRLZ(EG1ControllerDecayInfluence);          SRLZ(EG1ControllerDecayInfluence);
1915          SRLZ(EG1ControllerReleaseInfluence);          SRLZ(EG1ControllerReleaseInfluence);
1916            SRLZ(LFO1WaveForm);
1917          SRLZ(LFO1Frequency);          SRLZ(LFO1Frequency);
1918            SRLZ(LFO1Phase);
1919          SRLZ(LFO1InternalDepth);          SRLZ(LFO1InternalDepth);
1920          SRLZ(LFO1ControlDepth);          SRLZ(LFO1ControlDepth);
1921          SRLZ(LFO1Controller);          SRLZ(LFO1Controller);
# Line 1889  namespace { Line 1933  namespace {
1933          SRLZ(EG2ControllerAttackInfluence);          SRLZ(EG2ControllerAttackInfluence);
1934          SRLZ(EG2ControllerDecayInfluence);          SRLZ(EG2ControllerDecayInfluence);
1935          SRLZ(EG2ControllerReleaseInfluence);          SRLZ(EG2ControllerReleaseInfluence);
1936            SRLZ(LFO2WaveForm);
1937          SRLZ(LFO2Frequency);          SRLZ(LFO2Frequency);
1938            SRLZ(LFO2Phase);
1939          SRLZ(LFO2InternalDepth);          SRLZ(LFO2InternalDepth);
1940          SRLZ(LFO2ControlDepth);          SRLZ(LFO2ControlDepth);
1941          SRLZ(LFO2Controller);          SRLZ(LFO2Controller);
# Line 1897  namespace { Line 1943  namespace {
1943          SRLZ(LFO2Sync);          SRLZ(LFO2Sync);
1944          SRLZ(EG3Attack);          SRLZ(EG3Attack);
1945          SRLZ(EG3Depth);          SRLZ(EG3Depth);
1946            SRLZ(LFO3WaveForm);
1947          SRLZ(LFO3Frequency);          SRLZ(LFO3Frequency);
1948            SRLZ(LFO3Phase);
1949          SRLZ(LFO3InternalDepth);          SRLZ(LFO3InternalDepth);
1950          SRLZ(LFO3ControlDepth);          SRLZ(LFO3ControlDepth);
1951          SRLZ(LFO3Controller);          SRLZ(LFO3Controller);
1952            SRLZ(LFO3FlipPhase);
1953          SRLZ(LFO3Sync);          SRLZ(LFO3Sync);
1954          SRLZ(VCFEnabled);          SRLZ(VCFEnabled);
1955          SRLZ(VCFType);          SRLZ(VCFType);
# Line 1936  namespace { Line 1985  namespace {
1985          SRLZ(SampleAttenuation);          SRLZ(SampleAttenuation);
1986          SRLZ(EG1Options);          SRLZ(EG1Options);
1987          SRLZ(EG2Options);          SRLZ(EG2Options);
1988            SRLZ(SustainReleaseTrigger);
1989            SRLZ(NoNoteOffReleaseTrigger);
1990    
1991          // derived attributes from DLS::Sampler          // derived attributes from DLS::Sampler
1992          SRLZ(FineTune);          SRLZ(FineTune);
# Line 1975  namespace { Line 2026  namespace {
2026          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
2027          if (!_3ewa) {          if (!_3ewa) {
2028              File* pFile = (File*) GetParent()->GetParent()->GetParent();              File* pFile = (File*) GetParent()->GetParent()->GetParent();
2029              bool version3 = pFile->pVersion && pFile->pVersion->major == 3;              bool versiongt2 = pFile->pVersion && pFile->pVersion->major > 2;
2030              _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);              _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, versiongt2 ? 148 : 140);
2031          }          }
2032          pData = (uint8_t*) _3ewa->LoadChunkData();          pData = (uint8_t*) _3ewa->LoadChunkData();
2033    
# Line 2243  namespace { Line 2294  namespace {
2294              memcpy(&pData[140], DimensionUpperLimits, 8);              memcpy(&pData[140], DimensionUpperLimits, 8);
2295          }          }
2296    
2297          // format extension for EG behavior options, these will *NOT* work with          // chunk for own format extensions, these will *NOT* work with
2298          // Gigasampler/GigaStudio !          // Gigasampler/GigaStudio !
2299          RIFF::Chunk* lsde = pParentList->GetSubChunk(CHUNK_ID_LSDE);          RIFF::Chunk* lsde = pParentList->GetSubChunk(CHUNK_ID_LSDE);
2300          if (!lsde) {          const int lsdeSize =
2301              // only add this "LSDE" chunk if the EG options do not match the              3 /* EG cancel options */ +
2302              // default EG behavior              1 /* sustain pedal up on release trigger option */ +
2303              eg_opt_t defaultOpt;              8 /* LFOs' wave forms */ + 12 /* LFOs' phase */ + 4 /* flags (LFO3FlipPhase) */;
2304              if (memcmp(&EG1Options, &defaultOpt, sizeof(eg_opt_t)) ||          if (!lsde && UsesAnyGigFormatExtension()) {
2305                  memcmp(&EG2Options, &defaultOpt, sizeof(eg_opt_t)))              // only add this "LSDE" chunk if there is some (format extension)
2306              {              // setting effective that would require our "LSDE" format extension
2307                  lsde = pParentList->AddSubChunk(CHUNK_ID_LSDE, 2);              // chunk to be stored
2308                  // move LSDE chunk to the end of parent list              lsde = pParentList->AddSubChunk(CHUNK_ID_LSDE, lsdeSize);
2309                  pParentList->MoveSubChunk(lsde, (RIFF::Chunk*)NULL);              // move LSDE chunk to the end of parent list
2310              }              pParentList->MoveSubChunk(lsde, (RIFF::Chunk*)NULL);
2311          }          }
2312          if (lsde) {          if (lsde) {
2313                if (lsde->GetNewSize() < lsdeSize)
2314                    lsde->Resize(lsdeSize);
2315                // format extension for EG behavior options
2316              unsigned char* pData = (unsigned char*) lsde->LoadChunkData();              unsigned char* pData = (unsigned char*) lsde->LoadChunkData();
2317              eg_opt_t* pEGOpts[2] = { &EG1Options, &EG2Options };              eg_opt_t* pEGOpts[2] = { &EG1Options, &EG2Options };
2318              for (int i = 0; i < 2; ++i) {              for (int i = 0; i < 2; ++i) { // NOTE: we reserved the 3rd byte for a potential future EG3 option
2319                  pData[i] =                  pData[i] =
2320                      (pEGOpts[i]->AttackCancel     ? 1 : 0) |                      (pEGOpts[i]->AttackCancel     ? 1 : 0) |
2321                      (pEGOpts[i]->AttackHoldCancel ? (1<<1) : 0) |                      (pEGOpts[i]->AttackHoldCancel ? (1<<1) : 0) |
# Line 2269  namespace { Line 2323  namespace {
2323                      (pEGOpts[i]->Decay2Cancel     ? (1<<3) : 0) |                      (pEGOpts[i]->Decay2Cancel     ? (1<<3) : 0) |
2324                      (pEGOpts[i]->ReleaseCancel    ? (1<<4) : 0);                      (pEGOpts[i]->ReleaseCancel    ? (1<<4) : 0);
2325              }              }
2326                // format extension for release trigger options
2327                pData[3] = static_cast<uint8_t>(SustainReleaseTrigger) | (NoNoteOffReleaseTrigger ? (1<<7) : 0);
2328                // format extension for LFOs' wave form, phase displacement and for
2329                // LFO3's flip phase
2330                store16(&pData[4], LFO1WaveForm);
2331                store16(&pData[6], LFO2WaveForm);
2332                store16(&pData[8], LFO3WaveForm);
2333                //NOTE: 16 bits reserved here for potential future use !
2334                const int32_t lfo1Phase = (int32_t) GIG_EXP_ENCODE(LFO1Phase);
2335                const int32_t lfo2Phase = (int32_t) GIG_EXP_ENCODE(LFO2Phase);
2336                const int32_t lfo3Phase = (int32_t) GIG_EXP_ENCODE(LFO3Phase);
2337                store32(&pData[12], lfo1Phase);
2338                store32(&pData[16], lfo2Phase);
2339                store32(&pData[20], lfo3Phase);
2340                const int32_t flags = LFO3FlipPhase ? 1 : 0;
2341                store32(&pData[24], flags);
2342    
2343                // compile time sanity check: is our last store access here
2344                // consistent with the initial lsdeSize value assignment?
2345                static_assert(lsdeSize == 28, "Inconsistency in assumed 'LSDE' RIFF chunk size");
2346          }          }
2347      }      }
2348    
2349        /**
2350         * Returns @c true in case this DimensionRegion object uses any gig format
2351         * extension, that is whether this DimensionRegion object currently has any
2352         * setting effective that would require our "LSDE" RIFF chunk to be stored
2353         * to the gig file.
2354         *
2355         * Right now this is a private method. It is considerable though this method
2356         * to become (in slightly modified form) a public API method in future, i.e.
2357         * to allow instrument editors to visualize and/or warn the user of any
2358         * format extension being used. Right now this method really just serves to
2359         * answer the question whether an LSDE chunk is required, for the public API
2360         * purpose this method would also need to check whether any other setting
2361         * stored to the regular value '3ewa' chunk, is actually a format extension
2362         * as well.
2363         */
2364        bool DimensionRegion::UsesAnyGigFormatExtension() const {
2365            eg_opt_t defaultOpt;
2366            return memcmp(&EG1Options, &defaultOpt, sizeof(eg_opt_t)) ||
2367                   memcmp(&EG2Options, &defaultOpt, sizeof(eg_opt_t)) ||
2368                   SustainReleaseTrigger || NoNoteOffReleaseTrigger ||
2369                   LFO1WaveForm || LFO2WaveForm || LFO3WaveForm ||
2370                   LFO1Phase || LFO2Phase || LFO3Phase ||
2371                   LFO3FlipPhase;
2372        }
2373    
2374      double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {      double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2375          curve_type_t curveType = releaseVelocityResponseCurve;          curve_type_t curveType = releaseVelocityResponseCurve;
2376          uint8_t depth = releaseVelocityResponseDepth;          uint8_t depth = releaseVelocityResponseDepth;
# Line 3208  namespace { Line 3307  namespace {
3307          }          }
3308          Layers = 1;          Layers = 1;
3309          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3310          int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;          int dimensionBits = (file->pVersion && file->pVersion->major > 2) ? 8 : 5;
3311    
3312          // Actual Loading          // Actual Loading
3313    
# Line 3218  namespace { Line 3317  namespace {
3317    
3318          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
3319          if (_3lnk) {          if (_3lnk) {
3320                _3lnk->SetPos(0);
3321    
3322              DimensionRegions = _3lnk->ReadUint32();              DimensionRegions = _3lnk->ReadUint32();
3323              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
3324                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
# Line 3252  namespace { Line 3353  namespace {
3353              UpdateVelocityTable();              UpdateVelocityTable();
3354    
3355              // jump to start of the wave pool indices (if not already there)              // jump to start of the wave pool indices (if not already there)
3356              if (file->pVersion && file->pVersion->major == 3)              if (file->pVersion && file->pVersion->major > 2)
3357                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
3358              else              else
3359                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
# Line 3311  namespace { Line 3412  namespace {
3412          }          }
3413    
3414          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
3415          bool version3 = pFile->pVersion && pFile->pVersion->major == 3;          const bool versiongt2 = pFile->pVersion && pFile->pVersion->major > 2;
3416          const int iMaxDimensions =  version3 ? 8 : 5;          const int iMaxDimensions =  versiongt2 ? 8 : 5;
3417          const int iMaxDimensionRegions = version3 ? 256 : 32;          const int iMaxDimensionRegions = versiongt2 ? 256 : 32;
3418    
3419          // make sure '3lnk' chunk exists          // make sure '3lnk' chunk exists
3420          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
3421          if (!_3lnk) {          if (!_3lnk) {
3422              const int _3lnkChunkSize = version3 ? 1092 : 172;              const int _3lnkChunkSize = versiongt2 ? 1092 : 172;
3423              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3424              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3425    
# Line 3342  namespace { Line 3443  namespace {
3443          }          }
3444    
3445          // update wave pool table in '3lnk' chunk          // update wave pool table in '3lnk' chunk
3446          const int iWavePoolOffset = version3 ? 68 : 44;          const int iWavePoolOffset = versiongt2 ? 68 : 44;
3447          for (uint i = 0; i < iMaxDimensionRegions; i++) {          for (uint i = 0; i < iMaxDimensionRegions; i++) {
3448              int iWaveIndex = -1;              int iWaveIndex = -1;
3449              if (i < DimensionRegions) {              if (i < DimensionRegions) {
# Line 3358  namespace { Line 3459  namespace {
3459              }              }
3460              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3461          }          }
3462    
3463            // The following chunks are just added for compatibility with the
3464            // GigaStudio software, which would show a warning if these were
3465            // missing. However currently these chunks don't cover any useful
3466            // data. So if this gig file uses any of our own gig format
3467            // extensions which would cause this gig file to be unloadable
3468            // with GSt software anyway, then just skip these GSt compatibility
3469            // chunks here as well.
3470            if (versiongt2 && !UsesAnyGigFormatExtension()) {
3471                // add 3dnm list which always seems to be empty
3472                RIFF::List* _3dnm = pCkRegion->GetSubList(LIST_TYPE_3DNM);
3473                if (!_3dnm) _3dnm = pCkRegion->AddSubList(LIST_TYPE_3DNM);
3474    
3475                // add 3ddp chunk which always seems to have 16 bytes of 0xFF
3476                RIFF::Chunk* _3ddp = pCkRegion->GetSubChunk(CHUNK_ID_3DDP);
3477                if (!_3ddp) _3ddp =  pCkRegion->AddSubChunk(CHUNK_ID_3DDP, 16);
3478                uint8_t* pData = (uint8_t*) _3ddp->LoadChunkData();
3479                for (int i = 0; i < 16; i += 4) {
3480                    store32(&pData[i], 0xFFFFFFFF);
3481                }
3482    
3483                // move 3dnm and 3ddp to the end of the region list
3484                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3DNM), (RIFF::Chunk*)NULL);
3485                pCkRegion->MoveSubChunk(pCkRegion->GetSubChunk(CHUNK_ID_3DDP), (RIFF::Chunk*)NULL);
3486            } else {
3487                // this is intended for the user switching from GSt >= 3 version
3488                // back to an older format version, delete GSt3 chunks ...
3489                RIFF::List* _3dnm = pCkRegion->GetSubList(LIST_TYPE_3DNM);
3490                if (_3dnm) pCkRegion->DeleteSubChunk(_3dnm);
3491    
3492                RIFF::Chunk* _3ddp = pCkRegion->GetSubChunk(CHUNK_ID_3DDP);
3493                if (_3ddp) pCkRegion->DeleteSubChunk(_3ddp);
3494            }
3495      }      }
3496    
3497      void Region::LoadDimensionRegions(RIFF::List* rgn) {      void Region::LoadDimensionRegions(RIFF::List* rgn) {
# Line 3485  namespace { Line 3619  namespace {
3619    
3620          // check if max. amount of dimensions reached          // check if max. amount of dimensions reached
3621          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3622          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;          const int iMaxDimensions = (file->pVersion && file->pVersion->major > 2) ? 8 : 5;
3623          if (Dimensions >= iMaxDimensions)          if (Dimensions >= iMaxDimensions)
3624              throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");              throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
3625          // check if max. amount of dimension bits reached          // check if max. amount of dimension bits reached
# Line 3673  namespace { Line 3807  namespace {
3807       * @throws gig::Exception if requested zone could not be deleted       * @throws gig::Exception if requested zone could not be deleted
3808       */       */
3809      void Region::DeleteDimensionZone(dimension_t type, int zone) {      void Region::DeleteDimensionZone(dimension_t type, int zone) {
3810            if (!Dimensions)
3811                throw gig::Exception("Could not delete dimension zone, because there is no dimension at all.");
3812          dimension_def_t* oldDef = GetDimensionDefinition(type);          dimension_def_t* oldDef = GetDimensionDefinition(type);
3813          if (!oldDef)          if (!oldDef)
3814              throw gig::Exception("Could not delete dimension zone, no such dimension of given type");              throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
# Line 3701  namespace { Line 3837  namespace {
3837          // requested by the arguments of this method call) to the temporary          // requested by the arguments of this method call) to the temporary
3838          // region, and don't use Region::CopyAssign() here for this task, since          // region, and don't use Region::CopyAssign() here for this task, since
3839          // it would also alter fast lookup helper variables here and there          // it would also alter fast lookup helper variables here and there
3840          dimension_def_t newDef;          dimension_def_t newDef = {};
3841          for (int i = 0; i < Dimensions; ++i) {          for (int i = 0; i < Dimensions; ++i) {
3842              dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference              dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3843              // is this the dimension requested by the method arguments? ...              // is this the dimension requested by the method arguments? ...
# Line 3712  namespace { Line 3848  namespace {
3848              }              }
3849              tempRgn->AddDimension(&def);              tempRgn->AddDimension(&def);
3850          }          }
3851            // silence clang sanitizer warning
3852            if (newDef.dimension == dimension_none)
3853                throw gig::Exception("Unexpected internal failure resolving dimension in DeleteDimensionZone() [this is a bug].");
3854    
3855          // find the dimension index in the tempRegion which is the dimension          // find the dimension index in the tempRegion which is the dimension
3856          // type passed to this method (paranoidly expecting different order)          // type passed to this method (paranoidly expecting different order)
# Line 3756  namespace { Line 3895  namespace {
3895          // now tempRegion's dimensions and DimensionRegions basically reflect          // now tempRegion's dimensions and DimensionRegions basically reflect
3896          // what we wanted to get for this actual Region here, so we now just          // what we wanted to get for this actual Region here, so we now just
3897          // delete and recreate the dimension in question with the new amount          // delete and recreate the dimension in question with the new amount
3898          // zones and then copy back from tempRegion                // zones and then copy back from tempRegion. we're actually deleting and
3899          DeleteDimension(oldDef);          // recreating all dimensions here, to avoid altering the precise order
3900          AddDimension(&newDef);          // of the dimensions (which would not be an error per se, but it would
3901            // cause usability issues with instrument editors)
3902            {
3903                std::vector<dimension_def_t> oldDefs;
3904                for (int i = 0; i < Dimensions; ++i)
3905                    oldDefs.push_back(pDimensionDefinitions[i]); // copy, don't reference
3906                for (int i = Dimensions - 1; i >= 0; --i)
3907                    DeleteDimension(&pDimensionDefinitions[i]);
3908                for (int i = 0; i < oldDefs.size(); ++i) {
3909                    dimension_def_t& def = oldDefs[i];
3910                    AddDimension(
3911                        (def.dimension == newDef.dimension) ? &newDef : &def
3912                    );
3913                }
3914            }
3915          for (int iSrc = 0; iSrc < 256; ++iSrc) {          for (int iSrc = 0; iSrc < 256; ++iSrc) {
3916              DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];              DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3917              if (!srcDimRgn) continue;              if (!srcDimRgn) continue;
# Line 3777  namespace { Line 3930  namespace {
3930          }          }
3931    
3932          // delete temporary region          // delete temporary region
3933            tempRgn->DeleteChunks();
3934          delete tempRgn;          delete tempRgn;
3935    
3936          UpdateVelocityTable();          UpdateVelocityTable();
# Line 3895  namespace { Line 4049  namespace {
4049          // now tempRegion's dimensions and DimensionRegions basically reflect          // now tempRegion's dimensions and DimensionRegions basically reflect
4050          // what we wanted to get for this actual Region here, so we now just          // what we wanted to get for this actual Region here, so we now just
4051          // delete and recreate the dimension in question with the new amount          // delete and recreate the dimension in question with the new amount
4052          // zones and then copy back from tempRegion                // zones and then copy back from tempRegion. we're actually deleting and
4053          DeleteDimension(oldDef);          // recreating all dimensions here, to avoid altering the precise order
4054          AddDimension(&newDef);          // of the dimensions (which would not be an error per se, but it would
4055            // cause usability issues with instrument editors)
4056            {
4057                std::vector<dimension_def_t> oldDefs;
4058                for (int i = 0; i < Dimensions; ++i)
4059                    oldDefs.push_back(pDimensionDefinitions[i]); // copy, don't reference
4060                for (int i = Dimensions - 1; i >= 0; --i)
4061                    DeleteDimension(&pDimensionDefinitions[i]);
4062                for (int i = 0; i < oldDefs.size(); ++i) {
4063                    dimension_def_t& def = oldDefs[i];
4064                    AddDimension(
4065                        (def.dimension == newDef.dimension) ? &newDef : &def
4066                    );
4067                }
4068            }
4069          for (int iSrc = 0; iSrc < 256; ++iSrc) {          for (int iSrc = 0; iSrc < 256; ++iSrc) {
4070              DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];              DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
4071              if (!srcDimRgn) continue;              if (!srcDimRgn) continue;
# Line 3916  namespace { Line 4084  namespace {
4084          }          }
4085    
4086          // delete temporary region          // delete temporary region
4087            tempRgn->DeleteChunks();
4088          delete tempRgn;          delete tempRgn;
4089    
4090          UpdateVelocityTable();          UpdateVelocityTable();
# Line 4220  namespace { Line 4389  namespace {
4389          Layers = orig->Layers;          Layers = orig->Layers;
4390      }      }
4391    
4392        /**
4393         * Returns @c true in case this Region object uses any gig format
4394         * extension, that is e.g. whether any DimensionRegion object currently
4395         * has any setting effective that would require our "LSDE" RIFF chunk to
4396         * be stored to the gig file.
4397         *
4398         * Right now this is a private method. It is considerable though this method
4399         * to become (in slightly modified form) a public API method in future, i.e.
4400         * to allow instrument editors to visualize and/or warn the user of any gig
4401         * format extension being used. See also comments on
4402         * DimensionRegion::UsesAnyGigFormatExtension() for details about such a
4403         * potential public API change in future.
4404         */
4405        bool Region::UsesAnyGigFormatExtension() const {
4406            for (int i = 0; i < 256; i++) {
4407                if (pDimensionRegions[i]) {
4408                    if (pDimensionRegions[i]->UsesAnyGigFormatExtension())
4409                        return true;
4410                }
4411            }
4412            return false;
4413        }
4414    
4415    
4416  // *************** MidiRule ***************  // *************** MidiRule ***************
4417  // *  // *
# Line 4394  namespace { Line 4586  namespace {
4586          pGroup = group;          pGroup = group;
4587          pChunk = ckScri;          pChunk = ckScri;
4588          if (ckScri) { // object is loaded from file ...          if (ckScri) { // object is loaded from file ...
4589                ckScri->SetPos(0);
4590    
4591              // read header              // read header
4592              uint32_t headerSize = ckScri->ReadUint32();              uint32_t headerSize = ckScri->ReadUint32();
4593              Compression = (Compression_t) ckScri->ReadUint32();              Compression = (Compression_t) ckScri->ReadUint32();
4594              Encoding    = (Encoding_t) ckScri->ReadUint32();              Encoding    = (Encoding_t) ckScri->ReadUint32();
4595              Language    = (Language_t) ckScri->ReadUint32();              Language    = (Language_t) ckScri->ReadUint32();
4596              Bypass      = (Language_t) ckScri->ReadUint32() & 1;              Bypass      = ckScri->ReadUint32() & 1;
4597              crc         = ckScri->ReadUint32();              crc         = ckScri->ReadUint32();
4598              uint32_t nameSize = ckScri->ReadUint32();              uint32_t nameSize = ckScri->ReadUint32();
4599              Name.resize(nameSize, ' ');              Name.resize(nameSize, ' ');
4600              for (int i = 0; i < nameSize; ++i)              for (int i = 0; i < nameSize; ++i)
4601                  Name[i] = ckScri->ReadUint8();                  Name[i] = ckScri->ReadUint8();
4602                // check if an uuid was already stored along with this script
4603                if (headerSize >= 6*sizeof(int32_t) + nameSize + 16) { // yes ...
4604                    for (uint i = 0; i < 16; ++i) {
4605                        Uuid[i] = ckScri->ReadUint8();
4606                    }
4607                } else { // no uuid yet, generate one now ...
4608                    GenerateUuid();
4609                }
4610              // to handle potential future extensions of the header              // to handle potential future extensions of the header
4611              ckScri->SetPos(sizeof(int32_t) + headerSize);              ckScri->SetPos(sizeof(int32_t) + headerSize);
4612              // read actual script data              // read actual script data
# Line 4419  namespace { Line 4621  namespace {
4621              Bypass   = false;              Bypass   = false;
4622              crc      = 0;              crc      = 0;
4623              Name     = "Unnamed Script";              Name     = "Unnamed Script";
4624                GenerateUuid();
4625          }          }
4626      }      }
4627    
# Line 4446  namespace { Line 4649  namespace {
4649          memcpy(&data[0], &text[0], text.size());          memcpy(&data[0], &text[0], text.size());
4650      }      }
4651    
4652        /** @brief Remove all RIFF chunks associated with this Script object.
4653         *
4654         * At the moment Script::DeleteChunks() does nothing. It is
4655         * recommended to call this method explicitly though from deriving classes's
4656         * own overridden implementation of this method to avoid potential future
4657         * compatiblity issues.
4658         *
4659         * See DLS::Storage::DeleteChunks() for details.
4660         */
4661        void Script::DeleteChunks() {
4662        }
4663    
4664      /**      /**
4665       * Apply this script to the respective RIFF chunks. You have to call       * Apply this script to the respective RIFF chunks. You have to call
4666       * File::Save() to make changes persistent.       * File::Save() to make changes persistent.
# Line 4461  namespace { Line 4676  namespace {
4676          __calculateCRC(&data[0], data.size(), crc);          __calculateCRC(&data[0], data.size(), crc);
4677          __finalizeCRC(crc);          __finalizeCRC(crc);
4678          // make sure chunk exists and has the required size          // make sure chunk exists and has the required size
4679          const file_offset_t chunkSize = (file_offset_t) 7*sizeof(int32_t) + Name.size() + data.size();          const file_offset_t chunkSize =
4680                (file_offset_t) 7*sizeof(int32_t) + Name.size() + 16 + data.size();
4681          if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);          if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4682          else pChunk->Resize(chunkSize);          else pChunk->Resize(chunkSize);
4683          // fill the chunk data to be written to disk          // fill the chunk data to be written to disk
4684          uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();          uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4685          int pos = 0;          int pos = 0;
4686          store32(&pData[pos], uint32_t(6*sizeof(int32_t) + Name.size())); // total header size          store32(&pData[pos], uint32_t(6*sizeof(int32_t) + Name.size() + 16)); // total header size
4687          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4688          store32(&pData[pos], Compression);          store32(&pData[pos], Compression);
4689          pos += sizeof(int32_t);          pos += sizeof(int32_t);
# Line 4483  namespace { Line 4699  namespace {
4699          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4700          for (int i = 0; i < Name.size(); ++i, ++pos)          for (int i = 0; i < Name.size(); ++i, ++pos)
4701              pData[pos] = Name[i];              pData[pos] = Name[i];
4702            for (int i = 0; i < 16; ++i, ++pos)
4703                pData[pos] = Uuid[i];
4704          for (int i = 0; i < data.size(); ++i, ++pos)          for (int i = 0; i < data.size(); ++i, ++pos)
4705              pData[pos] = data[i];              pData[pos] = data[i];
4706      }      }
4707    
4708      /**      /**
4709         * Generate a new Universally Unique Identifier (UUID) for this script.
4710         */
4711        void Script::GenerateUuid() {
4712            DLS::dlsid_t dlsid;
4713            DLS::Resource::GenerateDLSID(&dlsid);
4714            Uuid[0]  = dlsid.ulData1       & 0xff;
4715            Uuid[1]  = dlsid.ulData1 >>  8 & 0xff;
4716            Uuid[2]  = dlsid.ulData1 >> 16 & 0xff;
4717            Uuid[3]  = dlsid.ulData1 >> 24 & 0xff;
4718            Uuid[4]  = dlsid.usData2       & 0xff;
4719            Uuid[5]  = dlsid.usData2 >>  8 & 0xff;
4720            Uuid[6]  = dlsid.usData3       & 0xff;
4721            Uuid[7]  = dlsid.usData3 >>  8 & 0xff;
4722            Uuid[8]  = dlsid.abData[0];
4723            Uuid[9]  = dlsid.abData[1];
4724            Uuid[10] = dlsid.abData[2];
4725            Uuid[11] = dlsid.abData[3];
4726            Uuid[12] = dlsid.abData[4];
4727            Uuid[13] = dlsid.abData[5];
4728            Uuid[14] = dlsid.abData[6];
4729            Uuid[15] = dlsid.abData[7];
4730        }
4731    
4732        /**
4733       * Move this script from its current ScriptGroup to another ScriptGroup       * Move this script from its current ScriptGroup to another ScriptGroup
4734       * given by @a pGroup.       * given by @a pGroup.
4735       *       *
# Line 4561  namespace { Line 4803  namespace {
4803          }          }
4804      }      }
4805    
4806        /** @brief Remove all RIFF chunks associated with this ScriptGroup object.
4807         *
4808         * At the moment ScriptGroup::DeleteChunks() does nothing. It is
4809         * recommended to call this method explicitly though from deriving classes's
4810         * own overridden implementation of this method to avoid potential future
4811         * compatiblity issues.
4812         *
4813         * See DLS::Storage::DeleteChunks() for details.
4814         */
4815        void ScriptGroup::DeleteChunks() {
4816        }
4817    
4818      /**      /**
4819       * Apply this script group to the respective RIFF chunks. You have to call       * Apply this script group to the respective RIFF chunks. You have to call
4820       * File::Save() to make changes persistent.       * File::Save() to make changes persistent.
# Line 4685  namespace { Line 4939  namespace {
4939          if (lart) {          if (lart) {
4940              RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);              RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4941              if (_3ewg) {              if (_3ewg) {
4942                    _3ewg->SetPos(0);
4943    
4944                  EffectSend             = _3ewg->ReadUint16();                  EffectSend             = _3ewg->ReadUint16();
4945                  Attenuation            = _3ewg->ReadInt32();                  Attenuation            = _3ewg->ReadInt32();
4946                  FineTune               = _3ewg->ReadInt16();                  FineTune               = _3ewg->ReadInt16();
# Line 4729  namespace { Line 4985  namespace {
4985                  RIFF::List* rgn = lrgn->GetFirstSubList();                  RIFF::List* rgn = lrgn->GetFirstSubList();
4986                  while (rgn) {                  while (rgn) {
4987                      if (rgn->GetListType() == LIST_TYPE_RGN) {                      if (rgn->GetListType() == LIST_TYPE_RGN) {
4988                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                          if (pProgress)
4989                                __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4990                          pRegions->push_back(new Region(this, rgn));                          pRegions->push_back(new Region(this, rgn));
4991                      }                      }
4992                      rgn = lrgn->GetNextSubList();                      rgn = lrgn->GetNextSubList();
# Line 4742  namespace { Line 4999  namespace {
4999          // own gig format extensions          // own gig format extensions
5000          RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);          RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
5001          if (lst3LS) {          if (lst3LS) {
5002                // script slots (that is references to instrument scripts)
5003              RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);              RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
5004              if (ckSCSL) {              if (ckSCSL) {
5005                    ckSCSL->SetPos(0);
5006    
5007                  int headerSize = ckSCSL->ReadUint32();                  int headerSize = ckSCSL->ReadUint32();
5008                  int slotCount  = ckSCSL->ReadUint32();                  int slotCount  = ckSCSL->ReadUint32();
5009                  if (slotCount) {                  if (slotCount) {
# Line 4759  namespace { Line 5019  namespace {
5019                      }                      }
5020                  }                  }
5021              }              }
5022    
5023                // overridden script 'patch' variables
5024                RIFF::Chunk* ckSCPV = lst3LS->GetSubChunk(CHUNK_ID_SCPV);
5025                if (ckSCPV) {
5026                    ckSCPV->SetPos(0);
5027    
5028                    int nScripts = ckSCPV->ReadUint32();
5029                    for (int iScript = 0; iScript < nScripts; ++iScript) {
5030                        _UUID uuid;
5031                        for (int i = 0; i < 16; ++i)
5032                            uuid[i] = ckSCPV->ReadUint8();
5033                        uint slot = ckSCPV->ReadUint32();
5034                        ckSCPV->ReadUint32(); // unused, reserved 32 bit
5035                        int nVars = ckSCPV->ReadUint32();
5036                        for (int iVar = 0; iVar < nVars; ++iVar) {
5037                            uint8_t type = ckSCPV->ReadUint8();
5038                            ckSCPV->ReadUint8();  // unused, reserved byte
5039                            int blobSize = ckSCPV->ReadUint16();
5040                            RIFF::file_offset_t pos = ckSCPV->GetPos();
5041                            // assuming 1st bit is set in 'type', otherwise blob not
5042                            // supported for decoding
5043                            if (type & 1) {
5044                                String name, value;
5045                                int len = ckSCPV->ReadUint16();
5046                                for (int i = 0; i < len; ++i)
5047                                    name += (char) ckSCPV->ReadUint8();
5048                                len = ckSCPV->ReadUint16();
5049                                for (int i = 0; i < len; ++i)
5050                                    value += (char) ckSCPV->ReadUint8();
5051                                if (!name.empty()) // 'name' should never be empty, but just to be sure
5052                                    scriptVars[uuid][slot][name] = value;
5053                            }
5054                            // also for potential future extensions: seek forward
5055                            // according to blob size
5056                            ckSCPV->SetPos(pos + blobSize);
5057                        }
5058                    }
5059                }
5060          }          }
5061    
5062          __notify_progress(pProgress, 1.0f); // notify done          if (pProgress)
5063                __notify_progress(pProgress, 1.0f); // notify done
5064      }      }
5065    
5066      void Instrument::UpdateRegionKeyTable() {      void Instrument::UpdateRegionKeyTable() {
# Line 4817  namespace { Line 5116  namespace {
5116              File* pFile = (File*) GetParent();              File* pFile = (File*) GetParent();
5117    
5118              // 3ewg is bigger in gig3, as it includes the iMIDI rules              // 3ewg is bigger in gig3, as it includes the iMIDI rules
5119              int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;              int size = (pFile->pVersion && pFile->pVersion->major > 2) ? 16416 : 12;
5120              _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);              _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
5121              memset(_3ewg->LoadChunkData(), 0, size);              memset(_3ewg->LoadChunkData(), 0, size);
5122          }          }
# Line 4849  namespace { Line 5148  namespace {
5148    
5149             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
5150             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
5151    
5152               // save script slots (that is references to instrument scripts)
5153             const int slotCount = (int) pScriptRefs->size();             const int slotCount = (int) pScriptRefs->size();
5154             const int headerSize = 3 * sizeof(uint32_t);             const int headerSize = 3 * sizeof(uint32_t);
5155             const int slotSize  = 2 * sizeof(uint32_t);             const int slotSize  = 2 * sizeof(uint32_t);
# Line 4873  namespace { Line 5174  namespace {
5174                 store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);                 store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
5175                 pos += sizeof(uint32_t);                 pos += sizeof(uint32_t);
5176             }             }
5177    
5178               // save overridden script 'patch' variables ...
5179    
5180               // the actual 'scriptVars' member variable might contain variables of
5181               // scripts which are currently no longer assigned to any script slot
5182               // of this instrument, we need to get rid of these variables here to
5183               // prevent saving those persistently, however instead of touching the
5184               // member variable 'scriptVars' directly, rather strip a separate
5185               // copy such that the overridden values are not lost during an
5186               // instrument editor session (i.e. if script might be re-assigned)
5187               _VarsByScript vars = stripScriptVars();
5188               if (!vars.empty()) {
5189                   // determine total size required for 'SCPV' RIFF chunk, and the
5190                   // total amount of scripts being overridden (the latter is
5191                   // required because a script might be used on several script
5192                   // slots, hence vars.size() could then not be used here instead)
5193                   size_t totalChunkSize = 4;
5194                   size_t totalScriptsOverridden = 0;
5195                   for (const auto& script : vars) {
5196                       for (const auto& slot : script.second) {
5197                           totalScriptsOverridden++;
5198                           totalChunkSize += 16 + 4 + 4 + 4;
5199                           for (const auto& var : slot.second) {
5200                               totalChunkSize += 4 + 2 + var.first.length() +
5201                                                     2 + var.second.length();
5202                           }
5203                       }
5204                   }
5205    
5206                   // ensure 'SCPV' RIFF chunk exists (with required size)
5207                   RIFF::Chunk* ckSCPV = lst3LS->GetSubChunk(CHUNK_ID_SCPV);
5208                   if (!ckSCPV) ckSCPV = lst3LS->AddSubChunk(CHUNK_ID_SCPV, totalChunkSize);
5209                   else ckSCPV->Resize(totalChunkSize);
5210    
5211                   // store the actual data to 'SCPV' RIFF chunk
5212                   uint8_t* pData = (uint8_t*) ckSCPV->LoadChunkData();
5213                   int pos = 0;
5214                   store32(&pData[pos], (uint32_t) totalScriptsOverridden); // scripts count
5215                   pos += 4;
5216                   for (const auto& script : vars) {
5217                       for (const auto& slot : script.second) {
5218                           for (int i = 0; i < 16; ++i)
5219                               pData[pos+i] = script.first[i]; // uuid
5220                           pos += 16;
5221                           store32(&pData[pos], (uint32_t) slot.first); // slot index
5222                           pos += 4;
5223                           store32(&pData[pos], (uint32_t) 0); // unused, reserved 32 bit
5224                           pos += 4;
5225                           store32(&pData[pos], (uint32_t) slot.second.size()); // variables count
5226                           pos += 4;
5227                           for (const auto& var : slot.second) {
5228                               pData[pos++] = 1; // type
5229                               pData[pos++] = 0; // reserved byte
5230                               store16(&pData[pos], 2 + var.first.size() + 2 + var.second.size()); // blob size
5231                               pos += 2;
5232                               store16(&pData[pos], var.first.size()); // variable name length
5233                               pos += 2;
5234                               for (int i = 0; i < var.first.size(); ++i)
5235                                   pData[pos++] = var.first[i];
5236                               store16(&pData[pos], var.second.size()); // variable value length
5237                               pos += 2;
5238                               for (int i = 0; i < var.second.size(); ++i)
5239                                   pData[pos++] = var.second[i];
5240                           }
5241                       }
5242                   }
5243               } else {
5244                   // no script variable overridden by this instrument, so get rid
5245                   // of 'SCPV' RIFF chunk (if any)
5246                   RIFF::Chunk* ckSCPV = lst3LS->GetSubChunk(CHUNK_ID_SCPV);
5247                   if (ckSCPV) lst3LS->DeleteSubChunk(ckSCPV);
5248               }
5249         } else {         } else {
5250             // no script slots, so get rid of any LS custom RIFF chunks (if any)             // no script slots, so get rid of any LS custom RIFF chunks (if any)
5251             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
# Line 5297  namespace { Line 5670  namespace {
5670              scriptPoolFileOffsets.at(index).bypass = bBypass;              scriptPoolFileOffsets.at(index).bypass = bBypass;
5671      }      }
5672    
5673        /// type cast (by copy) uint8_t[16] -> std::array<uint8_t,16>
5674        inline std::array<uint8_t,16> _UUIDFromCArray(const uint8_t* pData) {
5675            std::array<uint8_t,16> uuid;
5676            memcpy(&uuid[0], pData, 16);
5677            return uuid;
5678        }
5679    
5680        /**
5681         * Returns true if this @c Instrument has any script slot which references
5682         * the @c Script identified by passed @p uuid.
5683         */
5684        bool Instrument::ReferencesScriptWithUuid(const _UUID& uuid) {
5685            const uint nSlots = ScriptSlotCount();
5686            for (uint iSlot = 0; iSlot < nSlots; ++iSlot)
5687                if (_UUIDFromCArray(&GetScriptOfSlot(iSlot)->Uuid[0]) == uuid)
5688                    return true;
5689            return false;
5690        }
5691    
5692        /** @brief Checks whether a certain script 'patch' variable value is set.
5693         *
5694         * Returns @c true if the initial value for the requested script variable is
5695         * currently overridden by this instrument.
5696         *
5697         * @remarks Real-time instrument scripts allow to declare special 'patch'
5698         * variables, which essentially behave like regular variables of their data
5699         * type, however their initial value may optionally be overridden on a per
5700         * instrument basis. That allows to share scripts between instruments while
5701         * still being able to fine tune certain aspects of the script for each
5702         * instrument individually.
5703         *
5704         * @note This is an own format extension which did not exist i.e. in the
5705         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5706         * Gigedit.
5707         *
5708         * @param slot - script slot index of the variable to be retrieved
5709         * @param variable - name of the 'patch' variable in that script
5710         */
5711        bool Instrument::IsScriptPatchVariableSet(int slot, String variable) {
5712            if (variable.empty()) return false;
5713            Script* script = GetScriptOfSlot(slot);
5714            if (!script) return false;
5715            const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]);
5716            if (!scriptVars.count(uuid)) return false;
5717            const _VarsBySlot& slots = scriptVars.find(uuid)->second;
5718            if (slots.empty()) return false;
5719            if (slots.count(slot))
5720                return slots.find(slot)->second.count(variable);
5721            else
5722                return slots.begin()->second.count(variable);
5723        }
5724    
5725        /** @brief Get all overridden script 'patch' variables.
5726         *
5727         * Returns map of key-value pairs reflecting all patch variables currently
5728         * being overridden by this instrument for the given script @p slot, where
5729         * key is the variable name and value is the hereby currently overridden
5730         * value for that variable.
5731         *
5732         * @remarks Real-time instrument scripts allow to declare special 'patch'
5733         * variables, which essentially behave like regular variables of their data
5734         * type, however their initial value may optionally be overridden on a per
5735         * instrument basis. That allows to share scripts between instruments while
5736         * still being able to fine tune certain aspects of the script for each
5737         * instrument individually.
5738         *
5739         * @note This is an own format extension which did not exist i.e. in the
5740         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5741         * Gigedit.
5742         *
5743         * @param slot - script slot index of the variable to be retrieved
5744         */
5745        std::map<String,String> Instrument::GetScriptPatchVariables(int slot) {
5746            Script* script = GetScriptOfSlot(slot);
5747            if (!script) return std::map<String,String>();
5748            const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]);
5749            if (!scriptVars.count(uuid)) return std::map<String,String>();
5750            const _VarsBySlot& slots = scriptVars.find(uuid)->second;
5751            if (slots.empty()) return std::map<String,String>();
5752            const _PatchVars& vars =
5753                (slots.count(slot)) ?
5754                    slots.find(slot)->second : slots.begin()->second;
5755            return vars;
5756        }
5757    
5758        /** @brief Get overridden initial value for 'patch' variable.
5759         *
5760         * Returns current initial value for the requested script variable being
5761         * overridden by this instrument.
5762         *
5763         * @remarks Real-time instrument scripts allow to declare special 'patch'
5764         * variables, which essentially behave like regular variables of their data
5765         * type, however their initial value may optionally be overridden on a per
5766         * instrument basis. That allows to share scripts between instruments while
5767         * still being able to fine tune certain aspects of the script for each
5768         * instrument individually.
5769         *
5770         * @note This is an own format extension which did not exist i.e. in the
5771         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5772         * Gigedit.
5773         *
5774         * @param slot - script slot index of the variable to be retrieved
5775         * @param variable - name of the 'patch' variable in that script
5776         */
5777        String Instrument::GetScriptPatchVariable(int slot, String variable) {
5778            std::map<String,String> vars = GetScriptPatchVariables(slot);
5779            return (vars.count(variable)) ? vars.find(variable)->second : "";
5780        }
5781    
5782        /** @brief Override initial value for 'patch' variable.
5783         *
5784         * Overrides initial value for the requested script variable for this
5785         * instrument with the passed value.
5786         *
5787         * @remarks Real-time instrument scripts allow to declare special 'patch'
5788         * variables, which essentially behave like regular variables of their data
5789         * type, however their initial value may optionally be overridden on a per
5790         * instrument basis. That allows to share scripts between instruments while
5791         * still being able to fine tune certain aspects of the script for each
5792         * instrument individually.
5793         *
5794         * @note This is an own format extension which did not exist i.e. in the
5795         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5796         * Gigedit.
5797         *
5798         * @param slot - script slot index of the variable to be set
5799         * @param variable - name of the 'patch' variable in that script
5800         * @param value - overridden initial value for that script variable
5801         * @throws gig::Exception if given script @p slot index is invalid or given
5802         *         @p variable name is empty
5803         */
5804        void Instrument::SetScriptPatchVariable(int slot, String variable, String value) {
5805            if (variable.empty())
5806                throw Exception("Variable name must not be empty");
5807            Script* script = GetScriptOfSlot(slot);
5808            if (!script)
5809                throw Exception("No script slot with index " + ToString(slot));
5810            const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]);
5811            scriptVars[uuid][slot][variable] = value;
5812        }
5813    
5814        /** @brief Drop overridden initial value(s) for 'patch' variable(s).
5815         *
5816         * Reverts initial value(s) for requested script variable(s) back to their
5817         * default initial value(s) defined in the script itself.
5818         *
5819         * Both arguments of this method are optional. The most obvious use case of
5820         * this method would be passing a valid script @p slot index and a
5821         * (non-emtpy string as) @p variable name to this method, which would cause
5822         * that single variable to be unset for that specific script slot (on this
5823         * @c Instrument level).
5824         *
5825         * Not passing a value (or @c -1 for @p slot and/or empty string for
5826         * @p variable) means 'wildcard'. So accordingly absence of argument(s) will
5827         * cause all variables and/or for all script slots being unset. Hence this
5828         * method serves 2^2 = 4 possible use cases in total and accordingly covers
5829         * 4 different behaviours in one method.
5830         *
5831         * @remarks Real-time instrument scripts allow to declare special 'patch'
5832         * variables, which essentially behave like regular variables of their data
5833         * type, however their initial value may optionally be overridden on a per
5834         * instrument basis. That allows to share scripts between instruments while
5835         * still being able to fine tune certain aspects of the script for each
5836         * instrument individually.
5837         *
5838         * @note This is an own format extension which did not exist i.e. in the
5839         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5840         * Gigedit.
5841         *
5842         * @param slot - script slot index of the variable to be unset
5843         * @param variable - name of the 'patch' variable in that script
5844         */
5845        void Instrument::UnsetScriptPatchVariable(int slot, String variable) {
5846            Script* script = GetScriptOfSlot(slot);
5847    
5848            // option 1: unset a particular variable of one particular script slot
5849            if (slot != -1 && !variable.empty()) {
5850                if (!script) return;
5851                const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]);
5852                if (!scriptVars.count(uuid)) return;
5853                if (!scriptVars[uuid].count(slot)) return;
5854                if (scriptVars[uuid][slot].count(variable))
5855                    scriptVars[uuid][slot].erase(
5856                        scriptVars[uuid][slot].find(variable)
5857                    );
5858                if (scriptVars[uuid][slot].empty())
5859                    scriptVars[uuid].erase( scriptVars[uuid].find(slot) );
5860                if (scriptVars[uuid].empty())
5861                    scriptVars.erase( scriptVars.find(uuid) );
5862                return;
5863            }
5864    
5865            // option 2: unset all variables of all script slots
5866            if (slot == -1 && variable.empty()) {
5867                scriptVars.clear();
5868                return;
5869            }
5870    
5871            // option 3: unset all variables of one particular script slot only
5872            if (slot != -1) {
5873                if (!script) return;
5874                const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]);
5875                if (scriptVars.count(uuid))
5876                    scriptVars.erase( scriptVars.find(uuid) );
5877                return;
5878            }
5879    
5880            // option 4: unset a particular variable of all script slots
5881            _VarsByScript::iterator itScript = scriptVars.begin();
5882            _VarsByScript::iterator endScript = scriptVars.end();
5883            while (itScript != endScript) {
5884                _VarsBySlot& slots = itScript->second;
5885                _VarsBySlot::iterator itSlot = slots.begin();
5886                _VarsBySlot::iterator endSlot = slots.end();
5887                while (itSlot != endSlot) {
5888                    _PatchVars& vars = itSlot->second;
5889                    if (vars.count(variable))
5890                        vars.erase( vars.find(variable) );
5891                    if (vars.empty())
5892                        slots.erase(itSlot++); // postfix increment to avoid iterator invalidation
5893                    else
5894                        ++itSlot;
5895                }
5896                if (slots.empty())
5897                    scriptVars.erase(itScript++); // postfix increment to avoid iterator invalidation
5898                else
5899                    ++itScript;
5900            }
5901        }
5902    
5903        /**
5904         * Returns stripped version of member variable @c scriptVars, where scripts
5905         * no longer referenced by this @c Instrument are filtered out, and so are
5906         * variables of meanwhile obsolete slots (i.e. a script still being
5907         * referenced, but previously overridden on a script slot which either no
5908         * longer exists or is hosting another script now).
5909         */
5910        Instrument::_VarsByScript Instrument::stripScriptVars() {
5911            _VarsByScript vars;
5912            _VarsByScript::const_iterator itScript = scriptVars.begin();
5913            _VarsByScript::const_iterator endScript = scriptVars.end();
5914            for (; itScript != endScript; ++itScript) {
5915                const _UUID& uuid = itScript->first;
5916                if (!ReferencesScriptWithUuid(uuid))
5917                    continue;
5918                const _VarsBySlot& slots = itScript->second;
5919                _VarsBySlot::const_iterator itSlot = slots.begin();
5920                _VarsBySlot::const_iterator endSlot = slots.end();
5921                for (; itSlot != endSlot; ++itSlot) {
5922                    Script* script = GetScriptOfSlot(itSlot->first);
5923                    if (!script) continue;
5924                    if (_UUIDFromCArray(&script->Uuid[0]) != uuid) continue;
5925                    if (itSlot->second.empty()) continue;
5926                    vars[uuid][itSlot->first] = itSlot->second;
5927                }
5928            }
5929            return vars;
5930        }
5931    
5932      /**      /**
5933       * Make a (semi) deep copy of the Instrument object given by @a orig       * Make a (semi) deep copy of the Instrument object given by @a orig
5934       * and assign it to this object.       * and assign it to this object.
# Line 5331  namespace { Line 5963  namespace {
5963          PianoReleaseMode = orig->PianoReleaseMode;          PianoReleaseMode = orig->PianoReleaseMode;
5964          DimensionKeyRange = orig->DimensionKeyRange;          DimensionKeyRange = orig->DimensionKeyRange;
5965          scriptPoolFileOffsets = orig->scriptPoolFileOffsets;          scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5966          pScriptRefs = orig->pScriptRefs;          // deep copy of pScriptRefs required (to avoid undefined behaviour)
5967            if (pScriptRefs) delete pScriptRefs;
5968            pScriptRefs = new std::vector<_ScriptPooolRef>;
5969            if (orig->pScriptRefs)
5970                *pScriptRefs = *orig->pScriptRefs;
5971            scriptVars = orig->scriptVars;
5972                    
5973          // free old midi rules          // free old midi rules
5974          for (int i = 0 ; pMidiRules[i] ; i++) {          for (int i = 0 ; pMidiRules[i] ; i++) {
# Line 5358  namespace { Line 5995  namespace {
5995          UpdateRegionKeyTable();          UpdateRegionKeyTable();
5996      }      }
5997    
5998        /**
5999         * Returns @c true in case this Instrument object uses any gig format
6000         * extension, that is e.g. whether any DimensionRegion object currently
6001         * has any setting effective that would require our "LSDE" RIFF chunk to
6002         * be stored to the gig file.
6003         *
6004         * Right now this is a private method. It is considerable though this method
6005         * to become (in slightly modified form) a public API method in future, i.e.
6006         * to allow instrument editors to visualize and/or warn the user of any gig
6007         * format extension being used. See also comments on
6008         * DimensionRegion::UsesAnyGigFormatExtension() for details about such a
6009         * potential public API change in future.
6010         */
6011        bool Instrument::UsesAnyGigFormatExtension() const {
6012            if (!pRegions) return false;
6013            if (!scriptVars.empty()) return true;
6014            RegionList::const_iterator iter = pRegions->begin();
6015            RegionList::const_iterator end  = pRegions->end();
6016            for (; iter != end; ++iter) {
6017                gig::Region* rgn = static_cast<gig::Region*>(*iter);
6018                if (rgn->UsesAnyGigFormatExtension())
6019                    return true;
6020            }
6021            return false;
6022        }
6023    
6024    
6025  // *************** Group ***************  // *************** Group ***************
6026  // *  // *
# Line 5374  namespace { Line 6037  namespace {
6037          ::LoadString(pNameChunk, Name);          ::LoadString(pNameChunk, Name);
6038      }      }
6039    
6040        /** @brief Destructor.
6041         *
6042         * Currently this destructor implementation does nothing.
6043         */
6044      Group::~Group() {      Group::~Group() {
6045          // remove the chunk associated with this group (if any)      }
6046          if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);  
6047        /** @brief Remove all RIFF chunks associated with this Group object.
6048         *
6049         * See DLS::Storage::DeleteChunks() for details.
6050         */
6051        void Group::DeleteChunks() {
6052            // handle own RIFF chunks
6053            if (pNameChunk) {
6054                pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
6055                pNameChunk = NULL;
6056            }
6057      }      }
6058    
6059      /** @brief Update chunks with current group settings.      /** @brief Update chunks with current group settings.
# Line 5399  namespace { Line 6076  namespace {
6076          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);          RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
6077          if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);          if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
6078    
6079          if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {          if (!pNameChunk && pFile->pVersion && pFile->pVersion->major > 2) {
6080              // v3 has a fixed list of 128 strings, find a free one              // v3 has a fixed list of 128 strings, find a free one
6081              for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {              for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
6082                  if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {                  if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
# Line 5494  namespace { Line 6171  namespace {
6171          0, 3, 20030331 & 0xffff, 20030331 >> 16          0, 3, 20030331 & 0xffff, 20030331 >> 16
6172      };      };
6173    
6174        /// Reflects Gigasampler file format version 4.0 (2007-10-12).
6175        const DLS::version_t File::VERSION_4 = {
6176            0, 4, 20071012 & 0xffff, 20071012 >> 16
6177        };
6178    
6179      static const DLS::Info::string_length_t _FileFixedStringLengths[] = {      static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
6180          { CHUNK_ID_IARL, 256 },          { CHUNK_ID_IARL, 256 },
6181          { CHUNK_ID_IART, 128 },          { CHUNK_ID_IART, 128 },
# Line 5642  namespace { Line 6324  namespace {
6324          if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");          if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
6325          if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation          if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
6326          pSamples->erase(iter);          pSamples->erase(iter);
6327            pSample->DeleteChunks();
6328          delete pSample;          delete pSample;
6329    
6330          SampleList::iterator tmp = SamplesIterator;          SampleList::iterator tmp = SamplesIterator;
# Line 5679  namespace { Line 6362  namespace {
6362          int iSampleIndex  = 0;          int iSampleIndex  = 0;
6363          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
6364    
6365          // check if samples should be loaded from extension files          // just for assembling path of optional extension files to be read
6366          // (only for old gig files < 2 GB)          const std::string folder = parentPath(pRIFF->GetFileName());
6367          int lastFileNo = 0;          const std::string baseName = pathWithoutExtension(pRIFF->GetFileName());
6368          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {  
6369              for (int i = 0 ; i < WavePoolCount ; i++) {          // the main gig file and the extension files (.gx01, ... , .gx98) may
6370                  if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];          // contain wave data (wave pool)
6371              }          std::vector<RIFF::File*> poolFiles;
6372          }          poolFiles.push_back(pRIFF);
6373          String name(pRIFF->GetFileName());  
6374          int nameLen = (int) name.length();          // get info about all extension files
6375          char suffix[6];          RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
6376          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (ckXfil) { // there are extension files (.gx01, ... , .gx98) ...
6377                const uint32_t n = ckXfil->ReadInt32();
6378          for (int fileNo = 0 ; ; ) {              for (int i = 0; i < n; i++) {
6379                    // read the filename and load the extension file
6380                    std::string name;
6381                    ckXfil->ReadString(name, 128);
6382                    std::string path = concatPath(folder, name);
6383                    RIFF::File* pExtFile = new RIFF::File(path);
6384                    // check that the dlsids match
6385                    RIFF::Chunk* ckDLSID = pExtFile->GetSubChunk(CHUNK_ID_DLID);
6386                    if (ckDLSID) {
6387                        ::DLS::dlsid_t idExpected;
6388                        idExpected.ulData1 = ckXfil->ReadInt32();
6389                        idExpected.usData2 = ckXfil->ReadInt16();
6390                        idExpected.usData3 = ckXfil->ReadInt16();
6391                        ckXfil->Read(idExpected.abData, 8, 1);
6392                        ::DLS::dlsid_t idFound;
6393                        ckDLSID->Read(&idFound.ulData1, 1, 4);
6394                        ckDLSID->Read(&idFound.usData2, 1, 2);
6395                        ckDLSID->Read(&idFound.usData3, 1, 2);
6396                        ckDLSID->Read(idFound.abData, 8, 1);
6397                        if (memcmp(&idExpected, &idFound, 16) != 0)
6398                            throw gig::Exception("dlsid mismatch for extension file: %s", path.c_str());
6399                    }
6400                    poolFiles.push_back(pExtFile);
6401                    ExtensionFiles.push_back(pExtFile);
6402                }
6403            }
6404    
6405            // check if a .gx99 (GigaPulse) file exists
6406            RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
6407            if (ckDoxf) { // there is a .gx99 (GigaPulse) file ...
6408                std::string path = baseName + ".gx99";
6409                RIFF::File* pExtFile = new RIFF::File(path);
6410    
6411                // skip unused int and filename
6412                ckDoxf->SetPos(132, RIFF::stream_curpos);
6413    
6414                // check that the dlsids match
6415                RIFF::Chunk* ckDLSID = pExtFile->GetSubChunk(CHUNK_ID_DLID);
6416                if (ckDLSID) {
6417                    ::DLS::dlsid_t idExpected;
6418                    idExpected.ulData1 = ckDoxf->ReadInt32();
6419                    idExpected.usData2 = ckDoxf->ReadInt16();
6420                    idExpected.usData3 = ckDoxf->ReadInt16();
6421                    ckDoxf->Read(idExpected.abData, 8, 1);
6422                    ::DLS::dlsid_t idFound;
6423                    ckDLSID->Read(&idFound.ulData1, 1, 4);
6424                    ckDLSID->Read(&idFound.usData2, 1, 2);
6425                    ckDLSID->Read(&idFound.usData3, 1, 2);
6426                    ckDLSID->Read(idFound.abData, 8, 1);
6427                    if (memcmp(&idExpected, &idFound, 16) != 0)
6428                        throw gig::Exception("dlsid mismatch for GigaPulse file: %s", path.c_str());
6429                }
6430                poolFiles.push_back(pExtFile);
6431                ExtensionFiles.push_back(pExtFile);
6432            }
6433    
6434            // load samples from extension files (if required)
6435            for (int i = 0; i < poolFiles.size(); i++) {
6436                RIFF::File* file = poolFiles[i];
6437              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
6438              if (wvpl) {              if (wvpl) {
6439                  file_offset_t wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos() -
6440                                                   wvpl->GetPos(); // should be zero, but just to be sure
6441                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
6442                  while (wave) {                  while (wave) {
6443                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
6444                          // notify current progress                          // notify current progress
6445                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          if (pProgress) {
6446                          __notify_progress(pProgress, subprogress);                              const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
6447                                __notify_progress(pProgress, subprogress);
6448                            }
6449    
6450                          file_offset_t waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
6451                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, i, iSampleIndex));
6452    
6453                          iSampleIndex++;                          iSampleIndex++;
6454                      }                      }
6455                      wave = wvpl->GetNextSubList();                      wave = wvpl->GetNextSubList();
6456                  }                  }
6457                }
                 if (fileNo == lastFileNo) break;  
   
                 // open extension file (*.gx01, *.gx02, ...)  
                 fileNo++;  
                 sprintf(suffix, ".gx%02d", fileNo);  
                 name.replace(nameLen, 5, suffix);  
                 file = new RIFF::File(name);  
                 ExtensionFiles.push_back(file);  
             } else break;  
6458          }          }
6459    
6460          __notify_progress(pProgress, 1.0); // notify done          if (pProgress)
6461                __notify_progress(pProgress, 1.0); // notify done
6462      }      }
6463    
6464      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
# Line 5763  namespace { Line 6499  namespace {
6499          if (!pInstruments) {          if (!pInstruments) {
6500              // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)              // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
6501    
6502              // sample loading subtask              if (pProgress) {
6503              progress_t subprogress;                  // sample loading subtask
6504              __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask                  progress_t subprogress;
6505              __notify_progress(&subprogress, 0.0f);                  __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
6506              if (GetAutoLoad())                  __notify_progress(&subprogress, 0.0f);
6507                  GetFirstSample(&subprogress); // now force all samples to be loaded                  if (GetAutoLoad())
6508              __notify_progress(&subprogress, 1.0f);                      GetFirstSample(&subprogress); // now force all samples to be loaded
6509                    __notify_progress(&subprogress, 1.0f);
6510              // instrument loading subtask  
6511              if (pProgress && pProgress->callback) {                  // instrument loading subtask
6512                  subprogress.__range_min = subprogress.__range_max;                  if (pProgress->callback) {
6513                  subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask                      subprogress.__range_min = subprogress.__range_max;
6514              }                      subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
6515              __notify_progress(&subprogress, 0.0f);                  }
6516              LoadInstruments(&subprogress);                  __notify_progress(&subprogress, 0.0f);
6517              __notify_progress(&subprogress, 1.0f);                  LoadInstruments(&subprogress);
6518                    __notify_progress(&subprogress, 1.0f);
6519                } else {
6520                    // sample loading subtask
6521                    if (GetAutoLoad())
6522                        GetFirstSample(); // now force all samples to be loaded
6523    
6524                    // instrument loading subtask
6525                    LoadInstruments();
6526                }
6527          }          }
6528          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
6529          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
# Line 5927  namespace { Line 6672  namespace {
6672          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
6673          if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");          if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
6674          pInstruments->erase(iter);          pInstruments->erase(iter);
6675            pInstrument->DeleteChunks();
6676          delete pInstrument;          delete pInstrument;
6677      }      }
6678    
# Line 5942  namespace { Line 6688  namespace {
6688              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
6689              while (lstInstr) {              while (lstInstr) {
6690                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
6691                      // notify current progress                      if (pProgress) {
6692                      const float localProgress = (float) iInstrumentIndex / (float) Instruments;                          // notify current progress
6693                      __notify_progress(pProgress, localProgress);                          const float localProgress = (float) iInstrumentIndex / (float) Instruments;
6694                            __notify_progress(pProgress, localProgress);
                     // divide local progress into subprogress for loading current Instrument  
                     progress_t subprogress;  
                     __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);  
6695    
6696                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));                          // divide local progress into subprogress for loading current Instrument
6697                            progress_t subprogress;
6698                            __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
6699    
6700                            pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
6701                        } else {
6702                            pInstruments->push_back(new Instrument(this, lstInstr));
6703                        }
6704    
6705                      iInstrumentIndex++;                      iInstrumentIndex++;
6706                  }                  }
6707                  lstInstr = lstInstruments->GetNextSubList();                  lstInstr = lstInstruments->GetNextSubList();
6708              }              }
6709              __notify_progress(pProgress, 1.0); // notify done              if (pProgress)
6710                    __notify_progress(pProgress, 1.0); // notify done
6711          }          }
6712      }      }
6713    
# Line 6071  namespace { Line 6822  namespace {
6822              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
6823              // the order of einf and 3crc is not the same in v2 and v3              // the order of einf and 3crc is not the same in v2 and v3
6824              RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);              RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
6825              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major > 2) pRIFF->MoveSubChunk(_3crc, einf);
6826              bRequiresSave = true;              bRequiresSave = true;
6827          } else if (_3crc->GetNewSize() != pSamples->size() * 8) {          } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
6828              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
# Line 6186  namespace { Line 6937  namespace {
6937          }          }
6938          // now delete this group object          // now delete this group object
6939          pGroups->erase(iter);          pGroups->erase(iter);
6940            pGroup->DeleteChunks();
6941          delete pGroup;          delete pGroup;
6942      }      }
6943    
# Line 6207  namespace { Line 6959  namespace {
6959          // move all members of this group to another group          // move all members of this group to another group
6960          pGroup->MoveAll();          pGroup->MoveAll();
6961          pGroups->erase(iter);          pGroups->erase(iter);
6962            pGroup->DeleteChunks();
6963          delete pGroup;          delete pGroup;
6964      }      }
6965    
# Line 6220  namespace { Line 6973  namespace {
6973                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();                  RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
6974                  while (ck) {                  while (ck) {
6975                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {                      if (ck->GetChunkID() == CHUNK_ID_3GNM) {
6976                          if (pVersion && pVersion->major == 3 &&                          if (pVersion && pVersion->major > 2 &&
6977                              strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;                              strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
6978    
6979                          pGroups->push_back(new Group(this, ck));                          pGroups->push_back(new Group(this, ck));
# Line 6306  namespace { Line 7059  namespace {
7059              pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));              pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
7060          if (pScriptGroup->pList)          if (pScriptGroup->pList)
7061              pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);              pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
7062            pScriptGroup->DeleteChunks();
7063          delete pScriptGroup;          delete pScriptGroup;
7064      }      }
7065    
# Line 6396  namespace { Line 7150  namespace {
7150    
7151              // v3: make sure the file has 128 3gnm chunks              // v3: make sure the file has 128 3gnm chunks
7152              // (before updating the Group chunks)              // (before updating the Group chunks)
7153              if (pVersion && pVersion->major == 3) {              if (pVersion && pVersion->major > 2) {
7154                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
7155                  for (int i = 0 ; i < 128 ; i++) {                  for (int i = 0 ; i < 128 ; i++) {
7156                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);                      // create 128 empty placeholder strings which will either
7157                        // be filled by Group::UpdateChunks below or left empty.
7158                        ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
7159                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
7160                  }                  }
7161              }              }
# Line 6542  namespace { Line 7298  namespace {
7298          } else /*if (newFile)*/ {          } else /*if (newFile)*/ {
7299              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
7300              // the order of einf and 3crc is not the same in v2 and v3              // the order of einf and 3crc is not the same in v2 and v3
7301              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major > 2) pRIFF->MoveSubChunk(_3crc, einf);
7302          }          }
7303          { // must be performed in RAM here ...          { // must be performed in RAM here ...
7304              uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();              uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
# Line 6569  namespace { Line 7325  namespace {
7325      }      }
7326    
7327      /**      /**
7328       * Enable / disable automatic loading. By default this properyt is       * Enable / disable automatic loading. By default this property is
7329       * enabled and all informations are loaded automatically. However       * enabled and every information is loaded automatically. However
7330       * loading all Regions, DimensionRegions and especially samples might       * loading all Regions, DimensionRegions and especially samples might
7331       * take a long time for large .gig files, and sometimes one might only       * take a long time for large .gig files, and sometimes one might only
7332       * be interested in retrieving very superficial informations like the       * be interested in retrieving very superficial informations like the
# Line 6578  namespace { Line 7334  namespace {
7334       * automatic loading to avoid very slow response times.       * automatic loading to avoid very slow response times.
7335       *       *
7336       * @e CAUTION: by disabling this property many pointers (i.e. sample       * @e CAUTION: by disabling this property many pointers (i.e. sample
7337       * references) and informations will have invalid or even undefined       * references) and attributes will have invalid or even undefined
7338       * data! This feature is currently only intended for retrieving very       * data! This feature is currently only intended for retrieving very
7339       * superficial informations in a very fast way. Don't use it to retrieve       * superficial information in a very fast way. Don't use it to retrieve
7340       * details like synthesis informations or even to modify .gig files!       * details like synthesis information or even to modify .gig files!
7341       */       */
7342      void File::SetAutoLoad(bool b) {      void File::SetAutoLoad(bool b) {
7343          bAutoLoad = b;          bAutoLoad = b;
# Line 6595  namespace { Line 7351  namespace {
7351          return bAutoLoad;          return bAutoLoad;
7352      }      }
7353    
7354        /**
7355         * Returns @c true in case this gig File object uses any gig format
7356         * extension, that is e.g. whether any DimensionRegion object currently
7357         * has any setting effective that would require our "LSDE" RIFF chunk to
7358         * be stored to the gig file.
7359         *
7360         * Right now this is a private method. It is considerable though this method
7361         * to become (in slightly modified form) a public API method in future, i.e.
7362         * to allow instrument editors to visualize and/or warn the user of any gig
7363         * format extension being used. See also comments on
7364         * DimensionRegion::UsesAnyGigFormatExtension() for details about such a
7365         * potential public API change in future.
7366         */
7367        bool File::UsesAnyGigFormatExtension() const {
7368            if (!pInstruments) return false;
7369            InstrumentList::iterator iter = pInstruments->begin();
7370            InstrumentList::iterator end  = pInstruments->end();
7371            for (; iter != end; ++iter) {
7372                Instrument* pInstrument = static_cast<gig::Instrument*>(*iter);
7373                if (pInstrument->UsesAnyGigFormatExtension())
7374                    return true;
7375            }
7376            return false;
7377        }
7378    
7379    
7380  // *************** Exception ***************  // *************** Exception ***************

Legend:
Removed from v.3414  
changed lines
  Added in v.3903

  ViewVC Help
Powered by ViewVC