--- libgig/trunk/src/gig.cpp 2019/12/14 17:10:57 3657 +++ libgig/trunk/src/gig.cpp 2021/06/14 12:07:47 3924 @@ -2,7 +2,7 @@ * * * libgig - C++ cross-platform Gigasampler format file access library * * * - * Copyright (C) 2003-2019 by Christian Schoenebeck * + * Copyright (C) 2003-2021 by Christian Schoenebeck * * * * * * This library is free software; you can redistribute it and/or modify * @@ -482,8 +482,8 @@ ScanCompressedSample(); } - // we use a buffer for decompression and for truncating 24 bit samples to 16 bit - if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) { + // we use a buffer for decompression only + if (Compressed && !InternalDecompressionBuffer.Size) { InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE]; InternalDecompressionBuffer.Size = INITIAL_SAMPLE_BUFFER_SIZE; } @@ -3460,7 +3460,14 @@ store32(&pData[iWavePoolOffset + i * 4], iWaveIndex); } - if (versiongt2) { + // The following chunks are just added for compatibility with the + // GigaStudio software, which would show a warning if these were + // missing. However currently these chunks don't cover any useful + // data. So if this gig file uses any of our own gig format + // extensions which would cause this gig file to be unloadable + // with GSt software anyway, then just skip these GSt compatibility + // chunks here as well. + if (versiongt2 && !UsesAnyGigFormatExtension()) { // add 3dnm list which always seems to be empty RIFF::List* _3dnm = pCkRegion->GetSubList(LIST_TYPE_3DNM); if (!_3dnm) _3dnm = pCkRegion->AddSubList(LIST_TYPE_3DNM); @@ -3491,13 +3498,14 @@ RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG); if (_3prg) { int dimensionRegionNr = 0; - RIFF::List* _3ewl = _3prg->GetFirstSubList(); - while (_3ewl) { + size_t i = 0; + for (RIFF::List* _3ewl = _3prg->GetSubListAt(i); _3ewl; + _3ewl = _3prg->GetSubListAt(++i)) + { if (_3ewl->GetListType() == LIST_TYPE_3EWL) { pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl); dimensionRegionNr++; } - _3ewl = _3prg->GetNextSubList(); } if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found."); } @@ -3800,6 +3808,8 @@ * @throws gig::Exception if requested zone could not be deleted */ void Region::DeleteDimensionZone(dimension_t type, int zone) { + if (!Dimensions) + throw gig::Exception("Could not delete dimension zone, because there is no dimension at all."); dimension_def_t* oldDef = GetDimensionDefinition(type); if (!oldDef) throw gig::Exception("Could not delete dimension zone, no such dimension of given type"); @@ -3828,7 +3838,7 @@ // requested by the arguments of this method call) to the temporary // region, and don't use Region::CopyAssign() here for this task, since // it would also alter fast lookup helper variables here and there - dimension_def_t newDef; + dimension_def_t newDef = {}; for (int i = 0; i < Dimensions; ++i) { dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference // is this the dimension requested by the method arguments? ... @@ -3839,6 +3849,9 @@ } tempRgn->AddDimension(&def); } + // silence clang sanitizer warning + if (newDef.dimension == dimension_none) + throw gig::Exception("Unexpected internal failure resolving dimension in DeleteDimensionZone() [this is a bug]."); // find the dimension index in the tempRegion which is the dimension // type passed to this method (paranoidly expecting different order) @@ -3883,9 +3896,23 @@ // now tempRegion's dimensions and DimensionRegions basically reflect // what we wanted to get for this actual Region here, so we now just // delete and recreate the dimension in question with the new amount - // zones and then copy back from tempRegion - DeleteDimension(oldDef); - AddDimension(&newDef); + // zones and then copy back from tempRegion. we're actually deleting and + // recreating all dimensions here, to avoid altering the precise order + // of the dimensions (which would not be an error per se, but it would + // cause usability issues with instrument editors) + { + std::vector oldDefs; + for (int i = 0; i < Dimensions; ++i) + oldDefs.push_back(pDimensionDefinitions[i]); // copy, don't reference + for (int i = Dimensions - 1; i >= 0; --i) + DeleteDimension(&pDimensionDefinitions[i]); + for (int i = 0; i < oldDefs.size(); ++i) { + dimension_def_t& def = oldDefs[i]; + AddDimension( + (def.dimension == newDef.dimension) ? &newDef : &def + ); + } + } for (int iSrc = 0; iSrc < 256; ++iSrc) { DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc]; if (!srcDimRgn) continue; @@ -3925,6 +3952,8 @@ * @throws gig::Exception if requested zone could not be splitted */ void Region::SplitDimensionZone(dimension_t type, int zone) { + if (!Dimensions) + throw gig::Exception("Could not split dimension zone, because there is no dimension at all."); dimension_def_t* oldDef = GetDimensionDefinition(type); if (!oldDef) throw gig::Exception("Could not split dimension zone, no such dimension of given type"); @@ -3951,7 +3980,7 @@ // requested by the arguments of this method call) to the temporary // region, and don't use Region::CopyAssign() here for this task, since // it would also alter fast lookup helper variables here and there - dimension_def_t newDef; + dimension_def_t newDef = {}; for (int i = 0; i < Dimensions; ++i) { dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference // is this the dimension requested by the method arguments? ... @@ -3962,6 +3991,9 @@ } tempRgn->AddDimension(&def); } + // silence clang sanitizer warning + if (newDef.dimension == dimension_none) + throw gig::Exception("Unexpected internal failure resolving dimension in SplitDimensionZone() [this is a bug]."); // find the dimension index in the tempRegion which is the dimension // type passed to this method (paranoidly expecting different order) @@ -4023,9 +4055,23 @@ // now tempRegion's dimensions and DimensionRegions basically reflect // what we wanted to get for this actual Region here, so we now just // delete and recreate the dimension in question with the new amount - // zones and then copy back from tempRegion - DeleteDimension(oldDef); - AddDimension(&newDef); + // zones and then copy back from tempRegion. we're actually deleting and + // recreating all dimensions here, to avoid altering the precise order + // of the dimensions (which would not be an error per se, but it would + // cause usability issues with instrument editors) + { + std::vector oldDefs; + for (int i = 0; i < Dimensions; ++i) + oldDefs.push_back(pDimensionDefinitions[i]); // copy, don't reference + for (int i = Dimensions - 1; i >= 0; --i) + DeleteDimension(&pDimensionDefinitions[i]); + for (int i = 0; i < oldDefs.size(); ++i) { + dimension_def_t& def = oldDefs[i]; + AddDimension( + (def.dimension == newDef.dimension) ? &newDef : &def + ); + } + } for (int iSrc = 0; iSrc < 256; ++iSrc) { DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc]; if (!srcDimRgn) continue; @@ -4349,6 +4395,29 @@ Layers = orig->Layers; } + /** + * Returns @c true in case this Region object uses any gig format + * extension, that is e.g. whether any DimensionRegion object currently + * has any setting effective that would require our "LSDE" RIFF chunk to + * be stored to the gig file. + * + * Right now this is a private method. It is considerable though this method + * to become (in slightly modified form) a public API method in future, i.e. + * to allow instrument editors to visualize and/or warn the user of any gig + * format extension being used. See also comments on + * DimensionRegion::UsesAnyGigFormatExtension() for details about such a + * potential public API change in future. + */ + bool Region::UsesAnyGigFormatExtension() const { + for (int i = 0; i < 256; i++) { + if (pDimensionRegions[i]) { + if (pDimensionRegions[i]->UsesAnyGigFormatExtension()) + return true; + } + } + return false; + } + // *************** MidiRule *************** // * @@ -4530,12 +4599,20 @@ Compression = (Compression_t) ckScri->ReadUint32(); Encoding = (Encoding_t) ckScri->ReadUint32(); Language = (Language_t) ckScri->ReadUint32(); - Bypass = (Language_t) ckScri->ReadUint32() & 1; + Bypass = ckScri->ReadUint32() & 1; crc = ckScri->ReadUint32(); uint32_t nameSize = ckScri->ReadUint32(); Name.resize(nameSize, ' '); for (int i = 0; i < nameSize; ++i) Name[i] = ckScri->ReadUint8(); + // check if an uuid was already stored along with this script + if (headerSize >= 6*sizeof(int32_t) + nameSize + 16) { // yes ... + for (uint i = 0; i < 16; ++i) { + Uuid[i] = ckScri->ReadUint8(); + } + } else { // no uuid yet, generate one now ... + GenerateUuid(); + } // to handle potential future extensions of the header ckScri->SetPos(sizeof(int32_t) + headerSize); // read actual script data @@ -4550,6 +4627,7 @@ Bypass = false; crc = 0; Name = "Unnamed Script"; + GenerateUuid(); } } @@ -4604,13 +4682,14 @@ __calculateCRC(&data[0], data.size(), crc); __finalizeCRC(crc); // make sure chunk exists and has the required size - const file_offset_t chunkSize = (file_offset_t) 7*sizeof(int32_t) + Name.size() + data.size(); + const file_offset_t chunkSize = + (file_offset_t) 7*sizeof(int32_t) + Name.size() + 16 + data.size(); if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize); else pChunk->Resize(chunkSize); // fill the chunk data to be written to disk uint8_t* pData = (uint8_t*) pChunk->LoadChunkData(); int pos = 0; - 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 pos += sizeof(int32_t); store32(&pData[pos], Compression); pos += sizeof(int32_t); @@ -4626,11 +4705,37 @@ pos += sizeof(int32_t); for (int i = 0; i < Name.size(); ++i, ++pos) pData[pos] = Name[i]; + for (int i = 0; i < 16; ++i, ++pos) + pData[pos] = Uuid[i]; for (int i = 0; i < data.size(); ++i, ++pos) pData[pos] = data[i]; } /** + * Generate a new Universally Unique Identifier (UUID) for this script. + */ + void Script::GenerateUuid() { + DLS::dlsid_t dlsid; + DLS::Resource::GenerateDLSID(&dlsid); + Uuid[0] = dlsid.ulData1 & 0xff; + Uuid[1] = dlsid.ulData1 >> 8 & 0xff; + Uuid[2] = dlsid.ulData1 >> 16 & 0xff; + Uuid[3] = dlsid.ulData1 >> 24 & 0xff; + Uuid[4] = dlsid.usData2 & 0xff; + Uuid[5] = dlsid.usData2 >> 8 & 0xff; + Uuid[6] = dlsid.usData3 & 0xff; + Uuid[7] = dlsid.usData3 >> 8 & 0xff; + Uuid[8] = dlsid.abData[0]; + Uuid[9] = dlsid.abData[1]; + Uuid[10] = dlsid.abData[2]; + Uuid[11] = dlsid.abData[3]; + Uuid[12] = dlsid.abData[4]; + Uuid[13] = dlsid.abData[5]; + Uuid[14] = dlsid.abData[6]; + Uuid[15] = dlsid.abData[7]; + } + + /** * Move this script from its current ScriptGroup to another ScriptGroup * given by @a pGroup. * @@ -4802,8 +4907,9 @@ pScripts = new std::list; if (!pList) return; - for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck; - ck = pList->GetNextSubChunk()) + size_t i = 0; + for (RIFF::Chunk* ck = pList->GetSubChunkAt(i); ck; + ck = pList->GetSubChunkAt(++i)) { if (ck->GetChunkID() == CHUNK_ID_SCRI) { pScripts->push_back(new Script(this, ck)); @@ -4883,14 +4989,15 @@ if (!pRegions) pRegions = new RegionList; RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN); if (lrgn) { - RIFF::List* rgn = lrgn->GetFirstSubList(); - while (rgn) { + size_t i = 0; + for (RIFF::List* rgn = lrgn->GetSubListAt(i); rgn; + rgn = lrgn->GetSubListAt(++i)) + { if (rgn->GetListType() == LIST_TYPE_RGN) { if (pProgress) __notify_progress(pProgress, (float) pRegions->size() / (float) Regions); pRegions->push_back(new Region(this, rgn)); } - rgn = lrgn->GetNextSubList(); } // Creating Region Key Table for fast lookup UpdateRegionKeyTable(); @@ -4900,6 +5007,7 @@ // own gig format extensions RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS); if (lst3LS) { + // script slots (that is references to instrument scripts) RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL); if (ckSCSL) { ckSCSL->SetPos(0); @@ -4919,6 +5027,44 @@ } } } + + // overridden script 'patch' variables + RIFF::Chunk* ckSCPV = lst3LS->GetSubChunk(CHUNK_ID_SCPV); + if (ckSCPV) { + ckSCPV->SetPos(0); + + int nScripts = ckSCPV->ReadUint32(); + for (int iScript = 0; iScript < nScripts; ++iScript) { + _UUID uuid; + for (int i = 0; i < 16; ++i) + uuid[i] = ckSCPV->ReadUint8(); + uint slot = ckSCPV->ReadUint32(); + ckSCPV->ReadUint32(); // unused, reserved 32 bit + int nVars = ckSCPV->ReadUint32(); + for (int iVar = 0; iVar < nVars; ++iVar) { + uint8_t type = ckSCPV->ReadUint8(); + ckSCPV->ReadUint8(); // unused, reserved byte + int blobSize = ckSCPV->ReadUint16(); + RIFF::file_offset_t pos = ckSCPV->GetPos(); + // assuming 1st bit is set in 'type', otherwise blob not + // supported for decoding + if (type & 1) { + String name, value; + int len = ckSCPV->ReadUint16(); + for (int i = 0; i < len; ++i) + name += (char) ckSCPV->ReadUint8(); + len = ckSCPV->ReadUint16(); + for (int i = 0; i < len; ++i) + value += (char) ckSCPV->ReadUint8(); + if (!name.empty()) // 'name' should never be empty, but just to be sure + scriptVars[uuid][slot][name] = value; + } + // also for potential future extensions: seek forward + // according to blob size + ckSCPV->SetPos(pos + blobSize); + } + } + } } if (pProgress) @@ -5010,6 +5156,8 @@ RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS); if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS); + + // save script slots (that is references to instrument scripts) const int slotCount = (int) pScriptRefs->size(); const int headerSize = 3 * sizeof(uint32_t); const int slotSize = 2 * sizeof(uint32_t); @@ -5034,6 +5182,78 @@ store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0); pos += sizeof(uint32_t); } + + // save overridden script 'patch' variables ... + + // the actual 'scriptVars' member variable might contain variables of + // scripts which are currently no longer assigned to any script slot + // of this instrument, we need to get rid of these variables here to + // prevent saving those persistently, however instead of touching the + // member variable 'scriptVars' directly, rather strip a separate + // copy such that the overridden values are not lost during an + // instrument editor session (i.e. if script might be re-assigned) + _VarsByScript vars = stripScriptVars(); + if (!vars.empty()) { + // determine total size required for 'SCPV' RIFF chunk, and the + // total amount of scripts being overridden (the latter is + // required because a script might be used on several script + // slots, hence vars.size() could then not be used here instead) + size_t totalChunkSize = 4; + size_t totalScriptsOverridden = 0; + for (const auto& script : vars) { + for (const auto& slot : script.second) { + totalScriptsOverridden++; + totalChunkSize += 16 + 4 + 4 + 4; + for (const auto& var : slot.second) { + totalChunkSize += 4 + 2 + var.first.length() + + 2 + var.second.length(); + } + } + } + + // ensure 'SCPV' RIFF chunk exists (with required size) + RIFF::Chunk* ckSCPV = lst3LS->GetSubChunk(CHUNK_ID_SCPV); + if (!ckSCPV) ckSCPV = lst3LS->AddSubChunk(CHUNK_ID_SCPV, totalChunkSize); + else ckSCPV->Resize(totalChunkSize); + + // store the actual data to 'SCPV' RIFF chunk + uint8_t* pData = (uint8_t*) ckSCPV->LoadChunkData(); + int pos = 0; + store32(&pData[pos], (uint32_t) totalScriptsOverridden); // scripts count + pos += 4; + for (const auto& script : vars) { + for (const auto& slot : script.second) { + for (int i = 0; i < 16; ++i) + pData[pos+i] = script.first[i]; // uuid + pos += 16; + store32(&pData[pos], (uint32_t) slot.first); // slot index + pos += 4; + store32(&pData[pos], (uint32_t) 0); // unused, reserved 32 bit + pos += 4; + store32(&pData[pos], (uint32_t) slot.second.size()); // variables count + pos += 4; + for (const auto& var : slot.second) { + pData[pos++] = 1; // type + pData[pos++] = 0; // reserved byte + store16(&pData[pos], 2 + var.first.size() + 2 + var.second.size()); // blob size + pos += 2; + store16(&pData[pos], var.first.size()); // variable name length + pos += 2; + for (int i = 0; i < var.first.size(); ++i) + pData[pos++] = var.first[i]; + store16(&pData[pos], var.second.size()); // variable value length + pos += 2; + for (int i = 0; i < var.second.size(); ++i) + pData[pos++] = var.second[i]; + } + } + } + } else { + // no script variable overridden by this instrument, so get rid + // of 'SCPV' RIFF chunk (if any) + RIFF::Chunk* ckSCPV = lst3LS->GetSubChunk(CHUNK_ID_SCPV); + if (ckSCPV) lst3LS->DeleteSubChunk(ckSCPV); + } } else { // no script slots, so get rid of any LS custom RIFF chunks (if any) RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS); @@ -5458,6 +5678,265 @@ scriptPoolFileOffsets.at(index).bypass = bBypass; } + /// type cast (by copy) uint8_t[16] -> std::array + inline std::array _UUIDFromCArray(const uint8_t* pData) { + std::array uuid; + memcpy(&uuid[0], pData, 16); + return uuid; + } + + /** + * Returns true if this @c Instrument has any script slot which references + * the @c Script identified by passed @p uuid. + */ + bool Instrument::ReferencesScriptWithUuid(const _UUID& uuid) { + const uint nSlots = ScriptSlotCount(); + for (uint iSlot = 0; iSlot < nSlots; ++iSlot) + if (_UUIDFromCArray(&GetScriptOfSlot(iSlot)->Uuid[0]) == uuid) + return true; + return false; + } + + /** @brief Checks whether a certain script 'patch' variable value is set. + * + * Returns @c true if the initial value for the requested script variable is + * currently overridden by this instrument. + * + * @remarks Real-time instrument scripts allow to declare special 'patch' + * variables, which essentially behave like regular variables of their data + * type, however their initial value may optionally be overridden on a per + * instrument basis. That allows to share scripts between instruments while + * still being able to fine tune certain aspects of the script for each + * instrument individually. + * + * @note This is an own format extension which did not exist i.e. in the + * GigaStudio 4 software. It will currently only work with LinuxSampler and + * Gigedit. + * + * @param slot - script slot index of the variable to be retrieved + * @param variable - name of the 'patch' variable in that script + */ + bool Instrument::IsScriptPatchVariableSet(int slot, String variable) { + if (variable.empty()) return false; + Script* script = GetScriptOfSlot(slot); + if (!script) return false; + const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]); + if (!scriptVars.count(uuid)) return false; + const _VarsBySlot& slots = scriptVars.find(uuid)->second; + if (slots.empty()) return false; + if (slots.count(slot)) + return slots.find(slot)->second.count(variable); + else + return slots.begin()->second.count(variable); + } + + /** @brief Get all overridden script 'patch' variables. + * + * Returns map of key-value pairs reflecting all patch variables currently + * being overridden by this instrument for the given script @p slot, where + * key is the variable name and value is the hereby currently overridden + * value for that variable. + * + * @remarks Real-time instrument scripts allow to declare special 'patch' + * variables, which essentially behave like regular variables of their data + * type, however their initial value may optionally be overridden on a per + * instrument basis. That allows to share scripts between instruments while + * still being able to fine tune certain aspects of the script for each + * instrument individually. + * + * @note This is an own format extension which did not exist i.e. in the + * GigaStudio 4 software. It will currently only work with LinuxSampler and + * Gigedit. + * + * @param slot - script slot index of the variable to be retrieved + */ + std::map Instrument::GetScriptPatchVariables(int slot) { + Script* script = GetScriptOfSlot(slot); + if (!script) return std::map(); + const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]); + if (!scriptVars.count(uuid)) return std::map(); + const _VarsBySlot& slots = scriptVars.find(uuid)->second; + if (slots.empty()) return std::map(); + const _PatchVars& vars = + (slots.count(slot)) ? + slots.find(slot)->second : slots.begin()->second; + return vars; + } + + /** @brief Get overridden initial value for 'patch' variable. + * + * Returns current initial value for the requested script variable being + * overridden by this instrument. + * + * @remarks Real-time instrument scripts allow to declare special 'patch' + * variables, which essentially behave like regular variables of their data + * type, however their initial value may optionally be overridden on a per + * instrument basis. That allows to share scripts between instruments while + * still being able to fine tune certain aspects of the script for each + * instrument individually. + * + * @note This is an own format extension which did not exist i.e. in the + * GigaStudio 4 software. It will currently only work with LinuxSampler and + * Gigedit. + * + * @param slot - script slot index of the variable to be retrieved + * @param variable - name of the 'patch' variable in that script + */ + String Instrument::GetScriptPatchVariable(int slot, String variable) { + std::map vars = GetScriptPatchVariables(slot); + return (vars.count(variable)) ? vars.find(variable)->second : ""; + } + + /** @brief Override initial value for 'patch' variable. + * + * Overrides initial value for the requested script variable for this + * instrument with the passed value. + * + * @remarks Real-time instrument scripts allow to declare special 'patch' + * variables, which essentially behave like regular variables of their data + * type, however their initial value may optionally be overridden on a per + * instrument basis. That allows to share scripts between instruments while + * still being able to fine tune certain aspects of the script for each + * instrument individually. + * + * @note This is an own format extension which did not exist i.e. in the + * GigaStudio 4 software. It will currently only work with LinuxSampler and + * Gigedit. + * + * @param slot - script slot index of the variable to be set + * @param variable - name of the 'patch' variable in that script + * @param value - overridden initial value for that script variable + * @throws gig::Exception if given script @p slot index is invalid or given + * @p variable name is empty + */ + void Instrument::SetScriptPatchVariable(int slot, String variable, String value) { + if (variable.empty()) + throw Exception("Variable name must not be empty"); + Script* script = GetScriptOfSlot(slot); + if (!script) + throw Exception("No script slot with index " + ToString(slot)); + const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]); + scriptVars[uuid][slot][variable] = value; + } + + /** @brief Drop overridden initial value(s) for 'patch' variable(s). + * + * Reverts initial value(s) for requested script variable(s) back to their + * default initial value(s) defined in the script itself. + * + * Both arguments of this method are optional. The most obvious use case of + * this method would be passing a valid script @p slot index and a + * (non-emtpy string as) @p variable name to this method, which would cause + * that single variable to be unset for that specific script slot (on this + * @c Instrument level). + * + * Not passing a value (or @c -1 for @p slot and/or empty string for + * @p variable) means 'wildcard'. So accordingly absence of argument(s) will + * cause all variables and/or for all script slots being unset. Hence this + * method serves 2^2 = 4 possible use cases in total and accordingly covers + * 4 different behaviours in one method. + * + * @remarks Real-time instrument scripts allow to declare special 'patch' + * variables, which essentially behave like regular variables of their data + * type, however their initial value may optionally be overridden on a per + * instrument basis. That allows to share scripts between instruments while + * still being able to fine tune certain aspects of the script for each + * instrument individually. + * + * @note This is an own format extension which did not exist i.e. in the + * GigaStudio 4 software. It will currently only work with LinuxSampler and + * Gigedit. + * + * @param slot - script slot index of the variable to be unset + * @param variable - name of the 'patch' variable in that script + */ + void Instrument::UnsetScriptPatchVariable(int slot, String variable) { + Script* script = GetScriptOfSlot(slot); + + // option 1: unset a particular variable of one particular script slot + if (slot != -1 && !variable.empty()) { + if (!script) return; + const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]); + if (!scriptVars.count(uuid)) return; + if (!scriptVars[uuid].count(slot)) return; + if (scriptVars[uuid][slot].count(variable)) + scriptVars[uuid][slot].erase( + scriptVars[uuid][slot].find(variable) + ); + if (scriptVars[uuid][slot].empty()) + scriptVars[uuid].erase( scriptVars[uuid].find(slot) ); + if (scriptVars[uuid].empty()) + scriptVars.erase( scriptVars.find(uuid) ); + return; + } + + // option 2: unset all variables of all script slots + if (slot == -1 && variable.empty()) { + scriptVars.clear(); + return; + } + + // option 3: unset all variables of one particular script slot only + if (slot != -1) { + if (!script) return; + const _UUID uuid = _UUIDFromCArray(&script->Uuid[0]); + if (scriptVars.count(uuid)) + scriptVars.erase( scriptVars.find(uuid) ); + return; + } + + // option 4: unset a particular variable of all script slots + _VarsByScript::iterator itScript = scriptVars.begin(); + _VarsByScript::iterator endScript = scriptVars.end(); + while (itScript != endScript) { + _VarsBySlot& slots = itScript->second; + _VarsBySlot::iterator itSlot = slots.begin(); + _VarsBySlot::iterator endSlot = slots.end(); + while (itSlot != endSlot) { + _PatchVars& vars = itSlot->second; + if (vars.count(variable)) + vars.erase( vars.find(variable) ); + if (vars.empty()) + slots.erase(itSlot++); // postfix increment to avoid iterator invalidation + else + ++itSlot; + } + if (slots.empty()) + scriptVars.erase(itScript++); // postfix increment to avoid iterator invalidation + else + ++itScript; + } + } + + /** + * Returns stripped version of member variable @c scriptVars, where scripts + * no longer referenced by this @c Instrument are filtered out, and so are + * variables of meanwhile obsolete slots (i.e. a script still being + * referenced, but previously overridden on a script slot which either no + * longer exists or is hosting another script now). + */ + Instrument::_VarsByScript Instrument::stripScriptVars() { + _VarsByScript vars; + _VarsByScript::const_iterator itScript = scriptVars.begin(); + _VarsByScript::const_iterator endScript = scriptVars.end(); + for (; itScript != endScript; ++itScript) { + const _UUID& uuid = itScript->first; + if (!ReferencesScriptWithUuid(uuid)) + continue; + const _VarsBySlot& slots = itScript->second; + _VarsBySlot::const_iterator itSlot = slots.begin(); + _VarsBySlot::const_iterator endSlot = slots.end(); + for (; itSlot != endSlot; ++itSlot) { + Script* script = GetScriptOfSlot(itSlot->first); + if (!script) continue; + if (_UUIDFromCArray(&script->Uuid[0]) != uuid) continue; + if (itSlot->second.empty()) continue; + vars[uuid][itSlot->first] = itSlot->second; + } + } + return vars; + } + /** * Make a (semi) deep copy of the Instrument object given by @a orig * and assign it to this object. @@ -5492,7 +5971,12 @@ PianoReleaseMode = orig->PianoReleaseMode; DimensionKeyRange = orig->DimensionKeyRange; scriptPoolFileOffsets = orig->scriptPoolFileOffsets; - pScriptRefs = orig->pScriptRefs; + // deep copy of pScriptRefs required (to avoid undefined behaviour) + if (pScriptRefs) delete pScriptRefs; + pScriptRefs = new std::vector<_ScriptPooolRef>; + if (orig->pScriptRefs) + *pScriptRefs = *orig->pScriptRefs; + scriptVars = orig->scriptVars; // free old midi rules for (int i = 0 ; pMidiRules[i] ; i++) { @@ -5519,6 +6003,32 @@ UpdateRegionKeyTable(); } + /** + * Returns @c true in case this Instrument object uses any gig format + * extension, that is e.g. whether any DimensionRegion object currently + * has any setting effective that would require our "LSDE" RIFF chunk to + * be stored to the gig file. + * + * Right now this is a private method. It is considerable though this method + * to become (in slightly modified form) a public API method in future, i.e. + * to allow instrument editors to visualize and/or warn the user of any gig + * format extension being used. See also comments on + * DimensionRegion::UsesAnyGigFormatExtension() for details about such a + * potential public API change in future. + */ + bool Instrument::UsesAnyGigFormatExtension() const { + if (!pRegions) return false; + if (!scriptVars.empty()) return true; + RegionList::const_iterator iter = pRegions->begin(); + RegionList::const_iterator end = pRegions->end(); + for (; iter != end; ++iter) { + gig::Region* rgn = static_cast(*iter); + if (rgn->UsesAnyGigFormatExtension()) + return true; + } + return false; + } + // *************** Group *************** // * @@ -5576,7 +6086,8 @@ if (!pNameChunk && pFile->pVersion && pFile->pVersion->major > 2) { // v3 has a fixed list of 128 strings, find a free one - for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) { + size_t i = 0; + for (RIFF::Chunk* ck = _3gnl->GetSubChunkAt(i); ck; ck = _3gnl->GetSubChunkAt(++i)) { if (strcmp(static_cast(ck->LoadChunkData()), "") == 0) { pNameChunk = ck; break; @@ -5936,8 +6447,10 @@ if (wvpl) { file_offset_t wvplFileOffset = wvpl->GetFilePos() - wvpl->GetPos(); // should be zero, but just to be sure - RIFF::List* wave = wvpl->GetFirstSubList(); - while (wave) { + size_t i = 0; + for (RIFF::List* wave = wvpl->GetSubListAt(i); wave; + wave = wvpl->GetSubListAt(++i)) + { if (wave->GetListType() == LIST_TYPE_WAVE) { // notify current progress if (pProgress) { @@ -5950,7 +6463,6 @@ iSampleIndex++; } - wave = wvpl->GetNextSubList(); } } } @@ -6183,8 +6695,10 @@ RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS); if (lstInstruments) { int iInstrumentIndex = 0; - RIFF::List* lstInstr = lstInstruments->GetFirstSubList(); - while (lstInstr) { + size_t i = 0; + for (RIFF::List* lstInstr = lstInstruments->GetSubListAt(i); + lstInstr; lstInstr = lstInstruments->GetSubListAt(++i)) + { if (lstInstr->GetListType() == LIST_TYPE_INS) { if (pProgress) { // notify current progress @@ -6202,7 +6716,6 @@ iInstrumentIndex++; } - lstInstr = lstInstruments->GetNextSubList(); } if (pProgress) __notify_progress(pProgress, 1.0); // notify done @@ -6468,15 +6981,16 @@ if (lst3gri) { RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL); if (lst3gnl) { - RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk(); - while (ck) { + size_t i = 0; + for (RIFF::Chunk* ck = lst3gnl->GetSubChunkAt(i); ck; + ck = lst3gnl->GetSubChunkAt(++i)) + { if (ck->GetChunkID() == CHUNK_ID_3GNM) { if (pVersion && pVersion->major > 2 && strcmp(static_cast(ck->LoadChunkData()), "") == 0) break; pGroups->push_back(new Group(this, ck)); } - ck = lst3gnl->GetNextSubChunk(); } } } @@ -6566,8 +7080,9 @@ pScriptGroups = new std::list; RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS); if (lstLS) { - for (RIFF::List* lst = lstLS->GetFirstSubList(); lst; - lst = lstLS->GetNextSubList()) + size_t i = 0; + for (RIFF::List* lst = lstLS->GetSubListAt(i); lst; + lst = lstLS->GetSubListAt(++i)) { if (lst->GetListType() == LIST_TYPE_RTIS) { pScriptGroups->push_back(new ScriptGroup(this, lst)); @@ -6628,7 +7143,7 @@ // INFO was added by Resource::UpdateChunks - make sure it // is placed first in file RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO); - RIFF::Chunk* first = pRIFF->GetFirstSubChunk(); + RIFF::Chunk* first = pRIFF->GetSubChunkAt(0); if (first != info) { pRIFF->MoveSubChunk(info, first); } @@ -6649,12 +7164,13 @@ // v3: make sure the file has 128 3gnm chunks // (before updating the Group chunks) if (pVersion && pVersion->major > 2) { - RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk(); - for (int i = 0 ; i < 128 ; i++) { + size_t i = 0; + for (RIFF::Chunk* _3gnm = _3gnl->GetSubChunkAt(i); i < 128; + _3gnm = _3gnl->GetSubChunkAt(++i)) + { // create 128 empty placeholder strings which will either // be filled by Group::UpdateChunks below or left empty. ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64); - if (_3gnm) _3gnm = _3gnl->GetNextSubChunk(); } } @@ -6849,6 +7365,30 @@ return bAutoLoad; } + /** + * Returns @c true in case this gig File object uses any gig format + * extension, that is e.g. whether any DimensionRegion object currently + * has any setting effective that would require our "LSDE" RIFF chunk to + * be stored to the gig file. + * + * Right now this is a private method. It is considerable though this method + * to become (in slightly modified form) a public API method in future, i.e. + * to allow instrument editors to visualize and/or warn the user of any gig + * format extension being used. See also comments on + * DimensionRegion::UsesAnyGigFormatExtension() for details about such a + * potential public API change in future. + */ + bool File::UsesAnyGigFormatExtension() const { + if (!pInstruments) return false; + InstrumentList::iterator iter = pInstruments->begin(); + InstrumentList::iterator end = pInstruments->end(); + for (; iter != end; ++iter) { + Instrument* pInstrument = static_cast(*iter); + if (pInstrument->UsesAnyGigFormatExtension()) + return true; + } + return false; + } // *************** Exception ***************