--- libgig/trunk/src/gig.cpp 2017/07/23 18:18:30 3327 +++ libgig/trunk/src/gig.cpp 2021/06/19 09:07:16 3951 @@ -2,7 +2,7 @@ * * * libgig - C++ cross-platform Gigasampler format file access library * * * - * Copyright (C) 2003-2017 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(); @@ -476,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; } @@ -603,8 +609,8 @@ uint16_t iSampleGroup = 0; // 0 refers to default sample group File* pFile = static_cast(pParent); if (pFile->pGroups) { - std::list::iterator iter = pFile->pGroups->begin(); - std::list::iterator end = pFile->pGroups->end(); + std::vector::iterator iter = pFile->pGroups->begin(); + std::vector::iterator end = pFile->pGroups->end(); for (int i = 0; iter != end; i++, iter++) { if (*iter == pGroup) { iSampleGroup = i; @@ -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; @@ -2309,6 +2408,33 @@ // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) { + // sanity check input parameters + // (fallback to some default parameters on ill input) + switch (curveType) { + case curve_type_nonlinear: + case curve_type_linear: + if (depth > 4) { + printf("Warning: Invalid depth (0x%x) for velocity curve type (0x%x).\n", depth, curveType); + depth = 0; + scaling = 0; + } + break; + case curve_type_special: + if (depth > 5) { + printf("Warning: Invalid depth (0x%x) for velocity curve type 'special'.\n", depth); + depth = 0; + scaling = 0; + } + break; + case curve_type_unknown: + default: + printf("Warning: Unknown velocity curve type (0x%x).\n", curveType); + curveType = curve_type_linear; + depth = 0; + scaling = 0; + break; + } + double* table; uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling; if (pVelocityTables->count(tableKey)) { // if key exists @@ -3181,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 @@ -3191,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()); @@ -3225,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); @@ -3234,7 +3362,8 @@ if (file->GetAutoLoad()) { for (uint i = 0; i < DimensionRegions; i++) { uint32_t wavepoolindex = _3lnk->ReadUint32(); - if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex); + if (file->pWavePoolTable && pDimensionRegions[i]) + pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex); } GetSample(); // load global region sample reference } @@ -3283,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); @@ -3314,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) { @@ -3330,19 +3459,53 @@ } 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) { 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."); } @@ -3457,7 +3620,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 @@ -3645,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"); @@ -3673,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? ... @@ -3684,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) @@ -3728,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; @@ -3749,6 +3931,7 @@ } // delete temporary region + tempRgn->DeleteChunks(); delete tempRgn; UpdateVelocityTable(); @@ -3769,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"); @@ -3795,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? ... @@ -3806,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) @@ -3867,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; @@ -3888,6 +4090,7 @@ } // delete temporary region + tempRgn->DeleteChunks(); delete tempRgn; UpdateVelocityTable(); @@ -4115,27 +4318,30 @@ if ((int32_t)WavePoolTableIndex == -1) return NULL; File* file = (File*) GetParent()->GetParent(); if (!file->pWavePoolTable) return NULL; + if (WavePoolTableIndex + 1 > file->WavePoolCount) return NULL; // for new files or files >= 2 GB use 64 bit wave pool offsets if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) { // use 64 bit wave pool offsets (treating this as large file) uint64_t soughtoffset = uint64_t(file->pWavePoolTable[WavePoolTableIndex]) | uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32; - Sample* sample = file->GetFirstSample(pProgress); - while (sample) { + size_t i = 0; + for (Sample* sample = file->GetSample(i, pProgress); sample; + sample = file->GetSample(++i)) + { if (sample->ullWavePoolOffset == soughtoffset) - return static_cast(sample); - sample = file->GetNextSample(); + return sample; } } else { // use extension files and 32 bit wave pool offsets file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex]; file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex]; - Sample* sample = file->GetFirstSample(pProgress); - while (sample) { + size_t i = 0; + for (Sample* sample = file->GetSample(i, pProgress); sample; + sample = file->GetSample(++i)) + { if (sample->ullWavePoolOffset == soughtoffset && - sample->FileNo == soughtfileno) return static_cast(sample); - sample = file->GetNextSample(); + sample->FileNo == soughtfileno) return sample; } } return NULL; @@ -4191,6 +4397,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 *************** // * @@ -4365,17 +4594,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 @@ -4390,6 +4629,7 @@ Bypass = false; crc = 0; Name = "Unnamed Script"; + GenerateUuid(); } } @@ -4417,6 +4657,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. @@ -4432,13 +4684,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); @@ -4454,11 +4707,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. * @@ -4522,8 +4801,8 @@ ScriptGroup::~ScriptGroup() { if (pScripts) { - std::list::iterator iter = pScripts->begin(); - std::list::iterator end = pScripts->end(); + std::vector::iterator iter = pScripts->begin(); + std::vector::iterator end = pScripts->end(); while (iter != end) { delete *iter; ++iter; @@ -4532,6 +4811,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. @@ -4549,7 +4840,7 @@ // now store the name of this group as chunk as subchunk of the list chunk ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64); - for (std::list::iterator it = pScripts->begin(); + for (std::vector::iterator it = pScripts->begin(); it != pScripts->end(); ++it) { (*it)->UpdateChunks(pProgress); @@ -4564,12 +4855,10 @@ * @param index - number of the sought script (0..n) * @returns sought script or NULL if there's no such script */ - Script* ScriptGroup::GetScript(uint index) { + Script* ScriptGroup::GetScript(size_t index) { if (!pScripts) LoadScripts(); - std::list::iterator it = pScripts->begin(); - for (uint i = 0; it != pScripts->end(); ++i, ++it) - if (i == index) return *it; - return NULL; + if (index >= pScripts->size()) return NULL; + return (*pScripts)[index]; } /** @brief Add new instrument script. @@ -4602,7 +4891,7 @@ */ void ScriptGroup::DeleteScript(Script* pScript) { if (!pScripts) LoadScripts(); - std::list::iterator iter = + std::vector::iterator iter = find(pScripts->begin(), pScripts->end(), pScript); if (iter == pScripts->end()) throw gig::Exception("Could not delete script, could not find given script"); @@ -4615,11 +4904,12 @@ void ScriptGroup::LoadScripts() { if (pScripts) return; - pScripts = new std::list; + pScripts = new std::vector; 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)); @@ -4656,6 +4946,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(); @@ -4697,13 +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) { - __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(); } // Creating Region Key Table for fast lookup UpdateRegionKeyTable(); @@ -4713,8 +5007,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) { @@ -4730,9 +5027,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() { @@ -4741,7 +5077,9 @@ RegionList::iterator end = pRegions->end(); for (; iter != end; ++iter) { gig::Region* pRegion = static_cast(*iter); - for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) { + const int low = std::max(int(pRegion->KeyRange.low), 0); + const int high = std::min(int(pRegion->KeyRange.high), 127); + for (int iKey = low; iKey <= high; iKey++) { RegionKeyTable[iKey] = pRegion; } } @@ -4786,7 +5124,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); } @@ -4818,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); @@ -4842,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); @@ -4889,11 +5301,28 @@ } /** + * Returns Region at supplied @a pos position within the region list of + * this instrument. If supplied @a pos is out of bounds then @c NULL is + * returned. + * + * @param pos - position of sought Region in region list + * @returns pointer address to requested region or @c NULL if @a pos is + * out of bounds + */ + Region* Instrument::GetRegionAt(size_t pos) { + if (!pRegions) return NULL; + if (pos >= pRegions->size()) return NULL; + return static_cast( (*pRegions)[pos] ); + } + + /** * Returns the first Region of the instrument. You have to call this * method once before you use GetNextRegion(). * * @returns pointer address to first region or NULL if there is none * @see GetNextRegion() + * @deprecated This method is not reentrant-safe, use GetRegionAt() + * instead. */ Region* Instrument::GetFirstRegion() { if (!pRegions) return NULL; @@ -4908,6 +5337,8 @@ * * @returns pointer address to the next region or NULL if end reached * @see GetFirstRegion() + * @deprecated This method is not reentrant-safe, use GetRegionAt() + * instead. */ Region* Instrument::GetNextRegion() { if (!pRegions) return NULL; @@ -4961,7 +5392,8 @@ * @param dst - destination instrument at which this instrument will be * moved to, or pass NULL for moving to end of list * @throw gig::Exception if this instrument and target instrument are not - * part of the same file + * part of the same file, as well as on unexpected + * internal error */ void Instrument::MoveTo(Instrument* dst) { if (dst && GetParent() != dst->GetParent()) @@ -4978,11 +5410,17 @@ File::InstrumentList::iterator itFrom = std::find(list.begin(), list.end(), static_cast(this)); + if (itFrom == list.end()) + throw Exception( + "gig::Instrument::MoveTo(): unexpected missing membership " + "of this instrument." + ); + list.erase(itFrom); File::InstrumentList::iterator itTo = std::find(list.begin(), list.end(), static_cast(dst)); - list.splice(itTo, list, itFrom); + list.insert(itTo, this); } // move the instrument's actual list RIFF chunk appropriately @@ -5063,7 +5501,7 @@ File* pFile = (File*) GetParent(); for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) { uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset; - for (uint i = 0; pFile->GetScriptGroup(i); ++i) { + for (size_t i = 0; pFile->GetScriptGroup(i); ++i) { ScriptGroup* group = pFile->GetScriptGroup(i); for (uint s = 0; group->GetScript(s); ++s) { Script* script = group->GetScript(s); @@ -5266,6 +5704,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. @@ -5300,7 +5997,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++) { @@ -5310,7 +6012,7 @@ pMidiRules[0] = NULL; // delete all old regions - while (Regions) DeleteRegion(GetFirstRegion()); + while (Regions) DeleteRegion(GetRegionAt(0)); // create new regions and copy them from original { RegionList::const_iterator it = orig->pRegions->begin(); @@ -5327,6 +6029,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 *************** // * @@ -5340,12 +6068,27 @@ Group::Group(File* file, RIFF::Chunk* ck3gnm) { pFile = file; pNameChunk = ck3gnm; + SamplesIterator = 0; ::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. @@ -5368,9 +6111,10 @@ 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()) { + 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; @@ -5383,6 +6127,26 @@ } /** + * Returns Sample object at @a index of this sample group. + * + * @param index - position of sample in this sample group's sample list + * (0..n) + * @returns sample object or NULL if index is out of bounds + */ + Sample* Group::GetSample(size_t index) { + if (pFile->pSamples && index >= pFile->pSamples->size()) return NULL; + size_t indexInFile = 0; + size_t indexInGroup = 0; + for (Sample* pSample = pFile->GetSample(indexInFile); pSample; + pSample = pFile->GetSample(++indexInFile)) + { + if (pSample->GetGroup() != this) continue; + if (indexInGroup++ == index) return pSample; + } + return NULL; + } + + /** * Returns the first Sample of this Group. You have to call this method * once before you use GetNextSample(). * @@ -5392,11 +6156,17 @@ * @returns pointer address to first Sample or NULL if there is none * applied to this Group * @see GetNextSample() + * @deprecated This method is not reentrant-safe, use GetSample() + * instead. */ Sample* Group::GetFirstSample() { - // FIXME: lazy und unsafe implementation, should be an autonomous iterator - for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) { - if (pSample->GetGroup() == this) return pSample; + size_t& i = this->SamplesIterator; + i = 0; + for (Sample* pSample = pFile->GetSample(i); pSample; + pSample = pFile->GetSample(++i)) + { + if (pSample->GetGroup() == this) + return pSample; } return NULL; } @@ -5410,11 +6180,16 @@ * @returns pointer address to the next Sample of this Group or NULL if * end reached * @see GetFirstSample() + * @deprecated This method is not reentrant-safe, use GetSample() + * instead. */ Sample* Group::GetNextSample() { - // FIXME: lazy und unsafe implementation, should be an autonomous iterator - for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) { - if (pSample->GetGroup() == this) return pSample; + size_t& i = this->SamplesIterator; + for (Sample* pSample = pFile->GetSample(++i); pSample; + pSample = pFile->GetSample(++i)) + { + if (pSample->GetGroup() == this) + return pSample; } return NULL; } @@ -5434,8 +6209,11 @@ */ void Group::MoveAll() { // get "that" other group first + size_t i = 0; Group* pOtherGroup = NULL; - for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) { + for (pOtherGroup = pFile->GetGroup(i); pOtherGroup; + pOtherGroup = pFile->GetGroup(++i)) + { if (pOtherGroup != this) break; } if (!pOtherGroup) throw Exception( @@ -5443,7 +6221,8 @@ "other Group. This is a bug, report it!" ); // now move all samples of this group to the other group - for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) { + Sample* pSample; + while ((pSample = GetSample(0))) { pOtherGroup->AddSample(pSample); } } @@ -5463,6 +6242,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 }, @@ -5510,8 +6294,8 @@ File::~File() { if (pGroups) { - std::list::iterator iter = pGroups->begin(); - std::list::iterator end = pGroups->end(); + std::vector::iterator iter = pGroups->begin(); + std::vector::iterator end = pGroups->end(); while (iter != end) { delete *iter; ++iter; @@ -5519,8 +6303,8 @@ delete pGroups; } if (pScriptGroups) { - std::list::iterator iter = pScriptGroups->begin(); - std::list::iterator end = pScriptGroups->end(); + std::vector::iterator iter = pScriptGroups->begin(); + std::vector::iterator end = pScriptGroups->end(); while (iter != end) { delete *iter; ++iter; @@ -5529,6 +6313,14 @@ } } + /** + * Returns a pointer to the first Sample object of the file, + * NULL otherwise. + * + * @param pProgress - optional: callback function for progress notification + * @deprecated This method is not reentrant-safe, use GetSample() + * instead. + */ Sample* File::GetFirstSample(progress_t* pProgress) { if (!pSamples) LoadSamples(pProgress); if (!pSamples) return NULL; @@ -5536,6 +6328,13 @@ return static_cast( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL ); } + /** + * Returns a pointer to the next Sample object of the file, + * NULL otherwise. + * + * @deprecated This method is not reentrant-safe, use GetSample() + * instead. + */ Sample* File::GetNextSample() { if (!pSamples) return NULL; SamplesIterator++; @@ -5545,18 +6344,29 @@ /** * Returns Sample object of @a index. * + * @param index - position of sample in sample list (0..n) + * @param pProgress - optional: callback function for progress notification * @returns sample object or NULL if index is out of bounds */ - Sample* File::GetSample(uint index) { - if (!pSamples) LoadSamples(); + Sample* File::GetSample(size_t index, progress_t* pProgress) { + if (!pSamples) LoadSamples(pProgress); if (!pSamples) return NULL; - DLS::File::SampleList::iterator it = pSamples->begin(); - for (int i = 0; i < index; ++i) { - ++it; - if (it == pSamples->end()) return NULL; - } - if (it == pSamples->end()) return NULL; - return static_cast( *it ); + if (index >= pSamples->size()) return NULL; + return static_cast( (*pSamples)[index] ); + } + + /** + * Returns the total amount of samples of this gig file. + * + * Note that this method might block for a long time in case it is required + * to load the sample info for the first time. + * + * @returns total amount of samples + */ + size_t File::CountSamples() { + if (!pSamples) LoadSamples(); + if (!pSamples) return 0; + return pSamples->size(); } /** @brief Add a new sample. @@ -5597,15 +6407,18 @@ 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; // remove all references to the sample - for (Instrument* instrument = GetFirstInstrument() ; instrument ; - instrument = GetNextInstrument()) { - for (Region* region = instrument->GetFirstRegion() ; region ; - region = instrument->GetNextRegion()) { - + size_t iIns = 0; + for (Instrument* instrument = GetInstrument(iIns); instrument; + instrument = GetInstrument(++iIns)) + { + size_t iRgn = 0; + for (Region* region = instrument->GetRegionAt(iRgn); region; + region = instrument->GetRegionAt(++iRgn)) + { if (region->GetSample() == pSample) region->SetSample(NULL); for (int i = 0 ; i < region->DimensionRegions ; i++) { @@ -5614,7 +6427,6 @@ } } } - SamplesIterator = tmp; // restore iterator } void File::LoadSamples() { @@ -5628,58 +6440,117 @@ if (!pSamples) pSamples = new SampleList; - RIFF::File* file = pRIFF; - // just for progress calculation 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(); - RIFF::List* wave = wvpl->GetFirstSubList(); - while (wave) { + file_offset_t wvplFileOffset = wvpl->GetFilePos() - + wvpl->GetPos(); // should be zero, but just to be sure + 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 - 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 } + /** + * Returns a pointer to the first Instrument object of the file, + * NULL otherwise. + * + * @deprecated This method is not reentrant-safe, use GetInstrument() + * instead. + */ Instrument* File::GetFirstInstrument() { if (!pInstruments) LoadInstruments(); if (!pInstruments) return NULL; @@ -5687,6 +6558,13 @@ return static_cast( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL ); } + /** + * Returns a pointer to the next Instrument object of the file, + * NULL otherwise. + * + * @deprecated This method is not reentrant-safe, use GetInstrument() + * instead. + */ Instrument* File::GetNextInstrument() { if (!pInstruments) return NULL; InstrumentsIterator++; @@ -5694,40 +6572,59 @@ } /** + * Returns the total amount of instruments of this gig file. + * + * Note that this method might block for a long time in case it is required + * to load the instruments info for the first time. + * + * @returns total amount of instruments + */ + size_t File::CountInstruments() { + if (!pInstruments) LoadInstruments(); + if (!pInstruments) return 0; + return pInstruments->size(); + } + + /** * Returns the instrument with the given index. * * @param index - number of the sought instrument (0..n) * @param pProgress - optional: callback function for progress notification * @returns sought instrument or NULL if there's no such instrument */ - Instrument* File::GetInstrument(uint index, progress_t* pProgress) { + Instrument* File::GetInstrument(size_t index, progress_t* pProgress) { 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()) + GetSample(0, &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()) + GetSample(0); // now force all samples to be loaded + + // instrument loading subtask + LoadInstruments(); + } } if (!pInstruments) return NULL; - InstrumentsIterator = pInstruments->begin(); - for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) { - if (i == index) return static_cast( *InstrumentsIterator ); - InstrumentsIterator++; - } - return NULL; + if (index >= pInstruments->size()) return NULL; + return static_cast( (*pInstruments)[index] ); } /** @brief Add a new instrument definition. @@ -5814,7 +6711,7 @@ } // clone script groups and their scripts - for (int iGroup = 0; pFile->GetScriptGroup(iGroup); ++iGroup) { + for (size_t iGroup = 0; pFile->GetScriptGroup(iGroup); ++iGroup) { ScriptGroup* sg = pFile->GetScriptGroup(iGroup); ScriptGroup* dg = AddScriptGroup(); dg->Name = "COPY" + ToString(iCallCount) + "_" + sg->Name; @@ -5868,6 +6765,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; } @@ -5880,24 +6778,30 @@ 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) { - // 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 } } @@ -5948,7 +6852,7 @@ } int File::GetWaveTableIndexOf(gig::Sample* pSample) { - if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned + if (!pSamples) GetSample(0); // make sure sample chunks were scanned File::SampleList::iterator iter = pSamples->begin(); File::SampleList::iterator end = pSamples->end(); for (int index = 0; iter != end; ++iter, ++index) @@ -5968,7 +6872,7 @@ if (!_3crc) return false; if (_3crc->GetNewSize() <= 0) return false; if (_3crc->GetNewSize() % 8) return false; - if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned + if (!pSamples) GetSample(0); // make sure sample chunks were scanned if (_3crc->GetNewSize() != pSamples->size() * 8) return false; const file_offset_t n = _3crc->GetNewSize() / 8; @@ -6002,7 +6906,7 @@ */ bool File::RebuildSampleChecksumTable() { // make sure sample chunks were scanned - if (!pSamples) GetFirstSample(); + if (!pSamples) GetSample(0); bool bRequiresSave = false; @@ -6012,7 +6916,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); @@ -6051,6 +6955,12 @@ return bRequiresSave; } + /** + * Returns a pointer to the first Group object of the file, + * NULL otherwise. + * + * @deprecated This method is not reentrant-safe, use GetGroup() instead. + */ Group* File::GetFirstGroup() { if (!pGroups) LoadGroups(); // there must always be at least one group @@ -6058,6 +6968,12 @@ return *GroupsIterator; } + /** + * Returns a pointer to the next Group object of the file, + * NULL otherwise. + * + * @deprecated This method is not reentrant-safe, use GetGroup() instead. + */ Group* File::GetNextGroup() { if (!pGroups) return NULL; ++GroupsIterator; @@ -6070,14 +6986,10 @@ * @param index - number of the sought group (0..n) * @returns sought group or NULL if there's no such group */ - Group* File::GetGroup(uint index) { + Group* File::GetGroup(size_t index) { if (!pGroups) LoadGroups(); - GroupsIterator = pGroups->begin(); - for (uint i = 0; GroupsIterator != pGroups->end(); i++) { - if (i == index) return *GroupsIterator; - ++GroupsIterator; - } - return NULL; + if (index >= pGroups->size()) return NULL; + return (*pGroups)[index]; } /** @@ -6092,9 +7004,9 @@ */ Group* File::GetGroup(String name) { if (!pGroups) LoadGroups(); - GroupsIterator = pGroups->begin(); - for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i) - if ((*GroupsIterator)->Name == name) return *GroupsIterator; + size_t i = 0; + for (Group* pGroup = GetGroup(i); pGroup; pGroup = GetGroup(++i)) + if (pGroup->Name == name) return pGroup; return NULL; } @@ -6118,15 +7030,18 @@ */ void File::DeleteGroup(Group* pGroup) { if (!pGroups) LoadGroups(); - std::list::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup); + std::vector::iterator iter = + find(pGroups->begin(), pGroups->end(), pGroup); if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group"); if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!"); // delete all members of this group - for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) { + Sample* pSample; + while ((pSample = pGroup->GetSample(0))) { DeleteSample(pSample); } // now delete this group object pGroups->erase(iter); + pGroup->DeleteChunks(); delete pGroup; } @@ -6142,31 +7057,34 @@ */ void File::DeleteGroupOnly(Group* pGroup) { if (!pGroups) LoadGroups(); - std::list::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup); + std::vector::iterator iter = + find(pGroups->begin(), pGroups->end(), pGroup); if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group"); if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!"); // move all members of this group to another group pGroup->MoveAll(); pGroups->erase(iter); + pGroup->DeleteChunks(); delete pGroup; } void File::LoadGroups() { - if (!pGroups) pGroups = new std::list; + if (!pGroups) pGroups = new std::vector; // try to read defined groups from file RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI); 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 == 3 && + if (pVersion && pVersion->major > 2 && strcmp(static_cast(ck->LoadChunkData()), "") == 0) break; pGroups->push_back(new Group(this, ck)); } - ck = lst3gnl->GetNextSubChunk(); } } } @@ -6185,12 +7103,10 @@ * @param index - number of the sought group (0..n) * @returns sought script group or NULL if there's no such group */ - ScriptGroup* File::GetScriptGroup(uint index) { + ScriptGroup* File::GetScriptGroup(size_t index) { if (!pScriptGroups) LoadScriptGroups(); - std::list::iterator it = pScriptGroups->begin(); - for (uint i = 0; it != pScriptGroups->end(); ++i, ++it) - if (i == index) return *it; - return NULL; + if (index >= pScriptGroups->size()) return NULL; + return (*pScriptGroups)[index]; } /** @brief Get instrument script group (by name). @@ -6203,9 +7119,10 @@ */ ScriptGroup* File::GetScriptGroup(const String& name) { if (!pScriptGroups) LoadScriptGroups(); - std::list::iterator it = pScriptGroups->begin(); - for (uint i = 0; it != pScriptGroups->end(); ++i, ++it) - if ((*it)->Name == name) return *it; + for (size_t i = 0; i < pScriptGroups->size(); ++i) { + ScriptGroup* pGroup = (*pScriptGroups)[i]; + if (pGroup->Name == name) return pGroup; + } return NULL; } @@ -6238,7 +7155,7 @@ */ void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) { if (!pScriptGroups) LoadScriptGroups(); - std::list::iterator iter = + std::vector::iterator iter = find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup); if (iter == pScriptGroups->end()) throw gig::Exception("Could not delete script group, could not find given script group"); @@ -6247,16 +7164,18 @@ pScriptGroup->DeleteScript(pScriptGroup->GetScript(i)); if (pScriptGroup->pList) pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList); + pScriptGroup->DeleteChunks(); delete pScriptGroup; } void File::LoadScriptGroups() { if (pScriptGroups) return; - pScriptGroups = new std::list; + pScriptGroups = new std::vector; 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)); @@ -6296,7 +7215,7 @@ // of the respective instrument script chunk as reference. if (pScriptGroups) { // Update instrument script (group) chunks. - for (std::list::iterator it = pScriptGroups->begin(); + for (std::vector::iterator it = pScriptGroups->begin(); it != pScriptGroups->end(); ++it) { (*it)->UpdateChunks(pProgress); @@ -6317,7 +7236,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); } @@ -6337,16 +7256,19 @@ // v3: make sure the file has 128 3gnm chunks // (before updating the Group chunks) - if (pVersion && pVersion->major == 3) { - RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk(); - for (int i = 0 ; i < 128 ; i++) { - if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64); - if (_3gnm) _3gnm = _3gnl->GetNextSubChunk(); + if (pVersion && pVersion->major > 2) { + 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); } } - std::list::iterator iter = pGroups->begin(); - std::list::iterator end = pGroups->end(); + std::vector::iterator iter = pGroups->begin(); + std::vector::iterator end = pGroups->end(); for (; iter != end; ++iter) { (*iter)->UpdateChunks(pProgress); } @@ -6384,9 +7306,11 @@ uint8_t* pData = (uint8_t*) einf->LoadChunkData(); std::map sampleMap; - int sampleIdx = 0; - for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) { - sampleMap[pSample] = sampleIdx++; + size_t sampleIdx = 0; + for (Sample* pSample = GetSample(0); pSample; + pSample = GetSample(++sampleIdx)) + { + sampleMap[pSample] = sampleIdx; } int totnbusedsamples = 0; @@ -6398,8 +7322,10 @@ memset(&pData[48], 0, sublen - 48); - for (Instrument* instrument = GetFirstInstrument() ; instrument ; - instrument = GetNextInstrument()) { + size_t iIns = 0; + for (Instrument* instrument = GetInstrument(iIns); instrument; + instrument = GetInstrument(++iIns)) + { int nbusedsamples = 0; int nbusedchannels = 0; int nbdimregions = 0; @@ -6407,8 +7333,10 @@ memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48); - for (Region* region = instrument->GetFirstRegion() ; region ; - region = instrument->GetNextRegion()) { + size_t iRgn = 0; + for (Region* region = instrument->GetRegionAt(iRgn); region; + region = instrument->GetRegionAt(++iRgn)) + { for (int i = 0 ; i < region->DimensionRegions ; i++) { gig::DimensionRegion *d = region->pDimensionRegions[i]; if (d->pSample) { @@ -6483,7 +7411,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(); @@ -6502,16 +7430,17 @@ void File::UpdateFileOffsets() { DLS::File::UpdateFileOffsets(); - for (Instrument* instrument = GetFirstInstrument(); instrument; - instrument = GetNextInstrument()) + size_t i = 0; + for (Instrument* instrument = GetInstrument(i); instrument; + instrument = GetInstrument(++i)) { instrument->UpdateScriptFileOffsets(); } } /** - * 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 @@ -6519,10 +7448,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; @@ -6536,6 +7465,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 ***************