--- linuxsampler/trunk/src/engines/gig/InstrumentResourceManager.cpp 2007/05/29 23:59:36 1212 +++ linuxsampler/trunk/src/engines/gig/InstrumentResourceManager.cpp 2008/02/03 16:21:38 1662 @@ -3,7 +3,7 @@ * LinuxSampler - modular, streaming capable sampler * * * * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck * - * Copyright (C) 2005 - 2007 Christian Schoenebeck * + * Copyright (C) 2005 - 2008 Christian Schoenebeck * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * @@ -25,7 +25,8 @@ #include "InstrumentResourceManager.h" -#include "../InstrumentEditorFactory.h" +#include "../../common/global_private.h" +#include "../../plugins/InstrumentEditorFactory.h" // We need to know the maximum number of sample points which are going to // be processed for each render cycle of the audio output driver, to know @@ -66,6 +67,8 @@ // the instrument we borrowed on behalf of the editor ::gig::Instrument* pInstrument; + // the instrument editor we work on behalf + InstrumentEditor* pEditor; }; /** @@ -106,17 +109,76 @@ return res; } - String InstrumentResourceManager::GetInstrumentTypeName(instrument_id_t ID) { + String InstrumentResourceManager::GetInstrumentDataStructureName(instrument_id_t ID) { return ::gig::libraryName(); } - String InstrumentResourceManager::GetInstrumentTypeVersion(instrument_id_t ID) { + String InstrumentResourceManager::GetInstrumentDataStructureVersion(instrument_id_t ID) { return ::gig::libraryVersion(); } + std::vector InstrumentResourceManager::GetInstrumentFileContent(String File) throw (InstrumentManagerException) { + ::RIFF::File* riff = NULL; + ::gig::File* gig = NULL; + try { + std::vector result; + riff = new ::RIFF::File(File); + gig = new ::gig::File(riff); + gig->SetAutoLoad(false); // avoid time consuming samples scanning + for (int i = 0; gig->GetInstrument(i); i++) { + instrument_id_t id; + id.FileName = File; + id.Index = i; + result.push_back(id); + } + if (gig) delete gig; + if (riff) delete riff; + return result; + } catch (::RIFF::Exception e) { + if (gig) delete gig; + if (riff) delete riff; + throw InstrumentManagerException(e.Message); + } catch (...) { + if (gig) delete gig; + if (riff) delete riff; + throw InstrumentManagerException("Unknown exception while trying to parse '" + File + "'"); + } + } + + InstrumentResourceManager::instrument_info_t InstrumentResourceManager::GetInstrumentInfo(instrument_id_t ID) throw (InstrumentManagerException) { + std::vector result; + ::RIFF::File* riff = NULL; + ::gig::File* gig = NULL; + try { + riff = new ::RIFF::File(ID.FileName); + gig = new ::gig::File(riff); + gig->SetAutoLoad(false); // avoid time consuming samples scanning + ::gig::Instrument* pInstrument = gig->GetInstrument(ID.Index); + if (!pInstrument) throw InstrumentManagerException("There is no instrument " + ToString(ID.Index) + " in " + ID.FileName); + instrument_info_t info; + if (gig->pVersion) { + info.FormatVersion = ToString(gig->pVersion->major); + info.Product = gig->pInfo->Product; + info.Artists = gig->pInfo->Artists; + } + info.InstrumentName = pInstrument->pInfo->Name; + if (gig) delete gig; + if (riff) delete riff; + return info; + } catch (::RIFF::Exception e) { + if (gig) delete gig; + if (riff) delete riff; + throw InstrumentManagerException(e.Message); + } catch (...) { + if (gig) delete gig; + if (riff) delete riff; + throw InstrumentManagerException("Unknown exception while trying to parse '" + ID.FileName + "'"); + } + } + void InstrumentResourceManager::LaunchInstrumentEditor(instrument_id_t ID) throw (InstrumentManagerException) { - const String sDataType = GetInstrumentTypeName(ID); - const String sDataVersion = GetInstrumentTypeVersion(ID); + const String sDataType = GetInstrumentDataStructureName(ID); + const String sDataVersion = GetInstrumentDataStructureVersion(ID); // find instrument editors capable to handle given instrument std::vector vEditors = InstrumentEditorFactory::MatchingEditors(sDataType, sDataVersion); @@ -128,7 +190,7 @@ dmsg(1,("Found matching editor '%s' for instrument ('%s', %d) having data structure ('%s','%s')\n", vEditors[0].c_str(), ID.FileName.c_str(), ID.Index, sDataType.c_str(), sDataVersion.c_str())); InstrumentEditor* pEditor = InstrumentEditorFactory::Create(vEditors[0]); - // we want to know when you'll die X| (see OnInstrumentEditorQuit()) + // register for receiving notifications from the instrument editor pEditor->AddListener(this); // create a proxy that reacts on notification on behalf of the editor InstrumentEditorProxy* pProxy = new InstrumentEditorProxy; @@ -136,11 +198,28 @@ ::gig::Instrument* pInstrument = Borrow(ID, pProxy); // remember the proxy and instrument for this instrument editor pProxy->pInstrument = pInstrument; + pProxy->pEditor = pEditor; InstrumentEditorProxiesMutex.Lock(); - InstrumentEditorProxies[pEditor] = pProxy; + InstrumentEditorProxies.add(pProxy); InstrumentEditorProxiesMutex.Unlock(); // launch the instrument editor for the given instrument pEditor->Launch(pInstrument, sDataType, sDataVersion); + + // register the instrument editor as virtual MIDI device as well ... + VirtualMidiDevice* pVirtualMidiDevice = + dynamic_cast(pEditor); + if (!pVirtualMidiDevice) { + std::cerr << "Instrument editor not a virtual MIDI device\n" << std::flush; + return; + } + // NOTE: for now connect the virtual MIDI keyboard of the instrument editor (if any) with all engine channels that have the same instrument as the editor was opened for ( other ideas ? ) + Lock(); + std::set engineChannels = + GetEngineChannelsUsing(pInstrument, false/*don't lock again*/); + std::set::iterator iter = engineChannels.begin(); + std::set::iterator end = engineChannels.end(); + for (; iter != end; ++iter) (*iter)->Connect(pVirtualMidiDevice); + Unlock(); } /** @@ -152,27 +231,255 @@ */ void InstrumentResourceManager::OnInstrumentEditorQuit(InstrumentEditor* pSender) { dmsg(1,("InstrumentResourceManager: instrument editor quit, doing cleanup\n")); - // hand back instrument and free proxy + + ::gig::Instrument* pInstrument = NULL; + InstrumentEditorProxy* pProxy = NULL; + int iProxyIndex = -1; + + // first find the editor proxy entry for this editor InstrumentEditorProxiesMutex.Lock(); - if (InstrumentEditorProxies.count(pSender)) { - InstrumentEditorProxy* pProxy = + for (int i = 0; i < InstrumentEditorProxies.size(); i++) { + InstrumentEditorProxy* pCurProxy = dynamic_cast( - InstrumentEditorProxies[pSender] + InstrumentEditorProxies[i] ); - InstrumentEditorProxies.erase(pSender); - InstrumentEditorProxiesMutex.Unlock(); - HandBack(pProxy->pInstrument, pProxy); - if (pProxy) delete pProxy; + if (pCurProxy->pEditor == pSender) { + pProxy = pCurProxy; + iProxyIndex = i; + pInstrument = pCurProxy->pInstrument; + } + } + InstrumentEditorProxiesMutex.Unlock(); + + if (!pProxy) { + std::cerr << "Eeeek, could not find instrument editor proxy, " + "this is a bug!\n" << std::flush; + return; + } + + // now unregister editor as not being available as a virtual MIDI device anymore + VirtualMidiDevice* pVirtualMidiDevice = + dynamic_cast(pSender); + if (pVirtualMidiDevice) { + Lock(); + // NOTE: see note in LaunchInstrumentEditor() + std::set engineChannels = + GetEngineChannelsUsing(pInstrument, false/*don't lock again*/); + std::set::iterator iter = engineChannels.begin(); + std::set::iterator end = engineChannels.end(); + for (; iter != end; ++iter) (*iter)->Disconnect(pVirtualMidiDevice); + Unlock(); } else { + std::cerr << "Could not unregister editor as not longer acting as " + "virtual MIDI device. Wasn't it registered?\n" + << std::flush; + } + + // finally delete proxy entry and hand back instrument + if (pInstrument) { + InstrumentEditorProxiesMutex.Lock(); + InstrumentEditorProxies.remove(iProxyIndex); InstrumentEditorProxiesMutex.Unlock(); - std::cerr << "Eeeek, could not find instrument editor proxy, this is a bug!\n" << std::flush; + + HandBack(pInstrument, pProxy); + delete pProxy; + } + + // Note that we don't need to free the editor here. As it + // derives from Thread, it will delete itself when the thread + // dies. + } + +#if 0 // currently unused : + /** + * Try to inform the respective instrument editor(s), that a note on + * event just occured. This method is called by the MIDI thread. If any + * obstacles are in the way (e.g. if a wait for an unlock would be + * required) we give up immediately, since the RT safeness of the MIDI + * thread has absolute priority. + */ + void InstrumentResourceManager::TrySendNoteOnToEditors(uint8_t Key, uint8_t Velocity, ::gig::Instrument* pInstrument) { + const bool bGotLock = InstrumentEditorProxiesMutex.Trylock(); // naively assumes RT safe implementation + if (!bGotLock) return; // hell, forget it, not worth the hassle + for (int i = 0; i < InstrumentEditorProxies.size(); i++) { + InstrumentEditorProxy* pProxy = + dynamic_cast( + InstrumentEditorProxies[i] + ); + if (pProxy->pInstrument == pInstrument) + pProxy->pEditor->SendNoteOnToDevice(Key, Velocity); + } + InstrumentEditorProxiesMutex.Unlock(); // naively assumes RT safe implementation + } + + /** + * Try to inform the respective instrument editor(s), that a note off + * event just occured. This method is called by the MIDI thread. If any + * obstacles are in the way (e.g. if a wait for an unlock would be + * required) we give up immediately, since the RT safeness of the MIDI + * thread has absolute priority. + */ + void InstrumentResourceManager::TrySendNoteOffToEditors(uint8_t Key, uint8_t Velocity, ::gig::Instrument* pInstrument) { + const bool bGotLock = InstrumentEditorProxiesMutex.Trylock(); // naively assumes RT safe implementation + if (!bGotLock) return; // hell, forget it, not worth the hassle + for (int i = 0; i < InstrumentEditorProxies.size(); i++) { + InstrumentEditorProxy* pProxy = + dynamic_cast( + InstrumentEditorProxies[i] + ); + if (pProxy->pInstrument == pInstrument) + pProxy->pEditor->SendNoteOffToDevice(Key, Velocity); + } + InstrumentEditorProxiesMutex.Unlock(); // naively assumes RT safe implementation + } +#endif // unused + + void InstrumentResourceManager::OnSamplesToBeRemoved(std::set Samples, InstrumentEditor* pSender) { + if (Samples.empty()) { + std::cerr << "gig::InstrumentResourceManager: WARNING, " + "OnSamplesToBeRemoved() called with empty list, this " + "is a bug!\n" << std::flush; + return; + } + // TODO: ATM we assume here that all samples are from the same file + ::gig::Sample* pFirstSample = (::gig::Sample*) *Samples.begin(); + ::gig::File* pCriticalFile = dynamic_cast< ::gig::File*>(pFirstSample->GetParent()); + // completely suspend all engines that use that same file + SuspendEnginesUsing(pCriticalFile); + } + + void InstrumentResourceManager::OnSamplesRemoved(InstrumentEditor* pSender) { + // resume all previously, completely suspended engines + // (we don't have to un-cache the removed samples here, since that is + // automatically done by the gig::Sample destructor) + ResumeAllEngines(); + } + + void InstrumentResourceManager::OnDataStructureToBeChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) { + //TODO: remove code duplication + if (sStructType == "gig::File") { + // completely suspend all engines that use that file + ::gig::File* pFile = (::gig::File*) pStruct; + SuspendEnginesUsing(pFile); + } else if (sStructType == "gig::Instrument") { + // completely suspend all engines that use that instrument + ::gig::Instrument* pInstrument = (::gig::Instrument*) pStruct; + SuspendEnginesUsing(pInstrument); + } else if (sStructType == "gig::Region") { + // only advice the engines to suspend the given region, so they'll + // only ignore that region (and probably already other suspended + // ones), but beside that continue normal playback + ::gig::Region* pRegion = (::gig::Region*) pStruct; + ::gig::Instrument* pInstrument = + (::gig::Instrument*) pRegion->GetParent(); + Lock(); + std::set engines = + GetEnginesUsing(pInstrument, false/*don't lock again*/); + std::set::iterator iter = engines.begin(); + std::set::iterator end = engines.end(); + for (; iter != end; ++iter) (*iter)->Suspend(pRegion); + Unlock(); + } else if (sStructType == "gig::DimensionRegion") { + // only advice the engines to suspend the given DimensionRegions's + // parent region, so they'll only ignore that region (and probably + // already other suspended ones), but beside that continue normal + // playback + ::gig::DimensionRegion* pDimReg = + (::gig::DimensionRegion*) pStruct; + ::gig::Region* pRegion = pDimReg->GetParent(); + ::gig::Instrument* pInstrument = + (::gig::Instrument*) pRegion->GetParent(); + Lock(); + std::set engines = + GetEnginesUsing(pInstrument, false/*don't lock again*/); + std::set::iterator iter = engines.begin(); + std::set::iterator end = engines.end(); + for (; iter != end; ++iter) (*iter)->Suspend(pRegion); + Unlock(); + } else { + std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data " + "structure '" << sStructType << "' requested to be " + "suspended by instrument editor. This is a bug!\n" + << std::flush; + //TODO: we should inform the instrument editor that something seriously went wrong + } + } + + void InstrumentResourceManager::OnDataStructureChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) { + //TODO: remove code duplication + if (sStructType == "gig::File") { + // resume all previously suspended engines + ResumeAllEngines(); + } else if (sStructType == "gig::Instrument") { + // resume all previously suspended engines + ResumeAllEngines(); + } else if (sStructType == "gig::Region") { + // advice the engines to resume the given region, that is to + // using it for playback again + ::gig::Region* pRegion = (::gig::Region*) pStruct; + ::gig::Instrument* pInstrument = + (::gig::Instrument*) pRegion->GetParent(); + Lock(); + std::set engines = + GetEnginesUsing(pInstrument, false/*don't lock again*/); + std::set::iterator iter = engines.begin(); + std::set::iterator end = engines.end(); + for (; iter != end; ++iter) (*iter)->Resume(pRegion); + Unlock(); + } else if (sStructType == "gig::DimensionRegion") { + // advice the engines to resume the given DimensionRegion's parent + // region, that is to using it for playback again + ::gig::DimensionRegion* pDimReg = + (::gig::DimensionRegion*) pStruct; + ::gig::Region* pRegion = pDimReg->GetParent(); + ::gig::Instrument* pInstrument = + (::gig::Instrument*) pRegion->GetParent(); + Lock(); + std::set engines = + GetEnginesUsing(pInstrument, false/*don't lock again*/); + std::set::iterator iter = engines.begin(); + std::set::iterator end = engines.end(); + for (; iter != end; ++iter) (*iter)->Resume(pRegion); + Unlock(); + } else { + std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data " + "structure '" << sStructType << "' requested to be " + "resumed by instrument editor. This is a bug!\n" + << std::flush; + //TODO: we should inform the instrument editor that something seriously went wrong + } + } + + void InstrumentResourceManager::OnSampleReferenceChanged(void* pOldSample, void* pNewSample, InstrumentEditor* pSender) { + // uncache old sample in case it's not used by anybody anymore + if (pOldSample) { + Lock(); + ::gig::Sample* pSample = (::gig::Sample*) pOldSample; + ::gig::File* pFile = (::gig::File*) pSample->GetParent(); + std::vector< ::gig::Instrument*> instruments = + GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/); + for (int i = 0; i < instruments.size(); i++) + if (!SampleReferencedByInstrument(pSample, instruments[i])) + UncacheInitialSamples(pSample); + Unlock(); + } + // make sure new sample reference is cached + if (pNewSample) { + Lock(); + ::gig::Sample* pSample = (::gig::Sample*) pNewSample; + ::gig::File* pFile = (::gig::File*) pSample->GetParent(); + // get all engines that use that same gig::File + std::set engines = GetEnginesUsing(pFile, false/*don't lock again*/); + std::set::iterator iter = engines.begin(); + std::set::iterator end = engines.end(); + for (; iter != end; ++iter) + CacheInitialSamples(pSample, *iter); + Unlock(); } - // free the editor - InstrumentEditorFactory::Destroy(pSender); } ::gig::Instrument* InstrumentResourceManager::Create(instrument_id_t Key, InstrumentConsumer* pConsumer, void*& pArg) { - // get gig file from inernal gig file manager + // get gig file from internal gig file manager ::gig::File* pGig = Gigs.Borrow(Key.FileName, (GigConsumer*) Key.Index); // conversion kinda hackish :/ // we pass this to the progress callback mechanism of libgig @@ -257,15 +564,15 @@ * Give back an instrument. This should be used instead of * HandBack if there are some dimension regions that are still in * use. (When an instrument is changed, the voices currently - * playing is allowed to keep playing with the old instrument + * playing are allowed to keep playing with the old instrument * until note off arrives. New notes will use the new instrument.) */ void InstrumentResourceManager::HandBackInstrument(::gig::Instrument* pResource, InstrumentConsumer* pConsumer, - ::gig::DimensionRegion** dimRegionsInUse) { + RTList< ::gig::DimensionRegion*>* pDimRegionsInUse) { DimRegInfoMutex.Lock(); - for (int i = 0 ; dimRegionsInUse[i] ; i++) { - DimRegInfo[dimRegionsInUse[i]].refCount++; - SampleRefCount[dimRegionsInUse[i]->pSample]++; + for (RTList< ::gig::DimensionRegion*>::Iterator i = pDimRegionsInUse->first() ; i != pDimRegionsInUse->end() ; i++) { + DimRegInfo[*i].refCount++; + SampleRefCount[(*i)->pSample]++; } HandBack(pResource, pConsumer, true); DimRegInfoMutex.Unlock(); @@ -304,15 +611,32 @@ } /** + * Just a wrapper around the other @c CacheInitialSamples() method. + * + * @param pSample - points to the sample to be cached + * @param pEngine - pointer to Gig Engine Channel which caused this call + * (may be NULL, in this case default amount of samples + * will be cached) + */ + void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::EngineChannel* pEngineChannel) { + gig::Engine* pEngine = + (pEngineChannel && pEngineChannel->GetEngine()) ? + dynamic_cast(pEngineChannel->GetEngine()) : NULL; + CacheInitialSamples(pSample, pEngine); + } + + /** * Caches a certain size at the beginning of the given sample in RAM. If the * sample is very short, the whole sample will be loaded into RAM and thus * no disk streaming is needed for this sample. Caching an initial part of * samples is needed to compensate disk reading latency. * * @param pSample - points to the sample to be cached - * @param pEngineChannel - pointer to Gig Engine Channel which caused this call + * @param pEngine - pointer to Gig Engine which caused this call + * (may be NULL, in this case default amount of samples + * will be cached) */ - void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::EngineChannel* pEngineChannel) { + void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::Engine* pEngine) { if (!pSample) { dmsg(4,("gig::InstrumentResourceManager: Skipping sample (pSample == NULL)\n")); return; @@ -326,8 +650,8 @@ // border, to allow the interpolator do it's work even at the end of // the sample. const uint maxSamplesPerCycle = - (pEngineChannel && pEngineChannel->GetEngine()) ? dynamic_cast(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle() - : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE; + (pEngine) ? pEngine->pAudioOutputDevice->MaxSamplesPerCycle() + : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE; const uint neededSilenceSamples = (maxSamplesPerCycle << CONFIG_MAX_PITCH) + 3; const uint currentlyCachedSilenceSamples = pSample->GetCache().NullExtensionSize / pSample->FrameSize; if (currentlyCachedSilenceSamples < neededSilenceSamples) { @@ -343,6 +667,204 @@ if (!pSample->GetCache().Size) std::cerr << "Unable to cache sample - maybe memory full!" << std::endl << std::flush; } + void InstrumentResourceManager::UncacheInitialSamples(::gig::Sample* pSample) { + dmsg(1,("Uncaching sample %x\n",pSample)); + if (pSample->GetCache().Size) pSample->ReleaseSampleData(); + } + + /** + * Returns a list with all instruments currently in use, that are part of + * the given file. + * + * @param pFile - search criteria + * @param bLock - whether we should lock (mutex) the instrument manager + * during this call and unlock at the end of this call + */ + std::vector< ::gig::Instrument*> InstrumentResourceManager::GetInstrumentsCurrentlyUsedOf(::gig::File* pFile, bool bLock) { + if (bLock) Lock(); + std::vector< ::gig::Instrument*> result; + std::vector< ::gig::Instrument*> allInstruments = Resources(false/*don't lock again*/); + for (int i = 0; i < allInstruments.size(); i++) + if ( + (::gig::File*) allInstruments[i]->GetParent() + == pFile + ) result.push_back(allInstruments[i]); + if (bLock) Unlock(); + return result; + } + + /** + * Returns a list with all gig engine channels that are currently using + * the given instrument. + * + * @param pInstrument - search criteria + * @param bLock - whether we should lock (mutex) the instrument manager + * during this call and unlock at the end of this call + */ + std::set InstrumentResourceManager::GetEngineChannelsUsing(::gig::Instrument* pInstrument, bool bLock) { + if (bLock) Lock(); + std::set result; + std::set*> consumers = ConsumersOf(pInstrument); + std::set*>::iterator iter = consumers.begin(); + std::set*>::iterator end = consumers.end(); + for (; iter != end; ++iter) { + gig::EngineChannel* pEngineChannel = dynamic_cast(*iter); + if (!pEngineChannel) continue; + result.insert(pEngineChannel); + } + if (bLock) Unlock(); + return result; + } + + /** + * Returns a list with all gig Engines that are currently using the given + * instrument. + * + * @param pInstrument - search criteria + * @param bLock - whether we should lock (mutex) the instrument manager + * during this call and unlock at the end of this call + */ + std::set InstrumentResourceManager::GetEnginesUsing(::gig::Instrument* pInstrument, bool bLock) { + if (bLock) Lock(); + std::set result; + std::set*> consumers = ConsumersOf(pInstrument); + std::set*>::iterator iter = consumers.begin(); + std::set*>::iterator end = consumers.end(); + for (; iter != end; ++iter) { + gig::EngineChannel* pEngineChannel = dynamic_cast(*iter); + if (!pEngineChannel) continue; + gig::Engine* pEngine = dynamic_cast(pEngineChannel->GetEngine()); + if (!pEngine) continue; + result.insert(pEngine); + } + if (bLock) Unlock(); + return result; + } + + /** + * Returns a list with all gig Engines that are currently using an + * instrument that is part of the given instrument file. + * + * @param pFile - search criteria + * @param bLock - whether we should lock (mutex) the instrument manager + * during this call and unlock at the end of this call + */ + std::set InstrumentResourceManager::GetEnginesUsing(::gig::File* pFile, bool bLock) { + if (bLock) Lock(); + // get all instruments (currently in usage) that use that same gig::File + std::vector< ::gig::Instrument*> instrumentsOfInterest = + GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/); + + // get all engines that use that same gig::File + std::set result; + { + for (int i = 0; i < instrumentsOfInterest.size(); i++) { + std::set*> consumers = ConsumersOf(instrumentsOfInterest[i]); + std::set*>::iterator iter = consumers.begin(); + std::set*>::iterator end = consumers.end(); + for (; iter != end; ++iter) { + gig::EngineChannel* pEngineChannel = dynamic_cast(*iter); + if (!pEngineChannel) continue; + gig::Engine* pEngine = dynamic_cast(pEngineChannel->GetEngine()); + if (!pEngine) continue; + // the unique, sorted container std::set makes + // sure we won't have duplicates + result.insert(pEngine); + } + } + } + if (bLock) Unlock(); + return result; + } + + /** + * Returns @c true in case the given sample is referenced somewhere by the + * given instrument, @c false otherwise. + * + * @param pSample - sample reference + * @param pInstrument - instrument that might use that sample + */ + bool InstrumentResourceManager::SampleReferencedByInstrument(::gig::Sample* pSample, ::gig::Instrument* pInstrument) { + for ( + ::gig::Region* pRegion = pInstrument->GetFirstRegion(); + pRegion; pRegion = pInstrument->GetNextRegion() + ) { + for ( + int i = 0; i < pRegion->DimensionRegions && + pRegion->pDimensionRegions[i]; i++ + ) { + if (pRegion->pDimensionRegions[i]->pSample == pSample) + return true; + } + } + return false; + } + + /** + * Suspend all gig engines that use the given instrument. This means + * completely stopping playback on those engines and killing all their + * voices and disk streams. This method will block until all voices AND + * their disk streams are finally deleted and the engine turned into a + * complete idle loop. + * + * All @c SuspendEnginesUsing() methods only serve one thread by one and + * block all other threads until the current active thread called + * @c ResumeAllEngines() . + * + * @param pInstrument - search criteria + */ + void InstrumentResourceManager::SuspendEnginesUsing(::gig::Instrument* pInstrument) { + // make sure no other thread suspends whole engines at the same time + suspendedEnginesMutex.Lock(); + // get all engines that use that same gig::Instrument + suspendedEngines = GetEnginesUsing(pInstrument, true/*lock*/); + // finally, completely suspend all engines that use that same gig::Instrument + std::set::iterator iter = suspendedEngines.begin(); + std::set::iterator end = suspendedEngines.end(); + for (; iter != end; ++iter) (*iter)->SuspendAll(); + } + + /** + * Suspend all gig engines that use the given instrument file. This means + * completely stopping playback on those engines and killing all their + * voices and disk streams. This method will block until all voices AND + * their disk streams are finally deleted and the engine turned into a + * complete idle loop. + * + * All @c SuspendEnginesUsing() methods only serve one thread by one and + * block all other threads until the current active thread called + * @c ResumeAllEngines() . + * + * @param pFile - search criteria + */ + void InstrumentResourceManager::SuspendEnginesUsing(::gig::File* pFile) { + // make sure no other thread suspends whole engines at the same time + suspendedEnginesMutex.Lock(); + // get all engines that use that same gig::File + suspendedEngines = GetEnginesUsing(pFile, true/*lock*/); + // finally, completely suspend all engines that use that same gig::File + std::set::iterator iter = suspendedEngines.begin(); + std::set::iterator end = suspendedEngines.end(); + for (; iter != end; ++iter) (*iter)->SuspendAll(); + } + + /** + * MUST be called after one called one of the @c SuspendEnginesUsing() + * methods, to resume normal playback on all previously suspended engines. + * As it's only possible for one thread to suspend whole engines at the + * same time, this method doesn't take any arguments. + */ + void InstrumentResourceManager::ResumeAllEngines() { + // resume all previously completely suspended engines + std::set::iterator iter = suspendedEngines.begin(); + std::set::iterator end = suspendedEngines.end(); + for (; iter != end; ++iter) (*iter)->ResumeAll(); + // no more suspended engines ... + suspendedEngines.clear(); + // allow another thread to suspend whole engines + suspendedEnginesMutex.Unlock(); + } + // internal gig file manager