/[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 3481 by schoenebeck, Fri Feb 22 12:12:50 2019 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-2019 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 1740  namespace { Line 1740  namespace {
1740              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1741              memset(DimensionUpperLimits, 127, 8);              memset(DimensionUpperLimits, 127, 8);
1742          }          }
1743    
1744          // chunk for own format extensions, these will *NOT* work with 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) { // format extension for EG behavior options          if (lsde) { // format extension for EG behavior options
# Line 1765  namespace { Line 1766  namespace {
1766              SustainReleaseTrigger   = sust_rel_trg_none;              SustainReleaseTrigger   = sust_rel_trg_none;
1767              NoNoteOffReleaseTrigger = false;              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 1890  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 1908  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 1916  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 2267  namespace { Line 2297  namespace {
2297          // chunk for own format extensions, 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          const int lsdeSize = 4; // NOTE: we reserved the 3rd byte for a potential future EG3 option          const int lsdeSize =
2301          if (!lsde) {              3 /* EG cancel options */ +
2302              // only add this "LSDE" chunk if either EG options or release              1 /* sustain pedal up on release trigger option */ +
2303              // trigger options deviate from their default behaviour              8 /* LFOs' wave forms */ + 12 /* LFOs' phase */ + 4 /* flags (LFO3FlipPhase) */;
2304              eg_opt_t defaultOpt;          if (!lsde && UsesAnyGigFormatExtension()) {
2305              if (memcmp(&EG1Options, &defaultOpt, sizeof(eg_opt_t)) ||              // only add this "LSDE" chunk if there is some (format extension)
2306                  memcmp(&EG2Options, &defaultOpt, sizeof(eg_opt_t)) ||              // setting effective that would require our "LSDE" format extension
2307                  SustainReleaseTrigger || NoNoteOffReleaseTrigger)              // chunk to be stored
2308              {              lsde = pParentList->AddSubChunk(CHUNK_ID_LSDE, lsdeSize);
2309                  lsde = pParentList->AddSubChunk(CHUNK_ID_LSDE, lsdeSize);              // move LSDE chunk to the end of parent list
2310                  // move LSDE chunk to the end of parent list              pParentList->MoveSubChunk(lsde, (RIFF::Chunk*)NULL);
                 pParentList->MoveSubChunk(lsde, (RIFF::Chunk*)NULL);  
             }  
2311          }          }
2312          if (lsde) {          if (lsde) {
2313              if (lsde->GetNewSize() < lsdeSize)              if (lsde->GetNewSize() < lsdeSize)
# Line 2297  namespace { Line 2325  namespace {
2325              }              }
2326              // format extension for release trigger options              // format extension for release trigger options
2327              pData[3] = static_cast<uint8_t>(SustainReleaseTrigger) | (NoNoteOffReleaseTrigger ? (1<<7) : 0);              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 3341  namespace { Line 3412  namespace {
3412          }          }
3413    
3414          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
3415          bool versiongt2 = pFile->pVersion && pFile->pVersion->major > 2;          const bool versiongt2 = pFile->pVersion && pFile->pVersion->major > 2;
3416          const int iMaxDimensions =  versiongt2 ? 8 : 5;          const int iMaxDimensions =  versiongt2 ? 8 : 5;
3417          const int iMaxDimensionRegions = versiongt2 ? 256 : 32;          const int iMaxDimensionRegions = versiongt2 ? 256 : 32;
3418    
# Line 3388  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 3703  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 3731  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 3742  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 3786  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 3926  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 4252  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 4433  namespace { Line 4593  namespace {
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 4453  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 4507  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 4529  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 4789  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 4802  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);                  ckSCSL->SetPos(0);
# Line 4821  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 4911  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 4935  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 5359  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 5393  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 5420  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 5841  namespace { Line 6442  namespace {
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, i, iSampleIndex));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, i, iSampleIndex));
# Line 5854  namespace { Line 6457  namespace {
6457              }              }
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 5895  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 6075  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 6535  namespace { Line 7153  namespace {
7153              if (pVersion && pVersion->major > 2) {              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 6731  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.3481  
changed lines
  Added in v.3903

  ViewVC Help
Powered by ViewVC