/[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 1653 - (hide annotations) (download)
Wed Jan 30 01:51:46 2008 UTC (16 years, 2 months ago) by schoenebeck
File size: 41867 byte(s)
* added support for notifying instrument editors on note-on / note-off
  events (e.g. to highlight the pressed keys on the virtual keyboard
  of gigedit)
* fixed return value of recently added Thread::TestCancel() method
* be verbose on DLL load errors (on Linux)

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 persson 1646 * Copyright (C) 2005 - 2008 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 schoenebeck 1653 // the instrument editor we work on behalf
71     InstrumentEditor* pEditor;
72 schoenebeck 1212 };
73    
74 schoenebeck 517 /**
75     * Callback function which will be called by libgig during loading of
76     * instruments to inform about the current progress. Or to be more
77     * specific; it will be called during the GetInstrument() call.
78     *
79     * @param pProgress - contains current progress value, pointer to the
80     * InstrumentResourceManager instance and
81     * instrument ID
82     */
83     void InstrumentResourceManager::OnInstrumentLoadingProgress(::gig::progress_t* pProgress) {
84     dmsg(7,("gig::InstrumentResourceManager: progress %f%", pProgress->factor));
85     progress_callback_arg_t* pArg = static_cast<progress_callback_arg_t*>(pProgress->custom);
86     // we randomly schedule 90% for the .gig file loading and the remaining 10% later for sample caching
87     const float localProgress = 0.9f * pProgress->factor;
88     pArg->pManager->DispatchResourceProgressEvent(*pArg->pInstrumentKey, localProgress);
89     }
90    
91 schoenebeck 947 std::vector<InstrumentResourceManager::instrument_id_t> InstrumentResourceManager::Instruments() {
92     return Entries();
93     }
94    
95     InstrumentManager::mode_t InstrumentResourceManager::GetMode(const instrument_id_t& ID) {
96     return static_cast<InstrumentManager::mode_t>(AvailabilityMode(ID));
97     }
98    
99     void InstrumentResourceManager::SetMode(const instrument_id_t& ID, InstrumentManager::mode_t Mode) {
100     dmsg(2,("gig::InstrumentResourceManager: setting mode for %s (Index=%d) to %d\n",ID.FileName.c_str(),ID.Index,Mode));
101     SetAvailabilityMode(ID, static_cast<ResourceManager<InstrumentManager::instrument_id_t, ::gig::Instrument>::mode_t>(Mode));
102     }
103    
104     String InstrumentResourceManager::GetInstrumentName(instrument_id_t ID) {
105 schoenebeck 970 Lock();
106     ::gig::Instrument* pInstrument = Resource(ID, false);
107     String res = (pInstrument) ? pInstrument->pInfo->Name : "";
108     Unlock();
109     return res;
110 schoenebeck 947 }
111    
112 schoenebeck 1321 String InstrumentResourceManager::GetInstrumentDataStructureName(instrument_id_t ID) {
113 schoenebeck 1212 return ::gig::libraryName();
114     }
115    
116 schoenebeck 1321 String InstrumentResourceManager::GetInstrumentDataStructureVersion(instrument_id_t ID) {
117 schoenebeck 1212 return ::gig::libraryVersion();
118     }
119    
120 schoenebeck 1525 std::vector<InstrumentResourceManager::instrument_id_t> InstrumentResourceManager::GetInstrumentFileContent(String File) throw (InstrumentManagerException) {
121     ::RIFF::File* riff = NULL;
122     ::gig::File* gig = NULL;
123     try {
124     std::vector<instrument_id_t> result;
125     riff = new ::RIFF::File(File);
126     gig = new ::gig::File(riff);
127     gig->SetAutoLoad(false); // avoid time consuming samples scanning
128     for (int i = 0; gig->GetInstrument(i); i++) {
129     instrument_id_t id;
130     id.FileName = File;
131     id.Index = i;
132     result.push_back(id);
133     }
134     if (gig) delete gig;
135     if (riff) delete riff;
136     return result;
137     } catch (::RIFF::Exception e) {
138     if (gig) delete gig;
139     if (riff) delete riff;
140     throw InstrumentManagerException(e.Message);
141     } catch (...) {
142     if (gig) delete gig;
143     if (riff) delete riff;
144     throw InstrumentManagerException("Unknown exception while trying to parse '" + File + "'");
145     }
146     }
147    
148     InstrumentResourceManager::instrument_info_t InstrumentResourceManager::GetInstrumentInfo(instrument_id_t ID) throw (InstrumentManagerException) {
149     std::vector<instrument_id_t> result;
150     ::RIFF::File* riff = NULL;
151     ::gig::File* gig = NULL;
152     try {
153     riff = new ::RIFF::File(ID.FileName);
154     gig = new ::gig::File(riff);
155     gig->SetAutoLoad(false); // avoid time consuming samples scanning
156     ::gig::Instrument* pInstrument = gig->GetInstrument(ID.Index);
157     if (!pInstrument) throw InstrumentManagerException("There is no instrument " + ToString(ID.Index) + " in " + ID.FileName);
158     instrument_info_t info;
159     if (gig->pVersion) {
160     info.FormatVersion = ToString(gig->pVersion->major);
161     info.Product = gig->pInfo->Product;
162     info.Artists = gig->pInfo->Artists;
163     }
164     info.InstrumentName = pInstrument->pInfo->Name;
165     if (gig) delete gig;
166     if (riff) delete riff;
167     return info;
168     } catch (::RIFF::Exception e) {
169     if (gig) delete gig;
170     if (riff) delete riff;
171     throw InstrumentManagerException(e.Message);
172     } catch (...) {
173     if (gig) delete gig;
174     if (riff) delete riff;
175     throw InstrumentManagerException("Unknown exception while trying to parse '" + ID.FileName + "'");
176     }
177     }
178    
179 schoenebeck 1212 void InstrumentResourceManager::LaunchInstrumentEditor(instrument_id_t ID) throw (InstrumentManagerException) {
180 schoenebeck 1321 const String sDataType = GetInstrumentDataStructureName(ID);
181     const String sDataVersion = GetInstrumentDataStructureVersion(ID);
182 schoenebeck 1212 // find instrument editors capable to handle given instrument
183     std::vector<String> vEditors =
184     InstrumentEditorFactory::MatchingEditors(sDataType, sDataVersion);
185     if (!vEditors.size())
186     throw InstrumentManagerException(
187     "There is no instrument editor capable to handle this instrument"
188     );
189     // simply use the first editor in the result set
190     dmsg(1,("Found matching editor '%s' for instrument ('%s', %d) having data structure ('%s','%s')\n",
191     vEditors[0].c_str(), ID.FileName.c_str(), ID.Index, sDataType.c_str(), sDataVersion.c_str()));
192     InstrumentEditor* pEditor = InstrumentEditorFactory::Create(vEditors[0]);
193 schoenebeck 1321 // register for receiving notifications from the instrument editor
194 schoenebeck 1212 pEditor->AddListener(this);
195     // create a proxy that reacts on notification on behalf of the editor
196     InstrumentEditorProxy* pProxy = new InstrumentEditorProxy;
197     // borrow the instrument on behalf of the instrument editor
198     ::gig::Instrument* pInstrument = Borrow(ID, pProxy);
199     // remember the proxy and instrument for this instrument editor
200     pProxy->pInstrument = pInstrument;
201 schoenebeck 1653 pProxy->pEditor = pEditor;
202 schoenebeck 1212 InstrumentEditorProxiesMutex.Lock();
203 schoenebeck 1653 InstrumentEditorProxies.add(pProxy);
204 schoenebeck 1212 InstrumentEditorProxiesMutex.Unlock();
205     // launch the instrument editor for the given instrument
206     pEditor->Launch(pInstrument, sDataType, sDataVersion);
207     }
208    
209     /**
210     * Will be called by the respective instrument editor once it left its
211     * Main() loop. That way we can handle cleanup before its thread finally
212     * dies.
213     *
214     * @param pSender - instrument editor that stops execution
215     */
216     void InstrumentResourceManager::OnInstrumentEditorQuit(InstrumentEditor* pSender) {
217     dmsg(1,("InstrumentResourceManager: instrument editor quit, doing cleanup\n"));
218     // hand back instrument and free proxy
219     InstrumentEditorProxiesMutex.Lock();
220 schoenebeck 1653 for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
221 schoenebeck 1212 InstrumentEditorProxy* pProxy =
222     dynamic_cast<InstrumentEditorProxy*>(
223 schoenebeck 1653 InstrumentEditorProxies[i]
224 schoenebeck 1212 );
225 schoenebeck 1653 if (pProxy->pEditor == pSender) {
226     InstrumentEditorProxies.remove(i);
227     InstrumentEditorProxiesMutex.Unlock();
228     HandBack(pProxy->pInstrument, pProxy);
229     if (pProxy) delete pProxy;
230     return;
231     }
232 schoenebeck 1212 }
233 schoenebeck 1653 InstrumentEditorProxiesMutex.Unlock();
234     std::cerr << "Eeeek, could not find instrument editor proxy, this is a bug!\n" << std::flush;
235 persson 1455
236     // Note that we don't need to free the editor here. As it
237     // derives from Thread, it will delete itself when the thread
238     // dies.
239 schoenebeck 1212 }
240    
241 schoenebeck 1653 /**
242     * Try to inform the respective instrument editor(s), that a note on
243     * event just occured. This method is called by the MIDI thread. If any
244     * obstacles are in the way (e.g. if a wait for an unlock would be
245     * required) we give up immediately, since the RT safeness of the MIDI
246     * thread has absolute priority.
247     */
248     void InstrumentResourceManager::TrySendNoteOnToEditors(uint8_t Key, uint8_t Velocity, ::gig::Instrument* pInstrument) {
249     const bool bGotLock = InstrumentEditorProxiesMutex.Trylock(); // naively assumes RT safe implementation
250     if (!bGotLock) return; // hell, forget it, not worth the hassle
251     for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
252     InstrumentEditorProxy* pProxy =
253     dynamic_cast<InstrumentEditorProxy*>(
254     InstrumentEditorProxies[i]
255     );
256     if (pProxy->pInstrument == pInstrument)
257     pProxy->pEditor->SendNoteOnToEditor(Key, Velocity);
258     }
259     InstrumentEditorProxiesMutex.Unlock(); // naively assumes RT safe implementation
260     }
261    
262     /**
263     * Try to inform the respective instrument editor(s), that a note off
264     * event just occured. This method is called by the MIDI thread. If any
265     * obstacles are in the way (e.g. if a wait for an unlock would be
266     * required) we give up immediately, since the RT safeness of the MIDI
267     * thread has absolute priority.
268     */
269     void InstrumentResourceManager::TrySendNoteOffToEditors(uint8_t Key, uint8_t Velocity, ::gig::Instrument* pInstrument) {
270     const bool bGotLock = InstrumentEditorProxiesMutex.Trylock(); // naively assumes RT safe implementation
271     if (!bGotLock) return; // hell, forget it, not worth the hassle
272     for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
273     InstrumentEditorProxy* pProxy =
274     dynamic_cast<InstrumentEditorProxy*>(
275     InstrumentEditorProxies[i]
276     );
277     if (pProxy->pInstrument == pInstrument)
278     pProxy->pEditor->SendNoteOffToEditor(Key, Velocity);
279     }
280     InstrumentEditorProxiesMutex.Unlock(); // naively assumes RT safe implementation
281     }
282    
283 schoenebeck 1321 void InstrumentResourceManager::OnSamplesToBeRemoved(std::set<void*> Samples, InstrumentEditor* pSender) {
284     if (Samples.empty()) {
285     std::cerr << "gig::InstrumentResourceManager: WARNING, "
286     "OnSamplesToBeRemoved() called with empty list, this "
287     "is a bug!\n" << std::flush;
288     return;
289     }
290     // TODO: ATM we assume here that all samples are from the same file
291     ::gig::Sample* pFirstSample = (::gig::Sample*) *Samples.begin();
292     ::gig::File* pCriticalFile = dynamic_cast< ::gig::File*>(pFirstSample->GetParent());
293     // completely suspend all engines that use that same file
294     SuspendEnginesUsing(pCriticalFile);
295     }
296    
297     void InstrumentResourceManager::OnSamplesRemoved(InstrumentEditor* pSender) {
298     // resume all previously, completely suspended engines
299     // (we don't have to un-cache the removed samples here, since that is
300     // automatically done by the gig::Sample destructor)
301     ResumeAllEngines();
302     }
303    
304     void InstrumentResourceManager::OnDataStructureToBeChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {
305     //TODO: remove code duplication
306     if (sStructType == "gig::File") {
307     // completely suspend all engines that use that file
308     ::gig::File* pFile = (::gig::File*) pStruct;
309     SuspendEnginesUsing(pFile);
310     } else if (sStructType == "gig::Instrument") {
311     // completely suspend all engines that use that instrument
312     ::gig::Instrument* pInstrument = (::gig::Instrument*) pStruct;
313     SuspendEnginesUsing(pInstrument);
314     } else if (sStructType == "gig::Region") {
315     // only advice the engines to suspend the given region, so they'll
316     // only ignore that region (and probably already other suspended
317     // ones), but beside that continue normal playback
318     ::gig::Region* pRegion = (::gig::Region*) pStruct;
319     ::gig::Instrument* pInstrument =
320     (::gig::Instrument*) pRegion->GetParent();
321     Lock();
322     std::set<gig::Engine*> engines =
323     GetEnginesUsing(pInstrument, false/*don't lock again*/);
324     std::set<gig::Engine*>::iterator iter = engines.begin();
325     std::set<gig::Engine*>::iterator end = engines.end();
326     for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
327     Unlock();
328     } else if (sStructType == "gig::DimensionRegion") {
329     // only advice the engines to suspend the given DimensionRegions's
330     // parent region, so they'll only ignore that region (and probably
331     // already other suspended ones), but beside that continue normal
332     // playback
333     ::gig::DimensionRegion* pDimReg =
334     (::gig::DimensionRegion*) pStruct;
335     ::gig::Region* pRegion = pDimReg->GetParent();
336     ::gig::Instrument* pInstrument =
337     (::gig::Instrument*) pRegion->GetParent();
338     Lock();
339     std::set<gig::Engine*> engines =
340     GetEnginesUsing(pInstrument, false/*don't lock again*/);
341     std::set<gig::Engine*>::iterator iter = engines.begin();
342     std::set<gig::Engine*>::iterator end = engines.end();
343     for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
344     Unlock();
345     } else {
346     std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
347     "structure '" << sStructType << "' requested to be "
348     "suspended by instrument editor. This is a bug!\n"
349     << std::flush;
350     //TODO: we should inform the instrument editor that something seriously went wrong
351     }
352     }
353    
354     void InstrumentResourceManager::OnDataStructureChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {
355     //TODO: remove code duplication
356     if (sStructType == "gig::File") {
357     // resume all previously suspended engines
358     ResumeAllEngines();
359     } else if (sStructType == "gig::Instrument") {
360     // resume all previously suspended engines
361     ResumeAllEngines();
362     } else if (sStructType == "gig::Region") {
363     // advice the engines to resume the given region, that is to
364     // using it for playback again
365     ::gig::Region* pRegion = (::gig::Region*) pStruct;
366     ::gig::Instrument* pInstrument =
367     (::gig::Instrument*) pRegion->GetParent();
368     Lock();
369     std::set<gig::Engine*> engines =
370     GetEnginesUsing(pInstrument, false/*don't lock again*/);
371     std::set<gig::Engine*>::iterator iter = engines.begin();
372     std::set<gig::Engine*>::iterator end = engines.end();
373     for (; iter != end; ++iter) (*iter)->Resume(pRegion);
374     Unlock();
375     } else if (sStructType == "gig::DimensionRegion") {
376     // advice the engines to resume the given DimensionRegion's parent
377     // region, that is to using it for playback again
378     ::gig::DimensionRegion* pDimReg =
379     (::gig::DimensionRegion*) pStruct;
380     ::gig::Region* pRegion = pDimReg->GetParent();
381     ::gig::Instrument* pInstrument =
382     (::gig::Instrument*) pRegion->GetParent();
383     Lock();
384     std::set<gig::Engine*> engines =
385     GetEnginesUsing(pInstrument, false/*don't lock again*/);
386     std::set<gig::Engine*>::iterator iter = engines.begin();
387     std::set<gig::Engine*>::iterator end = engines.end();
388     for (; iter != end; ++iter) (*iter)->Resume(pRegion);
389     Unlock();
390     } else {
391     std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
392     "structure '" << sStructType << "' requested to be "
393     "resumed by instrument editor. This is a bug!\n"
394     << std::flush;
395     //TODO: we should inform the instrument editor that something seriously went wrong
396     }
397     }
398    
399     void InstrumentResourceManager::OnSampleReferenceChanged(void* pOldSample, void* pNewSample, InstrumentEditor* pSender) {
400     // uncache old sample in case it's not used by anybody anymore
401     if (pOldSample) {
402     Lock();
403     ::gig::Sample* pSample = (::gig::Sample*) pOldSample;
404     ::gig::File* pFile = (::gig::File*) pSample->GetParent();
405     std::vector< ::gig::Instrument*> instruments =
406     GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
407     for (int i = 0; i < instruments.size(); i++)
408     if (!SampleReferencedByInstrument(pSample, instruments[i]))
409     UncacheInitialSamples(pSample);
410     Unlock();
411     }
412     // make sure new sample reference is cached
413     if (pNewSample) {
414     Lock();
415     ::gig::Sample* pSample = (::gig::Sample*) pNewSample;
416     ::gig::File* pFile = (::gig::File*) pSample->GetParent();
417     // get all engines that use that same gig::File
418     std::set<gig::Engine*> engines = GetEnginesUsing(pFile, false/*don't lock again*/);
419     std::set<gig::Engine*>::iterator iter = engines.begin();
420     std::set<gig::Engine*>::iterator end = engines.end();
421     for (; iter != end; ++iter)
422     CacheInitialSamples(pSample, *iter);
423     Unlock();
424     }
425     }
426    
427 schoenebeck 53 ::gig::Instrument* InstrumentResourceManager::Create(instrument_id_t Key, InstrumentConsumer* pConsumer, void*& pArg) {
428 schoenebeck 1321 // get gig file from internal gig file manager
429 schoenebeck 947 ::gig::File* pGig = Gigs.Borrow(Key.FileName, (GigConsumer*) Key.Index); // conversion kinda hackish :/
430 schoenebeck 53
431 schoenebeck 517 // we pass this to the progress callback mechanism of libgig
432     progress_callback_arg_t callbackArg;
433     callbackArg.pManager = this;
434     callbackArg.pInstrumentKey = &Key;
435    
436     ::gig::progress_t progress;
437     progress.callback = OnInstrumentLoadingProgress;
438     progress.custom = &callbackArg;
439    
440 schoenebeck 947 dmsg(1,("Loading gig instrument ('%s',%d)...",Key.FileName.c_str(),Key.Index));
441     ::gig::Instrument* pInstrument = pGig->GetInstrument(Key.Index, &progress);
442 schoenebeck 53 if (!pInstrument) {
443     std::stringstream msg;
444 schoenebeck 947 msg << "There's no instrument with index " << Key.Index << ".";
445 schoenebeck 1212 throw InstrumentManagerException(msg.str());
446 schoenebeck 53 }
447     pGig->GetFirstSample(); // just to force complete instrument loading
448     dmsg(1,("OK\n"));
449    
450     // cache initial samples points (for actually needed samples)
451     dmsg(1,("Caching initial samples..."));
452 schoenebeck 517 uint iRegion = 0; // just for progress calculation
453 schoenebeck 53 ::gig::Region* pRgn = pInstrument->GetFirstRegion();
454     while (pRgn) {
455 schoenebeck 517 // we randomly schedule 90% for the .gig file loading and the remaining 10% now for sample caching
456     const float localProgress = 0.9f + 0.1f * (float) iRegion / (float) pInstrument->Regions;
457 schoenebeck 947 DispatchResourceProgressEvent(Key, localProgress);
458    
459 schoenebeck 354 if (pRgn->GetSample() && !pRgn->GetSample()->GetCache().Size) {
460 schoenebeck 53 dmsg(2,("C"));
461 schoenebeck 947 CacheInitialSamples(pRgn->GetSample(), (gig::EngineChannel*) pConsumer);
462 schoenebeck 53 }
463     for (uint i = 0; i < pRgn->DimensionRegions; i++) {
464 schoenebeck 947 CacheInitialSamples(pRgn->pDimensionRegions[i]->pSample, (gig::EngineChannel*) pConsumer);
465 schoenebeck 53 }
466    
467     pRgn = pInstrument->GetNextRegion();
468 schoenebeck 517 iRegion++;
469 schoenebeck 53 }
470     dmsg(1,("OK\n"));
471 schoenebeck 517 DispatchResourceProgressEvent(Key, 1.0f); // done; notify all consumers about progress 100%
472 schoenebeck 53
473     // we need the following for destruction later
474     instr_entry_t* pEntry = new instr_entry_t;
475 schoenebeck 947 pEntry->ID.FileName = Key.FileName;
476     pEntry->ID.Index = Key.Index;
477 schoenebeck 53 pEntry->pGig = pGig;
478 persson 438
479 schoenebeck 1212 gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(pConsumer);
480 schoenebeck 411 // and we save this to check if we need to reallocate for a engine with higher value of 'MaxSamplesPerSecond'
481     pEntry->MaxSamplesPerCycle =
482 schoenebeck 1212 (!pEngineChannel) ? 0 /* don't care for instrument editors */ :
483     (pEngineChannel->GetEngine()) ?
484     dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()
485     : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;
486 schoenebeck 53 pArg = pEntry;
487    
488     return pInstrument;
489     }
490    
491     void InstrumentResourceManager::Destroy( ::gig::Instrument* pResource, void* pArg) {
492     instr_entry_t* pEntry = (instr_entry_t*) pArg;
493 schoenebeck 947 // we don't need the .gig file here anymore
494     Gigs.HandBack(pEntry->pGig, (GigConsumer*) pEntry->ID.Index); // conversion kinda hackish :/
495 schoenebeck 53 delete pEntry;
496     }
497    
498     void InstrumentResourceManager::OnBorrow(::gig::Instrument* pResource, InstrumentConsumer* pConsumer, void*& pArg) {
499     instr_entry_t* pEntry = (instr_entry_t*) pArg;
500 schoenebeck 411 gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(pConsumer);
501     uint maxSamplesPerCycle =
502 schoenebeck 1212 (pEngineChannel && pEngineChannel->GetEngine()) ? dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()
503 schoenebeck 411 : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;
504     if (pEntry->MaxSamplesPerCycle < maxSamplesPerCycle) {
505 schoenebeck 53 Update(pResource, pConsumer);
506     }
507     }
508    
509     /**
510 persson 1038 * Give back an instrument. This should be used instead of
511     * HandBack if there are some dimension regions that are still in
512     * use. (When an instrument is changed, the voices currently
513 persson 1646 * playing are allowed to keep playing with the old instrument
514 persson 1038 * until note off arrives. New notes will use the new instrument.)
515     */
516     void InstrumentResourceManager::HandBackInstrument(::gig::Instrument* pResource, InstrumentConsumer* pConsumer,
517 persson 1646 RTList< ::gig::DimensionRegion*>* pDimRegionsInUse) {
518 persson 1038 DimRegInfoMutex.Lock();
519 persson 1646 for (RTList< ::gig::DimensionRegion*>::Iterator i = pDimRegionsInUse->first() ; i != pDimRegionsInUse->end() ; i++) {
520     DimRegInfo[*i].refCount++;
521     SampleRefCount[(*i)->pSample]++;
522 persson 1038 }
523     HandBack(pResource, pConsumer, true);
524     DimRegInfoMutex.Unlock();
525     }
526    
527     /**
528     * Give back a dimension region that belongs to an instrument that
529     * was previously handed back.
530     */
531     void InstrumentResourceManager::HandBackDimReg(::gig::DimensionRegion* pDimReg) {
532     DimRegInfoMutex.Lock();
533     dimreg_info_t& dimRegInfo = DimRegInfo[pDimReg];
534     int dimRegRefCount = --dimRegInfo.refCount;
535     int sampleRefCount = --SampleRefCount[pDimReg->pSample];
536     if (dimRegRefCount == 0) {
537     ::gig::File* gig = dimRegInfo.file;
538     ::RIFF::File* riff = dimRegInfo.riff;
539     DimRegInfo.erase(pDimReg);
540     // TODO: we could delete Region and Instrument here if
541     // they have become unused
542    
543     if (sampleRefCount == 0) {
544     SampleRefCount.erase(pDimReg->pSample);
545    
546     if (gig) {
547     gig->DeleteSample(pDimReg->pSample);
548     if (!gig->GetFirstSample()) {
549     dmsg(2,("No more samples in use - freeing gig\n"));
550     delete gig;
551     delete riff;
552     }
553     }
554     }
555     }
556     DimRegInfoMutex.Unlock();
557     }
558    
559     /**
560 schoenebeck 1321 * Just a wrapper around the other @c CacheInitialSamples() method.
561     *
562     * @param pSample - points to the sample to be cached
563     * @param pEngine - pointer to Gig Engine Channel which caused this call
564     * (may be NULL, in this case default amount of samples
565     * will be cached)
566     */
567     void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::EngineChannel* pEngineChannel) {
568     gig::Engine* pEngine =
569     (pEngineChannel && pEngineChannel->GetEngine()) ?
570     dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine()) : NULL;
571     CacheInitialSamples(pSample, pEngine);
572     }
573    
574     /**
575 schoenebeck 53 * Caches a certain size at the beginning of the given sample in RAM. If the
576     * sample is very short, the whole sample will be loaded into RAM and thus
577     * no disk streaming is needed for this sample. Caching an initial part of
578     * samples is needed to compensate disk reading latency.
579     *
580     * @param pSample - points to the sample to be cached
581 schoenebeck 1321 * @param pEngine - pointer to Gig Engine which caused this call
582     * (may be NULL, in this case default amount of samples
583     * will be cached)
584 schoenebeck 53 */
585 schoenebeck 1321 void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::Engine* pEngine) {
586 schoenebeck 420 if (!pSample) {
587 persson 438 dmsg(4,("gig::InstrumentResourceManager: Skipping sample (pSample == NULL)\n"));
588 schoenebeck 420 return;
589     }
590     if (!pSample->SamplesTotal) return; // skip zero size samples
591 persson 438
592 schoenebeck 554 if (pSample->SamplesTotal <= CONFIG_PRELOAD_SAMPLES) {
593 schoenebeck 53 // Sample is too short for disk streaming, so we load the whole
594 schoenebeck 554 // sample into RAM and place 'pAudioIO->FragmentSize << CONFIG_MAX_PITCH'
595 schoenebeck 53 // number of '0' samples (silence samples) behind the official buffer
596     // border, to allow the interpolator do it's work even at the end of
597 persson 438 // the sample.
598 schoenebeck 411 const uint maxSamplesPerCycle =
599 schoenebeck 1321 (pEngine) ? pEngine->pAudioOutputDevice->MaxSamplesPerCycle()
600     : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;
601 schoenebeck 554 const uint neededSilenceSamples = (maxSamplesPerCycle << CONFIG_MAX_PITCH) + 3;
602 schoenebeck 420 const uint currentlyCachedSilenceSamples = pSample->GetCache().NullExtensionSize / pSample->FrameSize;
603     if (currentlyCachedSilenceSamples < neededSilenceSamples) {
604     dmsg(3,("Caching whole sample (sample name: \"%s\", sample size: %d)\n", pSample->pInfo->Name.c_str(), pSample->SamplesTotal));
605     ::gig::buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(neededSilenceSamples);
606     dmsg(4,("Cached %d Bytes, %d silence bytes.\n", buf.Size, buf.NullExtensionSize));
607     }
608 schoenebeck 53 }
609 schoenebeck 554 else { // we only cache CONFIG_PRELOAD_SAMPLES and stream the other sample points from disk
610     if (!pSample->GetCache().Size) pSample->LoadSampleData(CONFIG_PRELOAD_SAMPLES);
611 schoenebeck 53 }
612    
613     if (!pSample->GetCache().Size) std::cerr << "Unable to cache sample - maybe memory full!" << std::endl << std::flush;
614     }
615    
616 schoenebeck 1321 void InstrumentResourceManager::UncacheInitialSamples(::gig::Sample* pSample) {
617     dmsg(1,("Uncaching sample %x\n",pSample));
618     if (pSample->GetCache().Size) pSample->ReleaseSampleData();
619     }
620 schoenebeck 53
621 schoenebeck 1321 /**
622     * Returns a list with all instruments currently in use, that are part of
623     * the given file.
624     *
625     * @param pFile - search criteria
626     * @param bLock - whether we should lock (mutex) the instrument manager
627     * during this call and unlock at the end of this call
628     */
629     std::vector< ::gig::Instrument*> InstrumentResourceManager::GetInstrumentsCurrentlyUsedOf(::gig::File* pFile, bool bLock) {
630     if (bLock) Lock();
631     std::vector< ::gig::Instrument*> result;
632     std::vector< ::gig::Instrument*> allInstruments = Resources(false/*don't lock again*/);
633     for (int i = 0; i < allInstruments.size(); i++)
634     if (
635     (::gig::File*) allInstruments[i]->GetParent()
636     == pFile
637     ) result.push_back(allInstruments[i]);
638     if (bLock) Unlock();
639     return result;
640     }
641 schoenebeck 53
642 schoenebeck 1321 /**
643     * Returns a list with all gig Engines that are currently using the given
644     * instrument.
645     *
646     * @param pInstrument - search criteria
647     * @param bLock - whether we should lock (mutex) the instrument manager
648     * during this call and unlock at the end of this call
649     */
650     std::set<gig::Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::Instrument* pInstrument, bool bLock) {
651     if (bLock) Lock();
652     std::set<gig::Engine*> result;
653     std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(pInstrument);
654     std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
655     std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end = consumers.end();
656     for (; iter != end; ++iter) {
657     gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(*iter);
658     if (!pEngineChannel) continue;
659     gig::Engine* pEngine = dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine());
660     if (!pEngine) continue;
661     result.insert(pEngine);
662     }
663     if (bLock) Unlock();
664     return result;
665     }
666    
667     /**
668     * Returns a list with all gig Engines that are currently using an
669     * instrument that is part of the given instrument file.
670     *
671     * @param pFile - search criteria
672     * @param bLock - whether we should lock (mutex) the instrument manager
673     * during this call and unlock at the end of this call
674     */
675     std::set<gig::Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::File* pFile, bool bLock) {
676     if (bLock) Lock();
677     // get all instruments (currently in usage) that use that same gig::File
678     std::vector< ::gig::Instrument*> instrumentsOfInterest =
679     GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
680    
681     // get all engines that use that same gig::File
682     std::set<gig::Engine*> result;
683     {
684     for (int i = 0; i < instrumentsOfInterest.size(); i++) {
685     std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(instrumentsOfInterest[i]);
686     std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
687     std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end = consumers.end();
688     for (; iter != end; ++iter) {
689     gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(*iter);
690     if (!pEngineChannel) continue;
691     gig::Engine* pEngine = dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine());
692     if (!pEngine) continue;
693     // the unique, sorted container std::set makes
694     // sure we won't have duplicates
695     result.insert(pEngine);
696     }
697     }
698     }
699     if (bLock) Unlock();
700     return result;
701     }
702    
703     /**
704     * Returns @c true in case the given sample is referenced somewhere by the
705     * given instrument, @c false otherwise.
706     *
707     * @param pSample - sample reference
708     * @param pInstrument - instrument that might use that sample
709     */
710     bool InstrumentResourceManager::SampleReferencedByInstrument(::gig::Sample* pSample, ::gig::Instrument* pInstrument) {
711     for (
712     ::gig::Region* pRegion = pInstrument->GetFirstRegion();
713     pRegion; pRegion = pInstrument->GetNextRegion()
714     ) {
715     for (
716     int i = 0; i < pRegion->DimensionRegions &&
717     pRegion->pDimensionRegions[i]; i++
718     ) {
719     if (pRegion->pDimensionRegions[i]->pSample == pSample)
720     return true;
721     }
722     }
723     return false;
724     }
725    
726     /**
727     * Suspend all gig engines that use the given instrument. This means
728     * completely stopping playback on those engines and killing all their
729     * voices and disk streams. This method will block until all voices AND
730     * their disk streams are finally deleted and the engine turned into a
731     * complete idle loop.
732     *
733     * All @c SuspendEnginesUsing() methods only serve one thread by one and
734     * block all other threads until the current active thread called
735     * @c ResumeAllEngines() .
736     *
737     * @param pInstrument - search criteria
738     */
739     void InstrumentResourceManager::SuspendEnginesUsing(::gig::Instrument* pInstrument) {
740     // make sure no other thread suspends whole engines at the same time
741     suspendedEnginesMutex.Lock();
742     // get all engines that use that same gig::Instrument
743     suspendedEngines = GetEnginesUsing(pInstrument, true/*lock*/);
744     // finally, completely suspend all engines that use that same gig::Instrument
745     std::set<gig::Engine*>::iterator iter = suspendedEngines.begin();
746     std::set<gig::Engine*>::iterator end = suspendedEngines.end();
747     for (; iter != end; ++iter) (*iter)->SuspendAll();
748     }
749    
750     /**
751     * Suspend all gig engines that use the given instrument file. This means
752     * completely stopping playback on those engines and killing all their
753     * voices and disk streams. This method will block until all voices AND
754     * their disk streams are finally deleted and the engine turned into a
755     * complete idle loop.
756     *
757     * All @c SuspendEnginesUsing() methods only serve one thread by one and
758     * block all other threads until the current active thread called
759     * @c ResumeAllEngines() .
760     *
761     * @param pFile - search criteria
762     */
763     void InstrumentResourceManager::SuspendEnginesUsing(::gig::File* pFile) {
764     // make sure no other thread suspends whole engines at the same time
765     suspendedEnginesMutex.Lock();
766     // get all engines that use that same gig::File
767     suspendedEngines = GetEnginesUsing(pFile, true/*lock*/);
768     // finally, completely suspend all engines that use that same gig::File
769     std::set<gig::Engine*>::iterator iter = suspendedEngines.begin();
770     std::set<gig::Engine*>::iterator end = suspendedEngines.end();
771     for (; iter != end; ++iter) (*iter)->SuspendAll();
772     }
773    
774     /**
775     * MUST be called after one called one of the @c SuspendEnginesUsing()
776     * methods, to resume normal playback on all previously suspended engines.
777     * As it's only possible for one thread to suspend whole engines at the
778     * same time, this method doesn't take any arguments.
779     */
780     void InstrumentResourceManager::ResumeAllEngines() {
781     // resume all previously completely suspended engines
782     std::set<Engine*>::iterator iter = suspendedEngines.begin();
783     std::set<Engine*>::iterator end = suspendedEngines.end();
784     for (; iter != end; ++iter) (*iter)->ResumeAll();
785     // no more suspended engines ...
786     suspendedEngines.clear();
787     // allow another thread to suspend whole engines
788     suspendedEnginesMutex.Unlock();
789     }
790    
791    
792    
793 schoenebeck 53 // internal gig file manager
794    
795     ::gig::File* InstrumentResourceManager::GigResourceManager::Create(String Key, GigConsumer* pConsumer, void*& pArg) {
796     dmsg(1,("Loading gig file \'%s\'...", Key.c_str()));
797     ::RIFF::File* pRIFF = new ::RIFF::File(Key);
798     ::gig::File* pGig = new ::gig::File(pRIFF);
799     pArg = pRIFF;
800     dmsg(1,("OK\n"));
801     return pGig;
802     }
803    
804     void InstrumentResourceManager::GigResourceManager::Destroy(::gig::File* pResource, void* pArg) {
805     dmsg(1,("Freeing gig file from memory..."));
806 persson 1038
807     // Delete as much as possible of the gig file. Some of the
808     // dimension regions and samples may still be in use - these
809     // will be deleted later by the HandBackDimReg function.
810     bool deleteFile = true;
811     ::gig::Instrument* nextInstrument;
812     for (::gig::Instrument* instrument = pResource->GetFirstInstrument() ;
813     instrument ;
814     instrument = nextInstrument) {
815     nextInstrument = pResource->GetNextInstrument();
816     bool deleteInstrument = true;
817     ::gig::Region* nextRegion;
818     for (::gig::Region *region = instrument->GetFirstRegion() ;
819     region ;
820     region = nextRegion) {
821     nextRegion = instrument->GetNextRegion();
822     bool deleteRegion = true;
823     for (int i = 0 ; i < region->DimensionRegions ; i++)
824     {
825     ::gig::DimensionRegion *d = region->pDimensionRegions[i];
826     std::map< ::gig::DimensionRegion*, dimreg_info_t>::iterator iter = parent->DimRegInfo.find(d);
827     if (iter != parent->DimRegInfo.end()) {
828     dimreg_info_t& dimRegInfo = (*iter).second;
829     dimRegInfo.file = pResource;
830     dimRegInfo.riff = (::RIFF::File*)pArg;
831     deleteFile = deleteInstrument = deleteRegion = false;
832     }
833     }
834     if (deleteRegion) instrument->DeleteRegion(region);
835     }
836     if (deleteInstrument) pResource->DeleteInstrument(instrument);
837     }
838     if (deleteFile) {
839     delete pResource;
840     delete (::RIFF::File*) pArg;
841     } else {
842     dmsg(2,("keeping some samples that are in use..."));
843     ::gig::Sample* nextSample;
844     for (::gig::Sample* sample = pResource->GetFirstSample() ;
845     sample ;
846     sample = nextSample) {
847     nextSample = pResource->GetNextSample();
848     if (parent->SampleRefCount.find(sample) == parent->SampleRefCount.end()) {
849     pResource->DeleteSample(sample);
850     }
851     }
852     }
853 schoenebeck 53 dmsg(1,("OK\n"));
854     }
855    
856     }} // namespace LinuxSampler::gig

  ViewVC Help
Powered by ViewVC