--- libgig/trunk/src/gig.cpp 2018/01/30 20:17:12 3414 +++ libgig/trunk/src/gig.cpp 2021/05/12 18:55:31 3904 @@ -2,7 +2,7 @@ * * * libgig - C++ cross-platform Gigasampler format file access library * * * - * Copyright (C) 2003-2018 by Christian Schoenebeck * + * Copyright (C) 2003-2021 by Christian Schoenebeck * * * * * * This library is free software; you can redistribute it and/or modify * @@ -412,6 +412,8 @@ pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX); if (pCk3gix) { + pCk3gix->SetPos(0); + uint16_t iSampleGroup = pCk3gix->ReadInt16(); pGroup = pFile->GetGroup(iSampleGroup); } else { // '3gix' chunk missing @@ -421,6 +423,8 @@ pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL); if (pCkSmpl) { + pCkSmpl->SetPos(0); + Manufacturer = pCkSmpl->ReadInt32(); Product = pCkSmpl->ReadInt32(); SamplePeriod = pCkSmpl->ReadInt32(); @@ -467,8 +471,10 @@ Dithered = false; TruncatedBits = 0; if (Compressed) { + ewav->SetPos(0); + uint32_t version = ewav->ReadInt32(); - if (version == 3 && BitDepth == 24) { + if (version > 2 && BitDepth == 24) { Dithered = ewav->ReadInt32(); ewav->SetPos(Channels == 2 ? 84 : 64); TruncatedBits = ewav->ReadInt32(); @@ -1500,6 +1506,8 @@ RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA); if (_3ewa) { // if '3ewa' chunk exists + _3ewa->SetPos(0); + _3ewa->ReadInt32(); // unknown, always == chunk size ? LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32()); EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32()); @@ -1732,12 +1740,14 @@ VCFType = vcf_type_lowpass; memset(DimensionUpperLimits, 127, 8); } - // format extension for EG behavior options, these will *NOT* work with - // Gigasampler/GigaStudio ! + + // chunk for own format extensions, these will *NOT* work with Gigasampler/GigaStudio ! RIFF::Chunk* lsde = _3ewl->GetSubChunk(CHUNK_ID_LSDE); - if (lsde) { + if (lsde) { // format extension for EG behavior options + lsde->SetPos(0); + eg_opt_t* pEGOpts[2] = { &EG1Options, &EG2Options }; - for (int i = 0; i < 2; ++i) { + for (int i = 0; i < 2; ++i) { // NOTE: we reserved a 3rd byte for a potential future EG3 option unsigned char byte = lsde->ReadUint8(); pEGOpts[i]->AttackCancel = byte & 1; pEGOpts[i]->AttackHoldCancel = byte & (1 << 1); @@ -1746,6 +1756,38 @@ pEGOpts[i]->ReleaseCancel = byte & (1 << 4); } } + // format extension for sustain pedal up effect on release trigger samples + if (lsde && lsde->GetSize() > 3) { // NOTE: we reserved the 3rd byte for a potential future EG3 option + lsde->SetPos(3); + uint8_t byte = lsde->ReadUint8(); + SustainReleaseTrigger = static_cast(byte & 0x03); + NoNoteOffReleaseTrigger = byte >> 7; + } else { + SustainReleaseTrigger = sust_rel_trg_none; + NoNoteOffReleaseTrigger = false; + } + // format extension for LFOs' wave form, phase displacement and for + // LFO3's flip phase + if (lsde && lsde->GetSize() > 4) { + lsde->SetPos(4); + LFO1WaveForm = static_cast( lsde->ReadUint16() ); + LFO2WaveForm = static_cast( lsde->ReadUint16() ); + LFO3WaveForm = static_cast( lsde->ReadUint16() ); + lsde->ReadUint16(); // unused 16 bits, reserved for potential future use + LFO1Phase = (double) GIG_EXP_DECODE( lsde->ReadInt32() ); + LFO2Phase = (double) GIG_EXP_DECODE( lsde->ReadInt32() ); + LFO3Phase = (double) GIG_EXP_DECODE( lsde->ReadInt32() ); + const uint32_t flags = lsde->ReadInt32(); + LFO3FlipPhase = flags & 1; + } else { + LFO1WaveForm = lfo_wave_sine; + LFO2WaveForm = lfo_wave_sine; + LFO3WaveForm = lfo_wave_sine; + LFO1Phase = 0.0; + LFO2Phase = 0.0; + LFO3Phase = 0.0; + LFO3FlipPhase = false; + } pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve, VelocityResponseDepth, @@ -1871,7 +1913,9 @@ SRLZ(EG1ControllerAttackInfluence); SRLZ(EG1ControllerDecayInfluence); SRLZ(EG1ControllerReleaseInfluence); + SRLZ(LFO1WaveForm); SRLZ(LFO1Frequency); + SRLZ(LFO1Phase); SRLZ(LFO1InternalDepth); SRLZ(LFO1ControlDepth); SRLZ(LFO1Controller); @@ -1889,7 +1933,9 @@ SRLZ(EG2ControllerAttackInfluence); SRLZ(EG2ControllerDecayInfluence); SRLZ(EG2ControllerReleaseInfluence); + SRLZ(LFO2WaveForm); SRLZ(LFO2Frequency); + SRLZ(LFO2Phase); SRLZ(LFO2InternalDepth); SRLZ(LFO2ControlDepth); SRLZ(LFO2Controller); @@ -1897,10 +1943,13 @@ SRLZ(LFO2Sync); SRLZ(EG3Attack); SRLZ(EG3Depth); + SRLZ(LFO3WaveForm); SRLZ(LFO3Frequency); + SRLZ(LFO3Phase); SRLZ(LFO3InternalDepth); SRLZ(LFO3ControlDepth); SRLZ(LFO3Controller); + SRLZ(LFO3FlipPhase); SRLZ(LFO3Sync); SRLZ(VCFEnabled); SRLZ(VCFType); @@ -1936,6 +1985,8 @@ SRLZ(SampleAttenuation); SRLZ(EG1Options); SRLZ(EG2Options); + SRLZ(SustainReleaseTrigger); + SRLZ(NoNoteOffReleaseTrigger); // derived attributes from DLS::Sampler SRLZ(FineTune); @@ -1975,8 +2026,8 @@ RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA); if (!_3ewa) { File* pFile = (File*) GetParent()->GetParent()->GetParent(); - bool version3 = pFile->pVersion && pFile->pVersion->major == 3; - _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140); + bool versiongt2 = pFile->pVersion && pFile->pVersion->major > 2; + _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, versiongt2 ? 148 : 140); } pData = (uint8_t*) _3ewa->LoadChunkData(); @@ -2243,25 +2294,28 @@ memcpy(&pData[140], DimensionUpperLimits, 8); } - // format extension for EG behavior options, these will *NOT* work with + // chunk for own format extensions, these will *NOT* work with // Gigasampler/GigaStudio ! RIFF::Chunk* lsde = pParentList->GetSubChunk(CHUNK_ID_LSDE); - if (!lsde) { - // only add this "LSDE" chunk if the EG options do not match the - // default EG behavior - eg_opt_t defaultOpt; - if (memcmp(&EG1Options, &defaultOpt, sizeof(eg_opt_t)) || - memcmp(&EG2Options, &defaultOpt, sizeof(eg_opt_t))) - { - lsde = pParentList->AddSubChunk(CHUNK_ID_LSDE, 2); - // move LSDE chunk to the end of parent list - pParentList->MoveSubChunk(lsde, (RIFF::Chunk*)NULL); - } + const int lsdeSize = + 3 /* EG cancel options */ + + 1 /* sustain pedal up on release trigger option */ + + 8 /* LFOs' wave forms */ + 12 /* LFOs' phase */ + 4 /* flags (LFO3FlipPhase) */; + if (!lsde && UsesAnyGigFormatExtension()) { + // only add this "LSDE" chunk if there is some (format extension) + // setting effective that would require our "LSDE" format extension + // chunk to be stored + lsde = pParentList->AddSubChunk(CHUNK_ID_LSDE, lsdeSize); + // move LSDE chunk to the end of parent list + pParentList->MoveSubChunk(lsde, (RIFF::Chunk*)NULL); } if (lsde) { + if (lsde->GetNewSize() < lsdeSize) + lsde->Resize(lsdeSize); + // format extension for EG behavior options unsigned char* pData = (unsigned char*) lsde->LoadChunkData(); eg_opt_t* pEGOpts[2] = { &EG1Options, &EG2Options }; - for (int i = 0; i < 2; ++i) { + for (int i = 0; i < 2; ++i) { // NOTE: we reserved the 3rd byte for a potential future EG3 option pData[i] = (pEGOpts[i]->AttackCancel ? 1 : 0) | (pEGOpts[i]->AttackHoldCancel ? (1<<1) : 0) | @@ -2269,9 +2323,54 @@ (pEGOpts[i]->Decay2Cancel ? (1<<3) : 0) | (pEGOpts[i]->ReleaseCancel ? (1<<4) : 0); } + // format extension for release trigger options + pData[3] = static_cast(SustainReleaseTrigger) | (NoNoteOffReleaseTrigger ? (1<<7) : 0); + // format extension for LFOs' wave form, phase displacement and for + // LFO3's flip phase + store16(&pData[4], LFO1WaveForm); + store16(&pData[6], LFO2WaveForm); + store16(&pData[8], LFO3WaveForm); + //NOTE: 16 bits reserved here for potential future use ! + const int32_t lfo1Phase = (int32_t) GIG_EXP_ENCODE(LFO1Phase); + const int32_t lfo2Phase = (int32_t) GIG_EXP_ENCODE(LFO2Phase); + const int32_t lfo3Phase = (int32_t) GIG_EXP_ENCODE(LFO3Phase); + store32(&pData[12], lfo1Phase); + store32(&pData[16], lfo2Phase); + store32(&pData[20], lfo3Phase); + const int32_t flags = LFO3FlipPhase ? 1 : 0; + store32(&pData[24], flags); + + // compile time sanity check: is our last store access here + // consistent with the initial lsdeSize value assignment? + static_assert(lsdeSize == 28, "Inconsistency in assumed 'LSDE' RIFF chunk size"); } } + /** + * Returns @c true in case this DimensionRegion object uses any gig format + * extension, that is whether this 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 + * format extension being used. Right now this method really just serves to + * answer the question whether an LSDE chunk is required, for the public API + * purpose this method would also need to check whether any other setting + * stored to the regular value '3ewa' chunk, is actually a format extension + * as well. + */ + bool DimensionRegion::UsesAnyGigFormatExtension() const { + eg_opt_t defaultOpt; + return memcmp(&EG1Options, &defaultOpt, sizeof(eg_opt_t)) || + memcmp(&EG2Options, &defaultOpt, sizeof(eg_opt_t)) || + SustainReleaseTrigger || NoNoteOffReleaseTrigger || + LFO1WaveForm || LFO2WaveForm || LFO3WaveForm || + LFO1Phase || LFO2Phase || LFO3Phase || + LFO3FlipPhase; + } + double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) { curve_type_t curveType = releaseVelocityResponseCurve; uint8_t depth = releaseVelocityResponseDepth; @@ -3208,7 +3307,7 @@ } Layers = 1; File* file = (File*) GetParent()->GetParent(); - int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5; + int dimensionBits = (file->pVersion && file->pVersion->major > 2) ? 8 : 5; // Actual Loading @@ -3218,6 +3317,8 @@ RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK); if (_3lnk) { + _3lnk->SetPos(0); + DimensionRegions = _3lnk->ReadUint32(); for (int i = 0; i < dimensionBits; i++) { dimension_t dimension = static_cast(_3lnk->ReadUint8()); @@ -3252,7 +3353,7 @@ UpdateVelocityTable(); // jump to start of the wave pool indices (if not already there) - if (file->pVersion && file->pVersion->major == 3) + if (file->pVersion && file->pVersion->major > 2) _3lnk->SetPos(68); // version 3 has a different 3lnk structure else _3lnk->SetPos(44); @@ -3311,14 +3412,14 @@ } File* pFile = (File*) GetParent()->GetParent(); - bool version3 = pFile->pVersion && pFile->pVersion->major == 3; - const int iMaxDimensions = version3 ? 8 : 5; - const int iMaxDimensionRegions = version3 ? 256 : 32; + const bool versiongt2 = pFile->pVersion && pFile->pVersion->major > 2; + const int iMaxDimensions = versiongt2 ? 8 : 5; + const int iMaxDimensionRegions = versiongt2 ? 256 : 32; // make sure '3lnk' chunk exists RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK); if (!_3lnk) { - const int _3lnkChunkSize = version3 ? 1092 : 172; + const int _3lnkChunkSize = versiongt2 ? 1092 : 172; _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize); memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize); @@ -3342,7 +3443,7 @@ } // update wave pool table in '3lnk' chunk - const int iWavePoolOffset = version3 ? 68 : 44; + const int iWavePoolOffset = versiongt2 ? 68 : 44; for (uint i = 0; i < iMaxDimensionRegions; i++) { int iWaveIndex = -1; if (i < DimensionRegions) { @@ -3358,6 +3459,39 @@ } store32(&pData[iWavePoolOffset + i * 4], iWaveIndex); } + + // 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); + + // add 3ddp chunk which always seems to have 16 bytes of 0xFF + RIFF::Chunk* _3ddp = pCkRegion->GetSubChunk(CHUNK_ID_3DDP); + if (!_3ddp) _3ddp = pCkRegion->AddSubChunk(CHUNK_ID_3DDP, 16); + uint8_t* pData = (uint8_t*) _3ddp->LoadChunkData(); + for (int i = 0; i < 16; i += 4) { + store32(&pData[i], 0xFFFFFFFF); + } + + // move 3dnm and 3ddp to the end of the region list + pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3DNM), (RIFF::Chunk*)NULL); + pCkRegion->MoveSubChunk(pCkRegion->GetSubChunk(CHUNK_ID_3DDP), (RIFF::Chunk*)NULL); + } else { + // this is intended for the user switching from GSt >= 3 version + // back to an older format version, delete GSt3 chunks ... + RIFF::List* _3dnm = pCkRegion->GetSubList(LIST_TYPE_3DNM); + if (_3dnm) pCkRegion->DeleteSubChunk(_3dnm); + + RIFF::Chunk* _3ddp = pCkRegion->GetSubChunk(CHUNK_ID_3DDP); + if (_3ddp) pCkRegion->DeleteSubChunk(_3ddp); + } } void Region::LoadDimensionRegions(RIFF::List* rgn) { @@ -3485,7 +3619,7 @@ // check if max. amount of dimensions reached File* file = (File*) GetParent()->GetParent(); - const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5; + const int iMaxDimensions = (file->pVersion && file->pVersion->major > 2) ? 8 : 5; if (Dimensions >= iMaxDimensions) throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached"); // check if max. amount of dimension bits reached @@ -3673,6 +3807,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"); @@ -3701,7 +3837,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? ... @@ -3712,6 +3848,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) @@ -3756,9 +3895,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; @@ -3777,6 +3930,7 @@ } // delete temporary region + tempRgn->DeleteChunks(); delete tempRgn; UpdateVelocityTable(); @@ -3797,6 +3951,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"); @@ -3823,7 +3979,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? ... @@ -3834,6 +3990,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) @@ -3895,9 +4054,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; @@ -3916,6 +4089,7 @@ } // delete temporary region + tempRgn->DeleteChunks(); delete tempRgn; UpdateVelocityTable(); @@ -4220,6 +4394,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 *************** // * @@ -4394,17 +4591,27 @@ pGroup = group; pChunk = ckScri; if (ckScri) { // object is loaded from file ... + ckScri->SetPos(0); + // read header uint32_t headerSize = ckScri->ReadUint32(); 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 @@ -4419,6 +4626,7 @@ Bypass = false; crc = 0; Name = "Unnamed Script"; + GenerateUuid(); } } @@ -4446,6 +4654,18 @@ memcpy(&data[0], &text[0], text.size()); } + /** @brief Remove all RIFF chunks associated with this Script object. + * + * At the moment Script::DeleteChunks() does nothing. It is + * recommended to call this method explicitly though from deriving classes's + * own overridden implementation of this method to avoid potential future + * compatiblity issues. + * + * See DLS::Storage::DeleteChunks() for details. + */ + void Script::DeleteChunks() { + } + /** * Apply this script to the respective RIFF chunks. You have to call * File::Save() to make changes persistent. @@ -4461,13 +4681,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); @@ -4483,11 +4704,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. * @@ -4561,6 +4808,18 @@ } } + /** @brief Remove all RIFF chunks associated with this ScriptGroup object. + * + * At the moment ScriptGroup::DeleteChunks() does nothing. It is + * recommended to call this method explicitly though from deriving classes's + * own overridden implementation of this method to avoid potential future + * compatiblity issues. + * + * See DLS::Storage::DeleteChunks() for details. + */ + void ScriptGroup::DeleteChunks() { + } + /** * Apply this script group to the respective RIFF chunks. You have to call * File::Save() to make changes persistent. @@ -4685,6 +4944,8 @@ if (lart) { RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG); if (_3ewg) { + _3ewg->SetPos(0); + EffectSend = _3ewg->ReadUint16(); Attenuation = _3ewg->ReadInt32(); FineTune = _3ewg->ReadInt16(); @@ -4729,7 +4990,8 @@ RIFF::List* rgn = lrgn->GetFirstSubList(); while (rgn) { if (rgn->GetListType() == LIST_TYPE_RGN) { - __notify_progress(pProgress, (float) pRegions->size() / (float) Regions); + if (pProgress) + __notify_progress(pProgress, (float) pRegions->size() / (float) Regions); pRegions->push_back(new Region(this, rgn)); } rgn = lrgn->GetNextSubList(); @@ -4742,8 +5004,11 @@ // 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); + int headerSize = ckSCSL->ReadUint32(); int slotCount = ckSCSL->ReadUint32(); if (slotCount) { @@ -4759,9 +5024,48 @@ } } } + + // 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); + } + } + } } - __notify_progress(pProgress, 1.0f); // notify done + if (pProgress) + __notify_progress(pProgress, 1.0f); // notify done } void Instrument::UpdateRegionKeyTable() { @@ -4817,7 +5121,7 @@ File* pFile = (File*) GetParent(); // 3ewg is bigger in gig3, as it includes the iMIDI rules - int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12; + int size = (pFile->pVersion && pFile->pVersion->major > 2) ? 16416 : 12; _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size); memset(_3ewg->LoadChunkData(), 0, size); } @@ -4849,6 +5153,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); @@ -4873,6 +5179,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); @@ -5297,6 +5675,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. @@ -5331,7 +5968,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++) { @@ -5358,6 +6000,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 *************** // * @@ -5374,9 +6042,23 @@ ::LoadString(pNameChunk, Name); } + /** @brief Destructor. + * + * Currently this destructor implementation does nothing. + */ Group::~Group() { - // remove the chunk associated with this group (if any) - if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk); + } + + /** @brief Remove all RIFF chunks associated with this Group object. + * + * See DLS::Storage::DeleteChunks() for details. + */ + void Group::DeleteChunks() { + // handle own RIFF chunks + if (pNameChunk) { + pNameChunk->GetParent()->DeleteSubChunk(pNameChunk); + pNameChunk = NULL; + } } /** @brief Update chunks with current group settings. @@ -5399,7 +6081,7 @@ RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL); if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL); - if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) { + 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()) { if (strcmp(static_cast(ck->LoadChunkData()), "") == 0) { @@ -5494,6 +6176,11 @@ 0, 3, 20030331 & 0xffff, 20030331 >> 16 }; + /// Reflects Gigasampler file format version 4.0 (2007-10-12). + const DLS::version_t File::VERSION_4 = { + 0, 4, 20071012 & 0xffff, 20071012 >> 16 + }; + static const DLS::Info::string_length_t _FileFixedStringLengths[] = { { CHUNK_ID_IARL, 256 }, { CHUNK_ID_IART, 128 }, @@ -5642,6 +6329,7 @@ if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample"); if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation pSamples->erase(iter); + pSample->DeleteChunks(); delete pSample; SampleList::iterator tmp = SamplesIterator; @@ -5679,50 +6367,103 @@ int iSampleIndex = 0; int iTotalSamples = WavePoolCount; - // check if samples should be loaded from extension files - // (only for old gig files < 2 GB) - int lastFileNo = 0; - if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) { - for (int i = 0 ; i < WavePoolCount ; i++) { - if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i]; - } - } - String name(pRIFF->GetFileName()); - int nameLen = (int) name.length(); - char suffix[6]; - if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4; - - for (int fileNo = 0 ; ; ) { + // just for assembling path of optional extension files to be read + const std::string folder = parentPath(pRIFF->GetFileName()); + const std::string baseName = pathWithoutExtension(pRIFF->GetFileName()); + + // the main gig file and the extension files (.gx01, ... , .gx98) may + // contain wave data (wave pool) + std::vector poolFiles; + poolFiles.push_back(pRIFF); + + // get info about all extension files + RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL); + if (ckXfil) { // there are extension files (.gx01, ... , .gx98) ... + const uint32_t n = ckXfil->ReadInt32(); + for (int i = 0; i < n; i++) { + // read the filename and load the extension file + std::string name; + ckXfil->ReadString(name, 128); + std::string path = concatPath(folder, name); + RIFF::File* pExtFile = new RIFF::File(path); + // check that the dlsids match + RIFF::Chunk* ckDLSID = pExtFile->GetSubChunk(CHUNK_ID_DLID); + if (ckDLSID) { + ::DLS::dlsid_t idExpected; + idExpected.ulData1 = ckXfil->ReadInt32(); + idExpected.usData2 = ckXfil->ReadInt16(); + idExpected.usData3 = ckXfil->ReadInt16(); + ckXfil->Read(idExpected.abData, 8, 1); + ::DLS::dlsid_t idFound; + ckDLSID->Read(&idFound.ulData1, 1, 4); + ckDLSID->Read(&idFound.usData2, 1, 2); + ckDLSID->Read(&idFound.usData3, 1, 2); + ckDLSID->Read(idFound.abData, 8, 1); + if (memcmp(&idExpected, &idFound, 16) != 0) + throw gig::Exception("dlsid mismatch for extension file: %s", path.c_str()); + } + poolFiles.push_back(pExtFile); + ExtensionFiles.push_back(pExtFile); + } + } + + // check if a .gx99 (GigaPulse) file exists + RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF); + if (ckDoxf) { // there is a .gx99 (GigaPulse) file ... + std::string path = baseName + ".gx99"; + RIFF::File* pExtFile = new RIFF::File(path); + + // skip unused int and filename + ckDoxf->SetPos(132, RIFF::stream_curpos); + + // check that the dlsids match + RIFF::Chunk* ckDLSID = pExtFile->GetSubChunk(CHUNK_ID_DLID); + if (ckDLSID) { + ::DLS::dlsid_t idExpected; + idExpected.ulData1 = ckDoxf->ReadInt32(); + idExpected.usData2 = ckDoxf->ReadInt16(); + idExpected.usData3 = ckDoxf->ReadInt16(); + ckDoxf->Read(idExpected.abData, 8, 1); + ::DLS::dlsid_t idFound; + ckDLSID->Read(&idFound.ulData1, 1, 4); + ckDLSID->Read(&idFound.usData2, 1, 2); + ckDLSID->Read(&idFound.usData3, 1, 2); + ckDLSID->Read(idFound.abData, 8, 1); + if (memcmp(&idExpected, &idFound, 16) != 0) + throw gig::Exception("dlsid mismatch for GigaPulse file: %s", path.c_str()); + } + poolFiles.push_back(pExtFile); + ExtensionFiles.push_back(pExtFile); + } + + // load samples from extension files (if required) + for (int i = 0; i < poolFiles.size(); i++) { + RIFF::File* file = poolFiles[i]; RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL); if (wvpl) { - file_offset_t wvplFileOffset = wvpl->GetFilePos(); + file_offset_t wvplFileOffset = wvpl->GetFilePos() - + wvpl->GetPos(); // should be zero, but just to be sure RIFF::List* wave = wvpl->GetFirstSubList(); while (wave) { if (wave->GetListType() == LIST_TYPE_WAVE) { // notify current progress - const float subprogress = (float) iSampleIndex / (float) iTotalSamples; - __notify_progress(pProgress, subprogress); + if (pProgress) { + const float subprogress = (float) iSampleIndex / (float) iTotalSamples; + __notify_progress(pProgress, subprogress); + } file_offset_t waveFileOffset = wave->GetFilePos(); - pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex)); + pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, i, iSampleIndex)); iSampleIndex++; } wave = wvpl->GetNextSubList(); } - - if (fileNo == lastFileNo) break; - - // open extension file (*.gx01, *.gx02, ...) - fileNo++; - sprintf(suffix, ".gx%02d", fileNo); - name.replace(nameLen, 5, suffix); - file = new RIFF::File(name); - ExtensionFiles.push_back(file); - } else break; + } } - __notify_progress(pProgress, 1.0); // notify done + if (pProgress) + __notify_progress(pProgress, 1.0); // notify done } Instrument* File::GetFirstInstrument() { @@ -5763,22 +6504,31 @@ if (!pInstruments) { // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM) - // sample loading subtask - progress_t subprogress; - __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask - __notify_progress(&subprogress, 0.0f); - if (GetAutoLoad()) - GetFirstSample(&subprogress); // now force all samples to be loaded - __notify_progress(&subprogress, 1.0f); - - // instrument loading subtask - if (pProgress && pProgress->callback) { - subprogress.__range_min = subprogress.__range_max; - subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask - } - __notify_progress(&subprogress, 0.0f); - LoadInstruments(&subprogress); - __notify_progress(&subprogress, 1.0f); + if (pProgress) { + // sample loading subtask + progress_t subprogress; + __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask + __notify_progress(&subprogress, 0.0f); + if (GetAutoLoad()) + GetFirstSample(&subprogress); // now force all samples to be loaded + __notify_progress(&subprogress, 1.0f); + + // instrument loading subtask + if (pProgress->callback) { + subprogress.__range_min = subprogress.__range_max; + subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask + } + __notify_progress(&subprogress, 0.0f); + LoadInstruments(&subprogress); + __notify_progress(&subprogress, 1.0f); + } else { + // sample loading subtask + if (GetAutoLoad()) + GetFirstSample(); // now force all samples to be loaded + + // instrument loading subtask + LoadInstruments(); + } } if (!pInstruments) return NULL; InstrumentsIterator = pInstruments->begin(); @@ -5927,6 +6677,7 @@ InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument); if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument"); pInstruments->erase(iter); + pInstrument->DeleteChunks(); delete pInstrument; } @@ -5942,21 +6693,26 @@ RIFF::List* lstInstr = lstInstruments->GetFirstSubList(); while (lstInstr) { if (lstInstr->GetListType() == LIST_TYPE_INS) { - // notify current progress - const float localProgress = (float) iInstrumentIndex / (float) Instruments; - __notify_progress(pProgress, localProgress); - - // divide local progress into subprogress for loading current Instrument - progress_t subprogress; - __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex); + if (pProgress) { + // notify current progress + const float localProgress = (float) iInstrumentIndex / (float) Instruments; + __notify_progress(pProgress, localProgress); - pInstruments->push_back(new Instrument(this, lstInstr, &subprogress)); + // divide local progress into subprogress for loading current Instrument + progress_t subprogress; + __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex); + + pInstruments->push_back(new Instrument(this, lstInstr, &subprogress)); + } else { + pInstruments->push_back(new Instrument(this, lstInstr)); + } iInstrumentIndex++; } lstInstr = lstInstruments->GetNextSubList(); } - __notify_progress(pProgress, 1.0); // notify done + if (pProgress) + __notify_progress(pProgress, 1.0); // notify done } } @@ -6071,7 +6827,7 @@ _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8); // the order of einf and 3crc is not the same in v2 and v3 RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF); - if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf); + if (einf && pVersion && pVersion->major > 2) pRIFF->MoveSubChunk(_3crc, einf); bRequiresSave = true; } else if (_3crc->GetNewSize() != pSamples->size() * 8) { _3crc->Resize(pSamples->size() * 8); @@ -6186,6 +6942,7 @@ } // now delete this group object pGroups->erase(iter); + pGroup->DeleteChunks(); delete pGroup; } @@ -6207,6 +6964,7 @@ // move all members of this group to another group pGroup->MoveAll(); pGroups->erase(iter); + pGroup->DeleteChunks(); delete pGroup; } @@ -6220,7 +6978,7 @@ RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk(); while (ck) { if (ck->GetChunkID() == CHUNK_ID_3GNM) { - if (pVersion && pVersion->major == 3 && + if (pVersion && pVersion->major > 2 && strcmp(static_cast(ck->LoadChunkData()), "") == 0) break; pGroups->push_back(new Group(this, ck)); @@ -6306,6 +7064,7 @@ pScriptGroup->DeleteScript(pScriptGroup->GetScript(i)); if (pScriptGroup->pList) pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList); + pScriptGroup->DeleteChunks(); delete pScriptGroup; } @@ -6396,10 +7155,12 @@ // v3: make sure the file has 128 3gnm chunks // (before updating the Group chunks) - if (pVersion && pVersion->major == 3) { + if (pVersion && pVersion->major > 2) { RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk(); for (int i = 0 ; i < 128 ; i++) { - if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64); + // 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(); } } @@ -6542,7 +7303,7 @@ } else /*if (newFile)*/ { _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8); // the order of einf and 3crc is not the same in v2 and v3 - if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf); + if (einf && pVersion && pVersion->major > 2) pRIFF->MoveSubChunk(_3crc, einf); } { // must be performed in RAM here ... uint32_t* pData = (uint32_t*) _3crc->LoadChunkData(); @@ -6569,8 +7330,8 @@ } /** - * Enable / disable automatic loading. By default this properyt is - * enabled and all informations are loaded automatically. However + * Enable / disable automatic loading. By default this property is + * enabled and every information is loaded automatically. However * loading all Regions, DimensionRegions and especially samples might * take a long time for large .gig files, and sometimes one might only * be interested in retrieving very superficial informations like the @@ -6578,10 +7339,10 @@ * automatic loading to avoid very slow response times. * * @e CAUTION: by disabling this property many pointers (i.e. sample - * references) and informations will have invalid or even undefined + * references) and attributes will have invalid or even undefined * data! This feature is currently only intended for retrieving very - * superficial informations in a very fast way. Don't use it to retrieve - * details like synthesis informations or even to modify .gig files! + * superficial information in a very fast way. Don't use it to retrieve + * details like synthesis information or even to modify .gig files! */ void File::SetAutoLoad(bool b) { bAutoLoad = b; @@ -6595,6 +7356,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 ***************