/[svn]/linuxsampler/trunk/src/engines/gig/InstrumentResourceManager.cpp
ViewVC logotype

Annotation of /linuxsampler/trunk/src/engines/gig/InstrumentResourceManager.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1455 - (hide annotations) (download)
Sun Oct 21 11:59:59 2007 UTC (16 years, 5 months ago) by persson
File size: 36782 byte(s)
* bugfix: the thread used by an editor plugin didn't die when the
  editor closed

1 schoenebeck 53 /***************************************************************************
2     * *
3     * LinuxSampler - modular, streaming capable sampler *
4     * *
5 schoenebeck 56 * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck *
6 schoenebeck 1212 * Copyright (C) 2005 - 2007 Christian Schoenebeck *
7 schoenebeck 53 * *
8     * This program is free software; you can redistribute it and/or modify *
9     * it under the terms of the GNU General Public License as published by *
10     * the Free Software Foundation; either version 2 of the License, or *
11     * (at your option) any later version. *
12     * *
13     * This program is distributed in the hope that it will be useful, *
14     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16     * GNU General Public License for more details. *
17     * *
18     * You should have received a copy of the GNU General Public License *
19     * along with this program; if not, write to the Free Software *
20     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
21     * MA 02111-1307 USA *
22     ***************************************************************************/
23    
24     #include <sstream>
25    
26     #include "InstrumentResourceManager.h"
27    
28 schoenebeck 1424 #include "../../common/global_private.h"
29 schoenebeck 1375 #include "../../plugins/InstrumentEditorFactory.h"
30 schoenebeck 1212
31 schoenebeck 411 // We need to know the maximum number of sample points which are going to
32     // be processed for each render cycle of the audio output driver, to know
33     // how much initial sample points we need to cache into RAM. If the given
34     // sampler channel does not have an audio output device assigned yet
35     // though, we simply use this default value.
36     #define GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE 128
37    
38 schoenebeck 53 namespace LinuxSampler { namespace gig {
39    
40 schoenebeck 947 // data stored as long as an instrument resource exists
41     struct instr_entry_t {
42     InstrumentManager::instrument_id_t ID;
43     ::gig::File* pGig;
44     uint MaxSamplesPerCycle; ///< if some engine requests an already allocated instrument with a higher value, we have to reallocate the instrument
45     };
46    
47 schoenebeck 517 // some data needed for the libgig callback function
48     struct progress_callback_arg_t {
49 schoenebeck 947 InstrumentResourceManager* pManager;
50     InstrumentManager::instrument_id_t* pInstrumentKey;
51 schoenebeck 517 };
52    
53 schoenebeck 1212 // we use this to react on events concerning an instrument on behalf of an instrument editor
54     class InstrumentEditorProxy : public InstrumentConsumer {
55     public:
56     virtual void ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {
57     //TODO: inform the instrument editor about the pending update
58     }
59    
60     virtual void ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {
61     //TODO:: inform the instrument editor about finished update
62     }
63    
64     virtual void OnResourceProgress(float fProgress) {
65     //TODO: inform the instrument editor about the progress of an update
66     }
67    
68     // the instrument we borrowed on behalf of the editor
69     ::gig::Instrument* pInstrument;
70     };
71    
72 schoenebeck 517 /**
73     * Callback function which will be called by libgig during loading of
74     * instruments to inform about the current progress. Or to be more
75     * specific; it will be called during the GetInstrument() call.
76     *
77     * @param pProgress - contains current progress value, pointer to the
78     * InstrumentResourceManager instance and
79     * instrument ID
80     */
81     void InstrumentResourceManager::OnInstrumentLoadingProgress(::gig::progress_t* pProgress) {
82     dmsg(7,("gig::InstrumentResourceManager: progress %f%", pProgress->factor));
83     progress_callback_arg_t* pArg = static_cast<progress_callback_arg_t*>(pProgress->custom);
84     // we randomly schedule 90% for the .gig file loading and the remaining 10% later for sample caching
85     const float localProgress = 0.9f * pProgress->factor;
86     pArg->pManager->DispatchResourceProgressEvent(*pArg->pInstrumentKey, localProgress);
87     }
88    
89 schoenebeck 947 std::vector<InstrumentResourceManager::instrument_id_t> InstrumentResourceManager::Instruments() {
90     return Entries();
91     }
92    
93     InstrumentManager::mode_t InstrumentResourceManager::GetMode(const instrument_id_t& ID) {
94     return static_cast<InstrumentManager::mode_t>(AvailabilityMode(ID));
95     }
96    
97     void InstrumentResourceManager::SetMode(const instrument_id_t& ID, InstrumentManager::mode_t Mode) {
98     dmsg(2,("gig::InstrumentResourceManager: setting mode for %s (Index=%d) to %d\n",ID.FileName.c_str(),ID.Index,Mode));
99     SetAvailabilityMode(ID, static_cast<ResourceManager<InstrumentManager::instrument_id_t, ::gig::Instrument>::mode_t>(Mode));
100     }
101    
102     String InstrumentResourceManager::GetInstrumentName(instrument_id_t ID) {
103 schoenebeck 970 Lock();
104     ::gig::Instrument* pInstrument = Resource(ID, false);
105     String res = (pInstrument) ? pInstrument->pInfo->Name : "";
106     Unlock();
107     return res;
108 schoenebeck 947 }
109    
110 schoenebeck 1321 String InstrumentResourceManager::GetInstrumentDataStructureName(instrument_id_t ID) {
111 schoenebeck 1212 return ::gig::libraryName();
112     }
113    
114 schoenebeck 1321 String InstrumentResourceManager::GetInstrumentDataStructureVersion(instrument_id_t ID) {
115 schoenebeck 1212 return ::gig::libraryVersion();
116     }
117    
118     void InstrumentResourceManager::LaunchInstrumentEditor(instrument_id_t ID) throw (InstrumentManagerException) {
119 schoenebeck 1321 const String sDataType = GetInstrumentDataStructureName(ID);
120     const String sDataVersion = GetInstrumentDataStructureVersion(ID);
121 schoenebeck 1212 // find instrument editors capable to handle given instrument
122     std::vector<String> vEditors =
123     InstrumentEditorFactory::MatchingEditors(sDataType, sDataVersion);
124     if (!vEditors.size())
125     throw InstrumentManagerException(
126     "There is no instrument editor capable to handle this instrument"
127     );
128     // simply use the first editor in the result set
129     dmsg(1,("Found matching editor '%s' for instrument ('%s', %d) having data structure ('%s','%s')\n",
130     vEditors[0].c_str(), ID.FileName.c_str(), ID.Index, sDataType.c_str(), sDataVersion.c_str()));
131     InstrumentEditor* pEditor = InstrumentEditorFactory::Create(vEditors[0]);
132 schoenebeck 1321 // register for receiving notifications from the instrument editor
133 schoenebeck 1212 pEditor->AddListener(this);
134     // create a proxy that reacts on notification on behalf of the editor
135     InstrumentEditorProxy* pProxy = new InstrumentEditorProxy;
136     // borrow the instrument on behalf of the instrument editor
137     ::gig::Instrument* pInstrument = Borrow(ID, pProxy);
138     // remember the proxy and instrument for this instrument editor
139     pProxy->pInstrument = pInstrument;
140     InstrumentEditorProxiesMutex.Lock();
141     InstrumentEditorProxies[pEditor] = pProxy;
142     InstrumentEditorProxiesMutex.Unlock();
143     // launch the instrument editor for the given instrument
144     pEditor->Launch(pInstrument, sDataType, sDataVersion);
145     }
146    
147     /**
148     * Will be called by the respective instrument editor once it left its
149     * Main() loop. That way we can handle cleanup before its thread finally
150     * dies.
151     *
152     * @param pSender - instrument editor that stops execution
153     */
154     void InstrumentResourceManager::OnInstrumentEditorQuit(InstrumentEditor* pSender) {
155     dmsg(1,("InstrumentResourceManager: instrument editor quit, doing cleanup\n"));
156     // hand back instrument and free proxy
157     InstrumentEditorProxiesMutex.Lock();
158     if (InstrumentEditorProxies.count(pSender)) {
159     InstrumentEditorProxy* pProxy =
160     dynamic_cast<InstrumentEditorProxy*>(
161     InstrumentEditorProxies[pSender]
162     );
163     InstrumentEditorProxies.erase(pSender);
164     InstrumentEditorProxiesMutex.Unlock();
165     HandBack(pProxy->pInstrument, pProxy);
166     if (pProxy) delete pProxy;
167     } else {
168     InstrumentEditorProxiesMutex.Unlock();
169     std::cerr << "Eeeek, could not find instrument editor proxy, this is a bug!\n" << std::flush;
170     }
171 persson 1455
172     // Note that we don't need to free the editor here. As it
173     // derives from Thread, it will delete itself when the thread
174     // dies.
175 schoenebeck 1212 }
176    
177 schoenebeck 1321 void InstrumentResourceManager::OnSamplesToBeRemoved(std::set<void*> Samples, InstrumentEditor* pSender) {
178     if (Samples.empty()) {
179     std::cerr << "gig::InstrumentResourceManager: WARNING, "
180     "OnSamplesToBeRemoved() called with empty list, this "
181     "is a bug!\n" << std::flush;
182     return;
183     }
184     // TODO: ATM we assume here that all samples are from the same file
185     ::gig::Sample* pFirstSample = (::gig::Sample*) *Samples.begin();
186     ::gig::File* pCriticalFile = dynamic_cast< ::gig::File*>(pFirstSample->GetParent());
187     // completely suspend all engines that use that same file
188     SuspendEnginesUsing(pCriticalFile);
189     }
190    
191     void InstrumentResourceManager::OnSamplesRemoved(InstrumentEditor* pSender) {
192     // resume all previously, completely suspended engines
193     // (we don't have to un-cache the removed samples here, since that is
194     // automatically done by the gig::Sample destructor)
195     ResumeAllEngines();
196     }
197    
198     void InstrumentResourceManager::OnDataStructureToBeChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {
199     //TODO: remove code duplication
200     if (sStructType == "gig::File") {
201     // completely suspend all engines that use that file
202     ::gig::File* pFile = (::gig::File*) pStruct;
203     SuspendEnginesUsing(pFile);
204     } else if (sStructType == "gig::Instrument") {
205     // completely suspend all engines that use that instrument
206     ::gig::Instrument* pInstrument = (::gig::Instrument*) pStruct;
207     SuspendEnginesUsing(pInstrument);
208     } else if (sStructType == "gig::Region") {
209     // only advice the engines to suspend the given region, so they'll
210     // only ignore that region (and probably already other suspended
211     // ones), but beside that continue normal playback
212     ::gig::Region* pRegion = (::gig::Region*) pStruct;
213     ::gig::Instrument* pInstrument =
214     (::gig::Instrument*) pRegion->GetParent();
215     Lock();
216     std::set<gig::Engine*> engines =
217     GetEnginesUsing(pInstrument, false/*don't lock again*/);
218     std::set<gig::Engine*>::iterator iter = engines.begin();
219     std::set<gig::Engine*>::iterator end = engines.end();
220     for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
221     Unlock();
222     } else if (sStructType == "gig::DimensionRegion") {
223     // only advice the engines to suspend the given DimensionRegions's
224     // parent region, so they'll only ignore that region (and probably
225     // already other suspended ones), but beside that continue normal
226     // playback
227     ::gig::DimensionRegion* pDimReg =
228     (::gig::DimensionRegion*) pStruct;
229     ::gig::Region* pRegion = pDimReg->GetParent();
230     ::gig::Instrument* pInstrument =
231     (::gig::Instrument*) pRegion->GetParent();
232     Lock();
233     std::set<gig::Engine*> engines =
234     GetEnginesUsing(pInstrument, false/*don't lock again*/);
235     std::set<gig::Engine*>::iterator iter = engines.begin();
236     std::set<gig::Engine*>::iterator end = engines.end();
237     for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
238     Unlock();
239     } else {
240     std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
241     "structure '" << sStructType << "' requested to be "
242     "suspended by instrument editor. This is a bug!\n"
243     << std::flush;
244     //TODO: we should inform the instrument editor that something seriously went wrong
245     }
246     }
247    
248     void InstrumentResourceManager::OnDataStructureChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {
249     //TODO: remove code duplication
250     if (sStructType == "gig::File") {
251     // resume all previously suspended engines
252     ResumeAllEngines();
253     } else if (sStructType == "gig::Instrument") {
254     // resume all previously suspended engines
255     ResumeAllEngines();
256     } else if (sStructType == "gig::Region") {
257     // advice the engines to resume the given region, that is to
258     // using it for playback again
259     ::gig::Region* pRegion = (::gig::Region*) pStruct;
260     ::gig::Instrument* pInstrument =
261     (::gig::Instrument*) pRegion->GetParent();
262     Lock();
263     std::set<gig::Engine*> engines =
264     GetEnginesUsing(pInstrument, false/*don't lock again*/);
265     std::set<gig::Engine*>::iterator iter = engines.begin();
266     std::set<gig::Engine*>::iterator end = engines.end();
267     for (; iter != end; ++iter) (*iter)->Resume(pRegion);
268     Unlock();
269     } else if (sStructType == "gig::DimensionRegion") {
270     // advice the engines to resume the given DimensionRegion's parent
271     // region, that is to using it for playback again
272     ::gig::DimensionRegion* pDimReg =
273     (::gig::DimensionRegion*) pStruct;
274     ::gig::Region* pRegion = pDimReg->GetParent();
275     ::gig::Instrument* pInstrument =
276     (::gig::Instrument*) pRegion->GetParent();
277     Lock();
278     std::set<gig::Engine*> engines =
279     GetEnginesUsing(pInstrument, false/*don't lock again*/);
280     std::set<gig::Engine*>::iterator iter = engines.begin();
281     std::set<gig::Engine*>::iterator end = engines.end();
282     for (; iter != end; ++iter) (*iter)->Resume(pRegion);
283     Unlock();
284     } else {
285     std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
286     "structure '" << sStructType << "' requested to be "
287     "resumed by instrument editor. This is a bug!\n"
288     << std::flush;
289     //TODO: we should inform the instrument editor that something seriously went wrong
290     }
291     }
292    
293     void InstrumentResourceManager::OnSampleReferenceChanged(void* pOldSample, void* pNewSample, InstrumentEditor* pSender) {
294     // uncache old sample in case it's not used by anybody anymore
295     if (pOldSample) {
296     Lock();
297     ::gig::Sample* pSample = (::gig::Sample*) pOldSample;
298     ::gig::File* pFile = (::gig::File*) pSample->GetParent();
299     std::vector< ::gig::Instrument*> instruments =
300     GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
301     for (int i = 0; i < instruments.size(); i++)
302     if (!SampleReferencedByInstrument(pSample, instruments[i]))
303     UncacheInitialSamples(pSample);
304     Unlock();
305     }
306     // make sure new sample reference is cached
307     if (pNewSample) {
308     Lock();
309     ::gig::Sample* pSample = (::gig::Sample*) pNewSample;
310     ::gig::File* pFile = (::gig::File*) pSample->GetParent();
311     // get all engines that use that same gig::File
312     std::set<gig::Engine*> engines = GetEnginesUsing(pFile, false/*don't lock again*/);
313     std::set<gig::Engine*>::iterator iter = engines.begin();
314     std::set<gig::Engine*>::iterator end = engines.end();
315     for (; iter != end; ++iter)
316     CacheInitialSamples(pSample, *iter);
317     Unlock();
318     }
319     }
320    
321 schoenebeck 53 ::gig::Instrument* InstrumentResourceManager::Create(instrument_id_t Key, InstrumentConsumer* pConsumer, void*& pArg) {
322 schoenebeck 1321 // get gig file from internal gig file manager
323 schoenebeck 947 ::gig::File* pGig = Gigs.Borrow(Key.FileName, (GigConsumer*) Key.Index); // conversion kinda hackish :/
324 schoenebeck 53
325 schoenebeck 517 // we pass this to the progress callback mechanism of libgig
326     progress_callback_arg_t callbackArg;
327     callbackArg.pManager = this;
328     callbackArg.pInstrumentKey = &Key;
329    
330     ::gig::progress_t progress;
331     progress.callback = OnInstrumentLoadingProgress;
332     progress.custom = &callbackArg;
333    
334 schoenebeck 947 dmsg(1,("Loading gig instrument ('%s',%d)...",Key.FileName.c_str(),Key.Index));
335     ::gig::Instrument* pInstrument = pGig->GetInstrument(Key.Index, &progress);
336 schoenebeck 53 if (!pInstrument) {
337     std::stringstream msg;
338 schoenebeck 947 msg << "There's no instrument with index " << Key.Index << ".";
339 schoenebeck 1212 throw InstrumentManagerException(msg.str());
340 schoenebeck 53 }
341     pGig->GetFirstSample(); // just to force complete instrument loading
342     dmsg(1,("OK\n"));
343    
344     // cache initial samples points (for actually needed samples)
345     dmsg(1,("Caching initial samples..."));
346 schoenebeck 517 uint iRegion = 0; // just for progress calculation
347 schoenebeck 53 ::gig::Region* pRgn = pInstrument->GetFirstRegion();
348     while (pRgn) {
349 schoenebeck 517 // we randomly schedule 90% for the .gig file loading and the remaining 10% now for sample caching
350     const float localProgress = 0.9f + 0.1f * (float) iRegion / (float) pInstrument->Regions;
351 schoenebeck 947 DispatchResourceProgressEvent(Key, localProgress);
352    
353 schoenebeck 354 if (pRgn->GetSample() && !pRgn->GetSample()->GetCache().Size) {
354 schoenebeck 53 dmsg(2,("C"));
355 schoenebeck 947 CacheInitialSamples(pRgn->GetSample(), (gig::EngineChannel*) pConsumer);
356 schoenebeck 53 }
357     for (uint i = 0; i < pRgn->DimensionRegions; i++) {
358 schoenebeck 947 CacheInitialSamples(pRgn->pDimensionRegions[i]->pSample, (gig::EngineChannel*) pConsumer);
359 schoenebeck 53 }
360    
361     pRgn = pInstrument->GetNextRegion();
362 schoenebeck 517 iRegion++;
363 schoenebeck 53 }
364     dmsg(1,("OK\n"));
365 schoenebeck 517 DispatchResourceProgressEvent(Key, 1.0f); // done; notify all consumers about progress 100%
366 schoenebeck 53
367     // we need the following for destruction later
368     instr_entry_t* pEntry = new instr_entry_t;
369 schoenebeck 947 pEntry->ID.FileName = Key.FileName;
370     pEntry->ID.Index = Key.Index;
371 schoenebeck 53 pEntry->pGig = pGig;
372 persson 438
373 schoenebeck 1212 gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(pConsumer);
374 schoenebeck 411 // and we save this to check if we need to reallocate for a engine with higher value of 'MaxSamplesPerSecond'
375     pEntry->MaxSamplesPerCycle =
376 schoenebeck 1212 (!pEngineChannel) ? 0 /* don't care for instrument editors */ :
377     (pEngineChannel->GetEngine()) ?
378     dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()
379     : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;
380 schoenebeck 53 pArg = pEntry;
381    
382     return pInstrument;
383     }
384    
385     void InstrumentResourceManager::Destroy( ::gig::Instrument* pResource, void* pArg) {
386     instr_entry_t* pEntry = (instr_entry_t*) pArg;
387 schoenebeck 947 // we don't need the .gig file here anymore
388     Gigs.HandBack(pEntry->pGig, (GigConsumer*) pEntry->ID.Index); // conversion kinda hackish :/
389 schoenebeck 53 delete pEntry;
390     }
391    
392     void InstrumentResourceManager::OnBorrow(::gig::Instrument* pResource, InstrumentConsumer* pConsumer, void*& pArg) {
393     instr_entry_t* pEntry = (instr_entry_t*) pArg;
394 schoenebeck 411 gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(pConsumer);
395     uint maxSamplesPerCycle =
396 schoenebeck 1212 (pEngineChannel && pEngineChannel->GetEngine()) ? dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()
397 schoenebeck 411 : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;
398     if (pEntry->MaxSamplesPerCycle < maxSamplesPerCycle) {
399 schoenebeck 53 Update(pResource, pConsumer);
400     }
401     }
402    
403     /**
404 persson 1038 * Give back an instrument. This should be used instead of
405     * HandBack if there are some dimension regions that are still in
406     * use. (When an instrument is changed, the voices currently
407     * playing is allowed to keep playing with the old instrument
408     * until note off arrives. New notes will use the new instrument.)
409     */
410     void InstrumentResourceManager::HandBackInstrument(::gig::Instrument* pResource, InstrumentConsumer* pConsumer,
411     ::gig::DimensionRegion** dimRegionsInUse) {
412     DimRegInfoMutex.Lock();
413     for (int i = 0 ; dimRegionsInUse[i] ; i++) {
414     DimRegInfo[dimRegionsInUse[i]].refCount++;
415     SampleRefCount[dimRegionsInUse[i]->pSample]++;
416     }
417     HandBack(pResource, pConsumer, true);
418     DimRegInfoMutex.Unlock();
419     }
420    
421     /**
422     * Give back a dimension region that belongs to an instrument that
423     * was previously handed back.
424     */
425     void InstrumentResourceManager::HandBackDimReg(::gig::DimensionRegion* pDimReg) {
426     DimRegInfoMutex.Lock();
427     dimreg_info_t& dimRegInfo = DimRegInfo[pDimReg];
428     int dimRegRefCount = --dimRegInfo.refCount;
429     int sampleRefCount = --SampleRefCount[pDimReg->pSample];
430     if (dimRegRefCount == 0) {
431     ::gig::File* gig = dimRegInfo.file;
432     ::RIFF::File* riff = dimRegInfo.riff;
433     DimRegInfo.erase(pDimReg);
434     // TODO: we could delete Region and Instrument here if
435     // they have become unused
436    
437     if (sampleRefCount == 0) {
438     SampleRefCount.erase(pDimReg->pSample);
439    
440     if (gig) {
441     gig->DeleteSample(pDimReg->pSample);
442     if (!gig->GetFirstSample()) {
443     dmsg(2,("No more samples in use - freeing gig\n"));
444     delete gig;
445     delete riff;
446     }
447     }
448     }
449     }
450     DimRegInfoMutex.Unlock();
451     }
452    
453     /**
454 schoenebeck 1321 * Just a wrapper around the other @c CacheInitialSamples() method.
455     *
456     * @param pSample - points to the sample to be cached
457     * @param pEngine - pointer to Gig Engine Channel which caused this call
458     * (may be NULL, in this case default amount of samples
459     * will be cached)
460     */
461     void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::EngineChannel* pEngineChannel) {
462     gig::Engine* pEngine =
463     (pEngineChannel && pEngineChannel->GetEngine()) ?
464     dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine()) : NULL;
465     CacheInitialSamples(pSample, pEngine);
466     }
467    
468     /**
469 schoenebeck 53 * Caches a certain size at the beginning of the given sample in RAM. If the
470     * sample is very short, the whole sample will be loaded into RAM and thus
471     * no disk streaming is needed for this sample. Caching an initial part of
472     * samples is needed to compensate disk reading latency.
473     *
474     * @param pSample - points to the sample to be cached
475 schoenebeck 1321 * @param pEngine - pointer to Gig Engine which caused this call
476     * (may be NULL, in this case default amount of samples
477     * will be cached)
478 schoenebeck 53 */
479 schoenebeck 1321 void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::Engine* pEngine) {
480 schoenebeck 420 if (!pSample) {
481 persson 438 dmsg(4,("gig::InstrumentResourceManager: Skipping sample (pSample == NULL)\n"));
482 schoenebeck 420 return;
483     }
484     if (!pSample->SamplesTotal) return; // skip zero size samples
485 persson 438
486 schoenebeck 554 if (pSample->SamplesTotal <= CONFIG_PRELOAD_SAMPLES) {
487 schoenebeck 53 // Sample is too short for disk streaming, so we load the whole
488 schoenebeck 554 // sample into RAM and place 'pAudioIO->FragmentSize << CONFIG_MAX_PITCH'
489 schoenebeck 53 // number of '0' samples (silence samples) behind the official buffer
490     // border, to allow the interpolator do it's work even at the end of
491 persson 438 // the sample.
492 schoenebeck 411 const uint maxSamplesPerCycle =
493 schoenebeck 1321 (pEngine) ? pEngine->pAudioOutputDevice->MaxSamplesPerCycle()
494     : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;
495 schoenebeck 554 const uint neededSilenceSamples = (maxSamplesPerCycle << CONFIG_MAX_PITCH) + 3;
496 schoenebeck 420 const uint currentlyCachedSilenceSamples = pSample->GetCache().NullExtensionSize / pSample->FrameSize;
497     if (currentlyCachedSilenceSamples < neededSilenceSamples) {
498     dmsg(3,("Caching whole sample (sample name: \"%s\", sample size: %d)\n", pSample->pInfo->Name.c_str(), pSample->SamplesTotal));
499     ::gig::buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(neededSilenceSamples);
500     dmsg(4,("Cached %d Bytes, %d silence bytes.\n", buf.Size, buf.NullExtensionSize));
501     }
502 schoenebeck 53 }
503 schoenebeck 554 else { // we only cache CONFIG_PRELOAD_SAMPLES and stream the other sample points from disk
504     if (!pSample->GetCache().Size) pSample->LoadSampleData(CONFIG_PRELOAD_SAMPLES);
505 schoenebeck 53 }
506    
507     if (!pSample->GetCache().Size) std::cerr << "Unable to cache sample - maybe memory full!" << std::endl << std::flush;
508     }
509    
510 schoenebeck 1321 void InstrumentResourceManager::UncacheInitialSamples(::gig::Sample* pSample) {
511     dmsg(1,("Uncaching sample %x\n",pSample));
512     if (pSample->GetCache().Size) pSample->ReleaseSampleData();
513     }
514 schoenebeck 53
515 schoenebeck 1321 /**
516     * Returns a list with all instruments currently in use, that are part of
517     * the given file.
518     *
519     * @param pFile - search criteria
520     * @param bLock - whether we should lock (mutex) the instrument manager
521     * during this call and unlock at the end of this call
522     */
523     std::vector< ::gig::Instrument*> InstrumentResourceManager::GetInstrumentsCurrentlyUsedOf(::gig::File* pFile, bool bLock) {
524     if (bLock) Lock();
525     std::vector< ::gig::Instrument*> result;
526     std::vector< ::gig::Instrument*> allInstruments = Resources(false/*don't lock again*/);
527     for (int i = 0; i < allInstruments.size(); i++)
528     if (
529     (::gig::File*) allInstruments[i]->GetParent()
530     == pFile
531     ) result.push_back(allInstruments[i]);
532     if (bLock) Unlock();
533     return result;
534     }
535 schoenebeck 53
536 schoenebeck 1321 /**
537     * Returns a list with all gig Engines that are currently using the given
538     * instrument.
539     *
540     * @param pInstrument - search criteria
541     * @param bLock - whether we should lock (mutex) the instrument manager
542     * during this call and unlock at the end of this call
543     */
544     std::set<gig::Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::Instrument* pInstrument, bool bLock) {
545     if (bLock) Lock();
546     std::set<gig::Engine*> result;
547     std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(pInstrument);
548     std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
549     std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end = consumers.end();
550     for (; iter != end; ++iter) {
551     gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(*iter);
552     if (!pEngineChannel) continue;
553     gig::Engine* pEngine = dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine());
554     if (!pEngine) continue;
555     result.insert(pEngine);
556     }
557     if (bLock) Unlock();
558     return result;
559     }
560    
561     /**
562     * Returns a list with all gig Engines that are currently using an
563     * instrument that is part of the given instrument file.
564     *
565     * @param pFile - search criteria
566     * @param bLock - whether we should lock (mutex) the instrument manager
567     * during this call and unlock at the end of this call
568     */
569     std::set<gig::Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::File* pFile, bool bLock) {
570     if (bLock) Lock();
571     // get all instruments (currently in usage) that use that same gig::File
572     std::vector< ::gig::Instrument*> instrumentsOfInterest =
573     GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
574    
575     // get all engines that use that same gig::File
576     std::set<gig::Engine*> result;
577     {
578     for (int i = 0; i < instrumentsOfInterest.size(); i++) {
579     std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(instrumentsOfInterest[i]);
580     std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
581     std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end = consumers.end();
582     for (; iter != end; ++iter) {
583     gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(*iter);
584     if (!pEngineChannel) continue;
585     gig::Engine* pEngine = dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine());
586     if (!pEngine) continue;
587     // the unique, sorted container std::set makes
588     // sure we won't have duplicates
589     result.insert(pEngine);
590     }
591     }
592     }
593     if (bLock) Unlock();
594     return result;
595     }
596    
597     /**
598     * Returns @c true in case the given sample is referenced somewhere by the
599     * given instrument, @c false otherwise.
600     *
601     * @param pSample - sample reference
602     * @param pInstrument - instrument that might use that sample
603     */
604     bool InstrumentResourceManager::SampleReferencedByInstrument(::gig::Sample* pSample, ::gig::Instrument* pInstrument) {
605     for (
606     ::gig::Region* pRegion = pInstrument->GetFirstRegion();
607     pRegion; pRegion = pInstrument->GetNextRegion()
608     ) {
609     for (
610     int i = 0; i < pRegion->DimensionRegions &&
611     pRegion->pDimensionRegions[i]; i++
612     ) {
613     if (pRegion->pDimensionRegions[i]->pSample == pSample)
614     return true;
615     }
616     }
617     return false;
618     }
619    
620     /**
621     * Suspend all gig engines that use the given instrument. This means
622     * completely stopping playback on those engines and killing all their
623     * voices and disk streams. This method will block until all voices AND
624     * their disk streams are finally deleted and the engine turned into a
625     * complete idle loop.
626     *
627     * All @c SuspendEnginesUsing() methods only serve one thread by one and
628     * block all other threads until the current active thread called
629     * @c ResumeAllEngines() .
630     *
631     * @param pInstrument - search criteria
632     */
633     void InstrumentResourceManager::SuspendEnginesUsing(::gig::Instrument* pInstrument) {
634     // make sure no other thread suspends whole engines at the same time
635     suspendedEnginesMutex.Lock();
636     // get all engines that use that same gig::Instrument
637     suspendedEngines = GetEnginesUsing(pInstrument, true/*lock*/);
638     // finally, completely suspend all engines that use that same gig::Instrument
639     std::set<gig::Engine*>::iterator iter = suspendedEngines.begin();
640     std::set<gig::Engine*>::iterator end = suspendedEngines.end();
641     for (; iter != end; ++iter) (*iter)->SuspendAll();
642     }
643    
644     /**
645     * Suspend all gig engines that use the given instrument file. This means
646     * completely stopping playback on those engines and killing all their
647     * voices and disk streams. This method will block until all voices AND
648     * their disk streams are finally deleted and the engine turned into a
649     * complete idle loop.
650     *
651     * All @c SuspendEnginesUsing() methods only serve one thread by one and
652     * block all other threads until the current active thread called
653     * @c ResumeAllEngines() .
654     *
655     * @param pFile - search criteria
656     */
657     void InstrumentResourceManager::SuspendEnginesUsing(::gig::File* pFile) {
658     // make sure no other thread suspends whole engines at the same time
659     suspendedEnginesMutex.Lock();
660     // get all engines that use that same gig::File
661     suspendedEngines = GetEnginesUsing(pFile, true/*lock*/);
662     // finally, completely suspend all engines that use that same gig::File
663     std::set<gig::Engine*>::iterator iter = suspendedEngines.begin();
664     std::set<gig::Engine*>::iterator end = suspendedEngines.end();
665     for (; iter != end; ++iter) (*iter)->SuspendAll();
666     }
667    
668     /**
669     * MUST be called after one called one of the @c SuspendEnginesUsing()
670     * methods, to resume normal playback on all previously suspended engines.
671     * As it's only possible for one thread to suspend whole engines at the
672     * same time, this method doesn't take any arguments.
673     */
674     void InstrumentResourceManager::ResumeAllEngines() {
675     // resume all previously completely suspended engines
676     std::set<Engine*>::iterator iter = suspendedEngines.begin();
677     std::set<Engine*>::iterator end = suspendedEngines.end();
678     for (; iter != end; ++iter) (*iter)->ResumeAll();
679     // no more suspended engines ...
680     suspendedEngines.clear();
681     // allow another thread to suspend whole engines
682     suspendedEnginesMutex.Unlock();
683     }
684    
685    
686    
687 schoenebeck 53 // internal gig file manager
688    
689     ::gig::File* InstrumentResourceManager::GigResourceManager::Create(String Key, GigConsumer* pConsumer, void*& pArg) {
690     dmsg(1,("Loading gig file \'%s\'...", Key.c_str()));
691     ::RIFF::File* pRIFF = new ::RIFF::File(Key);
692     ::gig::File* pGig = new ::gig::File(pRIFF);
693     pArg = pRIFF;
694     dmsg(1,("OK\n"));
695     return pGig;
696     }
697    
698     void InstrumentResourceManager::GigResourceManager::Destroy(::gig::File* pResource, void* pArg) {
699     dmsg(1,("Freeing gig file from memory..."));
700 persson 1038
701     // Delete as much as possible of the gig file. Some of the
702     // dimension regions and samples may still be in use - these
703     // will be deleted later by the HandBackDimReg function.
704     bool deleteFile = true;
705     ::gig::Instrument* nextInstrument;
706     for (::gig::Instrument* instrument = pResource->GetFirstInstrument() ;
707     instrument ;
708     instrument = nextInstrument) {
709     nextInstrument = pResource->GetNextInstrument();
710     bool deleteInstrument = true;
711     ::gig::Region* nextRegion;
712     for (::gig::Region *region = instrument->GetFirstRegion() ;
713     region ;
714     region = nextRegion) {
715     nextRegion = instrument->GetNextRegion();
716     bool deleteRegion = true;
717     for (int i = 0 ; i < region->DimensionRegions ; i++)
718     {
719     ::gig::DimensionRegion *d = region->pDimensionRegions[i];
720     std::map< ::gig::DimensionRegion*, dimreg_info_t>::iterator iter = parent->DimRegInfo.find(d);
721     if (iter != parent->DimRegInfo.end()) {
722     dimreg_info_t& dimRegInfo = (*iter).second;
723     dimRegInfo.file = pResource;
724     dimRegInfo.riff = (::RIFF::File*)pArg;
725     deleteFile = deleteInstrument = deleteRegion = false;
726     }
727     }
728     if (deleteRegion) instrument->DeleteRegion(region);
729     }
730     if (deleteInstrument) pResource->DeleteInstrument(instrument);
731     }
732     if (deleteFile) {
733     delete pResource;
734     delete (::RIFF::File*) pArg;
735     } else {
736     dmsg(2,("keeping some samples that are in use..."));
737     ::gig::Sample* nextSample;
738     for (::gig::Sample* sample = pResource->GetFirstSample() ;
739     sample ;
740     sample = nextSample) {
741     nextSample = pResource->GetNextSample();
742     if (parent->SampleRefCount.find(sample) == parent->SampleRefCount.end()) {
743     pResource->DeleteSample(sample);
744     }
745     }
746     }
747 schoenebeck 53 dmsg(1,("OK\n"));
748     }
749    
750     }} // namespace LinuxSampler::gig

  ViewVC Help
Powered by ViewVC