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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 4009 - (show annotations) (download)
Wed Dec 22 15:01:44 2021 UTC (2 years, 3 months ago) by schoenebeck
File size: 48904 byte(s)
* Show a more detailed error message on terminal if an appropriate editor
  could not be found for a .gig instrument.

* Bumped version (2.2.0.svn8).

1
2 /***************************************************************************
3 * *
4 * LinuxSampler - modular, streaming capable sampler *
5 * *
6 * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck *
7 * Copyright (C) 2005 - 2021 Christian Schoenebeck *
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 * This program is distributed in the hope that it will be useful, *
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
17 * GNU General Public License for more details. *
18 * *
19 * You should have received a copy of the GNU General Public License *
20 * along with this program; if not, write to the Free Software *
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
22 * MA 02111-1307 USA *
23 ***************************************************************************/
24
25 #include <sstream>
26
27 #include "InstrumentResourceManager.h"
28 #include "EngineChannel.h"
29 #include "Engine.h"
30
31 #include "../../common/global_private.h"
32 #include "../../plugins/InstrumentEditorFactory.h"
33
34 namespace LinuxSampler { namespace gig {
35
36 // some data needed for the libgig callback function
37 struct progress_callback_arg_t {
38 InstrumentResourceManager* pManager;
39 InstrumentManager::instrument_id_t* pInstrumentKey;
40 };
41
42 // we use this to react on events concerning an instrument on behalf of an instrument editor
43 class InstrumentEditorProxy : public InstrumentConsumer {
44 public:
45 virtual ~InstrumentEditorProxy() {}
46
47 virtual void ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {
48 //TODO: inform the instrument editor about the pending update
49 }
50
51 virtual void ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {
52 //TODO:: inform the instrument editor about finished update
53 }
54
55 virtual void OnResourceProgress(float fProgress) {
56 //TODO: inform the instrument editor about the progress of an update
57 }
58
59 // the instrument we borrowed on behalf of the editor
60 ::gig::Instrument* pInstrument;
61 // the instrument editor we work on behalf
62 InstrumentEditor* pEditor;
63 };
64
65 /**
66 * Callback function which will be called by libgig during loading of
67 * instruments to inform about the current progress. Or to be more
68 * specific; it will be called during the GetInstrument() call.
69 *
70 * @param pProgress - contains current progress value, pointer to the
71 * InstrumentResourceManager instance and
72 * instrument ID
73 */
74 void InstrumentResourceManager::OnInstrumentLoadingProgress(::gig::progress_t* pProgress) {
75 dmsg(7,("gig::InstrumentResourceManager: progress %f%%", pProgress->factor));
76 progress_callback_arg_t* pArg = static_cast<progress_callback_arg_t*>(pProgress->custom);
77 // we randomly schedule 90% for the .gig file loading and the remaining 10% later for sample caching
78 const float localProgress = 0.9f * pProgress->factor;
79 pArg->pManager->DispatchResourceProgressEvent(*pArg->pInstrumentKey, localProgress);
80 }
81
82 String InstrumentResourceManager::GetInstrumentName(instrument_id_t ID) {
83 Lock();
84 ::gig::Instrument* pInstrument = Resource(ID, false);
85 String res = (pInstrument) ? pInstrument->pInfo->Name : "";
86 Unlock();
87 return res;
88 }
89
90 String InstrumentResourceManager::GetInstrumentDataStructureName(instrument_id_t ID) {
91 return ::gig::libraryName();
92 }
93
94 String InstrumentResourceManager::GetInstrumentDataStructureVersion(instrument_id_t ID) {
95 return ::gig::libraryVersion();
96 }
97
98 std::vector<InstrumentResourceManager::instrument_id_t> InstrumentResourceManager::GetInstrumentFileContent(String File) throw (InstrumentManagerException) {
99 ::RIFF::File* riff = NULL;
100 ::gig::File* gig = NULL;
101 try {
102 std::vector<instrument_id_t> result;
103 riff = new ::RIFF::File(File);
104 gig = new ::gig::File(riff);
105 gig->SetAutoLoad(false); // avoid time consuming samples scanning
106 for (int i = 0; gig->GetInstrument(i); i++) {
107 instrument_id_t id;
108 id.FileName = File;
109 id.Index = i;
110 result.push_back(id);
111 }
112 if (gig) delete gig;
113 if (riff) delete riff;
114 return result;
115 } catch (::RIFF::Exception e) {
116 if (gig) delete gig;
117 if (riff) delete riff;
118 throw InstrumentManagerException(e.Message);
119 } catch (...) {
120 if (gig) delete gig;
121 if (riff) delete riff;
122 throw InstrumentManagerException("Unknown exception while trying to parse '" + File + "'");
123 }
124 }
125
126 InstrumentResourceManager::instrument_info_t InstrumentResourceManager::GetInstrumentInfo(instrument_id_t ID) throw (InstrumentManagerException) {
127 Lock();
128 ::gig::Instrument* pInstrument = Resource(ID, false);
129 bool loaded = (pInstrument != NULL);
130 if (!loaded) Unlock();
131
132 ::RIFF::File* riff = NULL;
133 ::gig::File* gig = NULL;
134 try {
135 if (!loaded) {
136 riff = new ::RIFF::File(ID.FileName);
137 gig = new ::gig::File(riff);
138 gig->SetAutoLoad(false); // avoid time consuming samples scanning
139 pInstrument = gig->GetInstrument(ID.Index);
140 }
141
142 if (!pInstrument) throw InstrumentManagerException("There is no instrument " + ToString(ID.Index) + " in " + ID.FileName);
143
144 instrument_info_t info;
145 for (int i = 0; i < 128; i++) { info.KeyBindings[i] = info.KeySwitchBindings[i] = 0; }
146
147 ::gig::File* pFile = (::gig::File*) pInstrument->GetParent();
148
149 if (pFile->pVersion) {
150 info.FormatVersion = ToString(pFile->pVersion->major);
151 info.Product = pFile->pInfo->Product;
152 info.Artists = pFile->pInfo->Artists;
153 }
154
155 info.InstrumentName = pInstrument->pInfo->Name;
156
157 size_t iRgn = 0;
158 for (::gig::Region* pRegion = pInstrument->GetRegionAt(iRgn);
159 pRegion; pRegion = pInstrument->GetRegionAt(++iRgn))
160 {
161 int low = pRegion->KeyRange.low;
162 int high = pRegion->KeyRange.high;
163 if (low < 0 || low > 127 || high < 0 || high > 127 || low > high) {
164 std::cerr << "Invalid key range: " << low << " - " << high << std::endl;
165 } else {
166 for (int i = low; i <= high; i++) info.KeyBindings[i] = 1;
167 }
168 }
169
170 if (loaded) { // retrieve keyswitching only if the instrument is fully loaded.
171
172 // only return keyswitch range if keyswitching is used
173 bool hasKeyswitches = false;
174 size_t iRgn = 0;
175 for (::gig::Region* pRegion = pInstrument->GetRegionAt(iRgn);
176 pRegion && !hasKeyswitches ;
177 pRegion = pInstrument->GetRegionAt(++iRgn))
178 {
179 for (int i = 0 ; i < pRegion->Dimensions ; i++) {
180 if (pRegion->pDimensionDefinitions[i].dimension == ::gig::dimension_keyboard) {
181 hasKeyswitches = true;
182 break;
183 }
184 }
185 }
186
187 if (hasKeyswitches) {
188 int low = pInstrument->DimensionKeyRange.low;
189 int high = pInstrument->DimensionKeyRange.high;
190 if (low < 0 || low > 127 || high < 0 || high > 127 || low > high) {
191 std::cerr << "Invalid keyswitch range: " << low << " - " << high << std::endl;
192 } else {
193 for (int i = low; i <= high; i++) info.KeySwitchBindings[i] = 1;
194 }
195 }
196 }
197
198 if (loaded) Unlock();
199
200 if (gig) delete gig;
201 if (riff) delete riff;
202 return info;
203 } catch (::RIFF::Exception e) {
204 if (loaded) Unlock();
205 if (gig) delete gig;
206 if (riff) delete riff;
207 throw InstrumentManagerException(e.Message);
208 } catch (...) {
209 if (loaded) Unlock();
210 if (gig) delete gig;
211 if (riff) delete riff;
212 throw InstrumentManagerException("Unknown exception while trying to parse '" + ID.FileName + "'");
213 }
214 }
215
216 InstrumentEditor* InstrumentResourceManager::LaunchInstrumentEditor(LinuxSampler::EngineChannel* pEngineChannel, instrument_id_t ID, void* pUserData) throw (InstrumentManagerException) {
217 const String sDataType = GetInstrumentDataStructureName(ID);
218 const String sDataVersion = GetInstrumentDataStructureVersion(ID);
219 // find instrument editors capable to handle given instrument
220 std::vector<String> vEditors =
221 InstrumentEditorFactory::MatchingEditors(sDataType, sDataVersion);
222 if (!vEditors.size()) {
223 fprintf(stderr,
224 "ERROR: Did not find a matching editor for instrument "
225 "('%s', %d) having data structure ('%s','%s')\n",
226 ID.FileName.c_str(), ID.Index,
227 sDataType.c_str(), sDataVersion.c_str()
228 );
229 throw InstrumentManagerException(
230 "There is no instrument editor capable to handle this instrument"
231 );
232 }
233 // simply use the first editor in the result set
234 dmsg(1,("Found matching editor '%s' for instrument ('%s', %d) having data structure ('%s','%s')\n",
235 vEditors[0].c_str(), ID.FileName.c_str(), ID.Index, sDataType.c_str(), sDataVersion.c_str()));
236 InstrumentEditor* pEditor = InstrumentEditorFactory::Create(vEditors[0]);
237 // register for receiving notifications from the instrument editor
238 pEditor->AddListener(this);
239 // create a proxy that reacts on notification on behalf of the editor
240 InstrumentEditorProxy* pProxy = new InstrumentEditorProxy;
241 // borrow the instrument on behalf of the instrument editor
242 ::gig::Instrument* pInstrument = Borrow(ID, pProxy);
243 // remember the proxy and instrument for this instrument editor
244 pProxy->pInstrument = pInstrument;
245 pProxy->pEditor = pEditor;
246 InstrumentEditorProxiesMutex.Lock();
247 InstrumentEditorProxies.add(pProxy);
248 InstrumentEditorProxiesMutex.Unlock();
249 // launch the instrument editor for the given instrument
250 pEditor->Launch(pEngineChannel, pInstrument, sDataType, sDataVersion, pUserData);
251
252 // register the instrument editor as virtual MIDI device as well ...
253 VirtualMidiDevice* pVirtualMidiDevice =
254 dynamic_cast<VirtualMidiDevice*>(pEditor);
255 if (!pVirtualMidiDevice) {
256 std::cerr << "Instrument editor not a virtual MIDI device\n" << std::flush;
257 return pEditor;
258 }
259 // 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 ? )
260 Lock();
261 std::set<EngineChannel*> engineChannels =
262 GetEngineChannelsUsing(pInstrument, false/*don't lock again*/);
263 std::set<EngineChannel*>::iterator iter = engineChannels.begin();
264 std::set<EngineChannel*>::iterator end = engineChannels.end();
265 for (; iter != end; ++iter) (static_cast<AbstractEngineChannel*>(*iter))->Connect(pVirtualMidiDevice);
266 Unlock();
267
268 return pEditor;
269 }
270
271 /**
272 * Will be called by the respective instrument editor once it left its
273 * Main() loop. That way we can handle cleanup before its thread finally
274 * dies.
275 *
276 * @param pSender - instrument editor that stops execution
277 */
278 void InstrumentResourceManager::OnInstrumentEditorQuit(InstrumentEditor* pSender) {
279 dmsg(1,("InstrumentResourceManager: instrument editor quit, doing cleanup\n"));
280
281 ::gig::Instrument* pInstrument = NULL;
282 InstrumentEditorProxy* pProxy = NULL;
283 int iProxyIndex = -1;
284
285 // first find the editor proxy entry for this editor
286 {
287 LockGuard lock(InstrumentEditorProxiesMutex);
288 for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
289 InstrumentEditorProxy* pCurProxy =
290 dynamic_cast<InstrumentEditorProxy*>(
291 InstrumentEditorProxies[i]
292 );
293 if (pCurProxy->pEditor == pSender) {
294 pProxy = pCurProxy;
295 iProxyIndex = i;
296 pInstrument = pCurProxy->pInstrument;
297 }
298 }
299 }
300
301 if (!pProxy) {
302 std::cerr << "Eeeek, could not find instrument editor proxy, "
303 "this is a bug!\n" << std::flush;
304 return;
305 }
306
307 // now unregister editor as not being available as a virtual MIDI device anymore
308 VirtualMidiDevice* pVirtualMidiDevice =
309 dynamic_cast<VirtualMidiDevice*>(pSender);
310 if (pVirtualMidiDevice) {
311 Lock();
312 // NOTE: see note in LaunchInstrumentEditor()
313 std::set<EngineChannel*> engineChannels =
314 GetEngineChannelsUsing(pInstrument, false/*don't lock again*/);
315 std::set<EngineChannel*>::iterator iter = engineChannels.begin();
316 std::set<EngineChannel*>::iterator end = engineChannels.end();
317 for (; iter != end; ++iter) (*iter)->Disconnect(pVirtualMidiDevice);
318 Unlock();
319 } else {
320 std::cerr << "Could not unregister editor as not longer acting as "
321 "virtual MIDI device. Wasn't it registered?\n"
322 << std::flush;
323 }
324
325 // finally delete proxy entry and hand back instrument
326 if (pInstrument) {
327 {
328 LockGuard lock(InstrumentEditorProxiesMutex);
329 InstrumentEditorProxies.remove(iProxyIndex);
330 }
331
332 HandBack(pInstrument, pProxy);
333 delete pProxy;
334 }
335
336 // Note that we don't need to free the editor here. As it
337 // derives from Thread, it will delete itself when the thread
338 // dies.
339 }
340
341 #if 0 // currently unused :
342 /**
343 * Try to inform the respective instrument editor(s), that a note on
344 * event just occured. This method is called by the MIDI thread. If any
345 * obstacles are in the way (e.g. if a wait for an unlock would be
346 * required) we give up immediately, since the RT safeness of the MIDI
347 * thread has absolute priority.
348 */
349 void InstrumentResourceManager::TrySendNoteOnToEditors(uint8_t Key, uint8_t Velocity, ::gig::Instrument* pInstrument) {
350 const bool bGotLock = InstrumentEditorProxiesMutex.Trylock(); // naively assumes RT safe implementation
351 if (!bGotLock) return; // hell, forget it, not worth the hassle
352 for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
353 InstrumentEditorProxy* pProxy =
354 dynamic_cast<InstrumentEditorProxy*>(
355 InstrumentEditorProxies[i]
356 );
357 if (pProxy->pInstrument == pInstrument)
358 pProxy->pEditor->SendNoteOnToDevice(Key, Velocity);
359 }
360 InstrumentEditorProxiesMutex.Unlock(); // naively assumes RT safe implementation
361 }
362
363 /**
364 * Try to inform the respective instrument editor(s), that a note off
365 * event just occured. This method is called by the MIDI thread. If any
366 * obstacles are in the way (e.g. if a wait for an unlock would be
367 * required) we give up immediately, since the RT safeness of the MIDI
368 * thread has absolute priority.
369 */
370 void InstrumentResourceManager::TrySendNoteOffToEditors(uint8_t Key, uint8_t Velocity, ::gig::Instrument* pInstrument) {
371 const bool bGotLock = InstrumentEditorProxiesMutex.Trylock(); // naively assumes RT safe implementation
372 if (!bGotLock) return; // hell, forget it, not worth the hassle
373 for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
374 InstrumentEditorProxy* pProxy =
375 dynamic_cast<InstrumentEditorProxy*>(
376 InstrumentEditorProxies[i]
377 );
378 if (pProxy->pInstrument == pInstrument)
379 pProxy->pEditor->SendNoteOffToDevice(Key, Velocity);
380 }
381 InstrumentEditorProxiesMutex.Unlock(); // naively assumes RT safe implementation
382 }
383 #endif // unused
384
385 void InstrumentResourceManager::OnSamplesToBeRemoved(std::set<void*> Samples, InstrumentEditor* pSender) {
386 if (Samples.empty()) {
387 std::cerr << "gig::InstrumentResourceManager: WARNING, "
388 "OnSamplesToBeRemoved() called with empty list, this "
389 "is a bug!\n" << std::flush;
390 return;
391 }
392 // TODO: ATM we assume here that all samples are from the same file
393 ::gig::Sample* pFirstSample = (::gig::Sample*) *Samples.begin();
394 ::gig::File* pCriticalFile = dynamic_cast< ::gig::File*>(pFirstSample->GetParent());
395 // completely suspend all engines that use that same file
396 SuspendEnginesUsing(pCriticalFile);
397 }
398
399 void InstrumentResourceManager::OnSamplesRemoved(InstrumentEditor* pSender) {
400 // resume all previously, completely suspended engines
401 // (we don't have to un-cache the removed samples here, since that is
402 // automatically done by the gig::Sample destructor)
403 ResumeAllEngines();
404 }
405
406 void InstrumentResourceManager::OnDataStructureToBeChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {
407 dmsg(5,("gig::InstrumentResourceManager::OnDataStructureToBeChanged(%s)\n", sStructType.c_str()));
408 //TODO: remove code duplication
409 if (sStructType == "gig::File") {
410 // completely suspend all engines that use that file
411 ::gig::File* pFile = (::gig::File*) pStruct;
412 SuspendEnginesUsing(pFile);
413 } else if (sStructType == "gig::Instrument") {
414 // completely suspend all engines that use that instrument
415 ::gig::Instrument* pInstrument = (::gig::Instrument*) pStruct;
416 SuspendEnginesUsing(pInstrument);
417 } else if (sStructType == "gig::Region") {
418 // only advice the engines to suspend the given region, so they'll
419 // only ignore that region (and probably already other suspended
420 // ones), but beside that continue normal playback
421 ::gig::Region* pRegion = (::gig::Region*) pStruct;
422 ::gig::Instrument* pInstrument =
423 (::gig::Instrument*) pRegion->GetParent();
424 Lock();
425 std::set<Engine*> engines =
426 GetEnginesUsing(pInstrument, false/*don't lock again*/);
427 std::set<Engine*>::iterator iter = engines.begin();
428 std::set<Engine*>::iterator end = engines.end();
429 for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
430 Unlock();
431 } else if (sStructType == "gig::DimensionRegion") {
432 // only advice the engines to suspend the given DimensionRegions's
433 // parent region, so they'll only ignore that region (and probably
434 // already other suspended ones), but beside that continue normal
435 // playback
436 ::gig::DimensionRegion* pDimReg =
437 (::gig::DimensionRegion*) pStruct;
438 ::gig::Region* pRegion = pDimReg->GetParent();
439 ::gig::Instrument* pInstrument =
440 (::gig::Instrument*) pRegion->GetParent();
441 Lock();
442 std::set<Engine*> engines =
443 GetEnginesUsing(pInstrument, false/*don't lock again*/);
444 std::set<Engine*>::iterator iter = engines.begin();
445 std::set<Engine*>::iterator end = engines.end();
446 for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
447 Unlock();
448 } else if (sStructType == "gig::Script") {
449 // no need to suspend anything here, since the sampler is
450 // processing a translated VM representation of the original script
451 // source code, not accessing the source code itself during playback
452 ::gig::Script* pScript = (::gig::Script*) pStruct;
453 // remember the original source code of the script, since the script
454 // resource manager uses the source code as key
455 pendingScriptUpdatesMutex.Lock();
456 pendingScriptUpdates[pScript] = pScript->GetScriptAsText();
457 pendingScriptUpdatesMutex.Unlock();
458 } else {
459 std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
460 "structure '" << sStructType << "' requested to be "
461 "suspended by instrument editor. This is a bug!\n"
462 << std::flush;
463 //TODO: we should inform the instrument editor that something seriously went wrong
464 }
465 }
466
467 void InstrumentResourceManager::OnDataStructureChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {
468 dmsg(5,("gig::InstrumentResourceManager::OnDataStructureChanged(%s)\n", sStructType.c_str()));
469 //TODO: remove code duplication
470 if (sStructType == "gig::File") {
471 // resume all previously suspended engines
472 ResumeAllEngines();
473 } else if (sStructType == "gig::Instrument") {
474 // resume all previously suspended engines
475 ResumeAllEngines();
476 } else if (sStructType == "gig::Sample") {
477 // we're assuming here, that OnDataStructureToBeChanged() with
478 // "gig::File" was called previously, so we won't resume anything
479 // here, but just re-cache the given sample
480 Lock();
481 ::gig::Sample* pSample = (::gig::Sample*) pStruct;
482 ::gig::File* pFile = (::gig::File*) pSample->GetParent();
483 UncacheInitialSamples(pSample);
484 // now re-cache ...
485 std::vector< ::gig::Instrument*> instruments =
486 GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
487 for (int i = 0; i < instruments.size(); i++) {
488 if (SampleReferencedByInstrument(pSample, instruments[i])) {
489 std::set<EngineChannel*> engineChannels =
490 GetEngineChannelsUsing(instruments[i], false/*don't lock again*/);
491 std::set<EngineChannel*>::iterator iter = engineChannels.begin();
492 std::set<EngineChannel*>::iterator end = engineChannels.end();
493 for (; iter != end; ++iter)
494 CacheInitialSamples(pSample, *iter);
495 }
496 }
497 Unlock();
498 } else if (sStructType == "gig::Region") {
499 // advice the engines to resume the given region, that is to
500 // using it for playback again
501 ::gig::Region* pRegion = (::gig::Region*) pStruct;
502 ::gig::Instrument* pInstrument =
503 (::gig::Instrument*) pRegion->GetParent();
504 Lock();
505 std::set<Engine*> engines =
506 GetEnginesUsing(pInstrument, false/*don't lock again*/);
507 std::set<Engine*>::iterator iter = engines.begin();
508 std::set<Engine*>::iterator end = engines.end();
509 for (; iter != end; ++iter) (*iter)->Resume(pRegion);
510 Unlock();
511 } else if (sStructType == "gig::DimensionRegion") {
512 // advice the engines to resume the given DimensionRegion's parent
513 // region, that is to using it for playback again
514 ::gig::DimensionRegion* pDimReg =
515 (::gig::DimensionRegion*) pStruct;
516 ::gig::Region* pRegion = pDimReg->GetParent();
517 ::gig::Instrument* pInstrument =
518 (::gig::Instrument*) pRegion->GetParent();
519 Lock();
520 std::set<Engine*> engines =
521 GetEnginesUsing(pInstrument, false/*don't lock again*/);
522 std::set<Engine*>::iterator iter = engines.begin();
523 std::set<Engine*>::iterator end = engines.end();
524 for (; iter != end; ++iter) (*iter)->Resume(pRegion);
525 Unlock();
526 } else if (sStructType == "gig::Script") {
527 // inform all engine channels which are using this script, that
528 // they need to reload (parse) the script's source code text
529 ::gig::Script* pScript = (::gig::Script*) pStruct;
530 pendingScriptUpdatesMutex.Lock();
531 if (pendingScriptUpdates.count(pScript)) {
532 const String& code = pendingScriptUpdates[pScript];
533 std::set<EngineChannel*> channels = GetEngineChannelsUsingScriptSourceCode(code, true/*lock*/);
534 pendingScriptUpdates.erase(pScript);
535 std::set<EngineChannel*>::iterator iter = channels.begin();
536 std::set<EngineChannel*>::iterator end = channels.end();
537 for (; iter != end; ++iter) (*iter)->reloadScript(pScript);
538 }
539 pendingScriptUpdatesMutex.Unlock();
540 } else {
541 std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
542 "structure '" << sStructType << "' requested to be "
543 "resumed by instrument editor. This is a bug!\n"
544 << std::flush;
545 //TODO: we should inform the instrument editor that something seriously went wrong
546 }
547 }
548
549 void InstrumentResourceManager::OnSampleReferenceChanged(void* pOldSample, void* pNewSample, InstrumentEditor* pSender) {
550 // uncache old sample in case it's not used by anybody anymore
551 if (pOldSample) {
552 Lock();
553 ::gig::Sample* pSample = (::gig::Sample*) pOldSample;
554 ::gig::File* pFile = (::gig::File*) pSample->GetParent();
555 bool bSampleStillInUse = false;
556 std::vector< ::gig::Instrument*> instruments =
557 GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
558 for (int i = 0; i < instruments.size(); i++) {
559 if (SampleReferencedByInstrument(pSample, instruments[i])) {
560 bSampleStillInUse = true;
561 break;
562 }
563 }
564 if (!bSampleStillInUse) UncacheInitialSamples(pSample);
565 Unlock();
566 }
567 // make sure new sample reference is cached
568 if (pNewSample) {
569 Lock();
570 ::gig::Sample* pSample = (::gig::Sample*) pNewSample;
571 ::gig::File* pFile = (::gig::File*) pSample->GetParent();
572 // get all engines that use that same gig::File
573 std::set<Engine*> engines = GetEnginesUsing(pFile, false/*don't lock again*/);
574 std::set<Engine*>::iterator iter = engines.begin();
575 std::set<Engine*>::iterator end = engines.end();
576 for (; iter != end; ++iter)
577 CacheInitialSamples(pSample, *iter);
578 Unlock();
579 }
580 }
581
582 ::gig::Instrument* InstrumentResourceManager::Create(instrument_id_t Key, InstrumentConsumer* pConsumer, void*& pArg) {
583 // get gig file from internal gig file manager
584 ::gig::File* pGig = Gigs.Borrow(Key.FileName, reinterpret_cast<GigConsumer*>(Key.Index)); // conversion kinda hackish :/
585
586 // we pass this to the progress callback mechanism of libgig
587 progress_callback_arg_t callbackArg;
588 callbackArg.pManager = this;
589 callbackArg.pInstrumentKey = &Key;
590
591 ::gig::progress_t progress;
592 progress.callback = OnInstrumentLoadingProgress;
593 progress.custom = &callbackArg;
594
595 dmsg(1,("Loading gig instrument ('%s',%d)...",Key.FileName.c_str(),Key.Index));
596 ::gig::Instrument* pInstrument = pGig->GetInstrument(Key.Index, &progress);
597 if (!pInstrument) {
598 std::stringstream msg;
599 msg << "There's no instrument with index " << Key.Index << ".";
600 throw InstrumentManagerException(msg.str());
601 }
602 pGig->GetSample(0); // just to force complete instrument loading
603 dmsg(1,("OK\n"));
604
605 uint maxSamplesPerCycle = GetMaxSamplesPerCycle(pConsumer);
606
607 // cache initial samples points (for actually needed samples)
608 dmsg(1,("Caching initial samples..."));
609 size_t iRegion = 0;
610 for (::gig::Region* pRgn = pInstrument->GetRegionAt(iRegion); pRgn;
611 pRgn = pInstrument->GetRegionAt(++iRegion))
612 {
613 // we randomly schedule 90% for the .gig file loading and the remaining 10% now for sample caching
614 const float localProgress = 0.9f + 0.1f * (float) iRegion / (float) pInstrument->Regions;
615 DispatchResourceProgressEvent(Key, localProgress);
616
617 if (pRgn->GetSample() && !pRgn->GetSample()->GetCache().Size) {
618 dmsg(2,("C"));
619 CacheInitialSamples(pRgn->GetSample(), maxSamplesPerCycle);
620 }
621 for (uint i = 0; i < pRgn->DimensionRegions; i++) {
622 CacheInitialSamples(pRgn->pDimensionRegions[i]->pSample, maxSamplesPerCycle);
623 }
624 }
625 dmsg(1,("OK\n"));
626 DispatchResourceProgressEvent(Key, 1.0f); // done; notify all consumers about progress 100%
627
628 // we need the following for destruction later
629 instr_entry_t* pEntry = new instr_entry_t;
630 pEntry->ID.FileName = Key.FileName;
631 pEntry->ID.Index = Key.Index;
632 pEntry->pFile = pGig;
633
634 // and we save this to check if we need to reallocate for an engine with higher value of 'MaxSamplesPerSecond'
635 pEntry->MaxSamplesPerCycle = maxSamplesPerCycle;
636
637 pArg = pEntry;
638
639 return pInstrument;
640 }
641
642 void InstrumentResourceManager::Destroy(::gig::Instrument* pResource, void* pArg) {
643 instr_entry_t* pEntry = (instr_entry_t*) pArg;
644 // we don't need the .gig file here anymore
645 Gigs.HandBack(pEntry->pFile, reinterpret_cast<GigConsumer*>(pEntry->ID.Index)); // conversion kinda hackish :/
646 delete pEntry;
647 }
648
649 void InstrumentResourceManager::DeleteRegionIfNotUsed(::gig::DimensionRegion* pRegion, region_info_t* pRegInfo) {
650 // TODO: we could delete Region and Instrument here if they have become unused
651 }
652
653 void InstrumentResourceManager::DeleteSampleIfNotUsed(::gig::Sample* pSample, region_info_t* pRegInfo) {
654 ::gig::File* gig = pRegInfo->file;
655 ::RIFF::File* riff = static_cast< ::RIFF::File*>(pRegInfo->pArg);
656 if (gig) {
657 gig->DeleteSample(pSample);
658 if (!gig->GetSample(0)) {
659 dmsg(2,("No more samples in use - freeing gig\n"));
660 delete gig;
661 delete riff;
662 }
663 }
664 }
665
666 /**
667 * Just a wrapper around the other @c CacheInitialSamples() method.
668 *
669 * @param pSample - points to the sample to be cached
670 * @param pEngine - pointer to Gig Engine Channel which caused this call
671 * (may be NULL, in this case default amount of samples
672 * will be cached)
673 */
674 void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, EngineChannel* pEngineChannel) {
675 Engine* pEngine =
676 (pEngineChannel && pEngineChannel->GetEngine()) ?
677 dynamic_cast<Engine*>(pEngineChannel->GetEngine()) : NULL;
678 CacheInitialSamples(pSample, pEngine);
679 }
680
681 /**
682 * Caches a certain size at the beginning of the given sample in RAM. If the
683 * sample is very short, the whole sample will be loaded into RAM and thus
684 * no disk streaming is needed for this sample. Caching an initial part of
685 * samples is needed to compensate disk reading latency.
686 *
687 * @param pSample - points to the sample to be cached
688 * @param pEngine - pointer to Gig Engine which caused this call
689 * (may be NULL, in this case default amount of samples
690 * will be cached)
691 */
692 void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, AbstractEngine* pEngine) {
693 uint maxSamplesPerCycle =
694 (pEngine) ? pEngine->pAudioOutputDevice->MaxSamplesPerCycle() :
695 DefaultMaxSamplesPerCycle();
696 CacheInitialSamples(pSample, maxSamplesPerCycle);
697 }
698
699 void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, uint maxSamplesPerCycle) {
700 if (!pSample) {
701 dmsg(4,("gig::InstrumentResourceManager: Skipping sample (pSample == NULL)\n"));
702 return;
703 }
704 if (!pSample->SamplesTotal) return; // skip zero size samples
705
706 if (pSample->SamplesTotal <= CONFIG_PRELOAD_SAMPLES) {
707 // Sample is too short for disk streaming, so we load the whole
708 // sample into RAM and place 'pAudioIO->FragmentSize << CONFIG_MAX_PITCH'
709 // number of '0' samples (silence samples) behind the official buffer
710 // border, to allow the interpolator do it's work even at the end of
711 // the sample.
712 const uint neededSilenceSamples = uint((maxSamplesPerCycle << CONFIG_MAX_PITCH) + 6);
713 const uint currentlyCachedSilenceSamples = uint(pSample->GetCache().NullExtensionSize / pSample->FrameSize);
714 if (currentlyCachedSilenceSamples < neededSilenceSamples) {
715 dmsg(3,("Caching whole sample (sample name: \"%s\", sample size: %llu)\n", pSample->pInfo->Name.c_str(), (long long)pSample->SamplesTotal));
716 ::gig::buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(neededSilenceSamples);
717 dmsg(4,("Cached %llu Bytes, %llu silence bytes.\n", (long long)buf.Size, (long long)buf.NullExtensionSize));
718 }
719 }
720 else { // we only cache CONFIG_PRELOAD_SAMPLES and stream the other sample points from disk
721 if (!pSample->GetCache().Size) pSample->LoadSampleData(CONFIG_PRELOAD_SAMPLES);
722 }
723
724 if (!pSample->GetCache().Size) std::cerr << "Unable to cache sample - maybe memory full!" << std::endl << std::flush;
725 }
726
727 void InstrumentResourceManager::UncacheInitialSamples(::gig::Sample* pSample) {
728 dmsg(1,("Uncaching sample %p\n",(void*)pSample));
729 if (pSample->GetCache().Size) pSample->ReleaseSampleData();
730 }
731
732 /**
733 * Returns a list with all instruments currently in use, that are part of
734 * the given file.
735 *
736 * @param pFile - search criteria
737 * @param bLock - whether we should lock (mutex) the instrument manager
738 * during this call and unlock at the end of this call
739 */
740 std::vector< ::gig::Instrument*> InstrumentResourceManager::GetInstrumentsCurrentlyUsedOf(::gig::File* pFile, bool bLock) {
741 if (bLock) Lock();
742 std::vector< ::gig::Instrument*> result;
743 std::vector< ::gig::Instrument*> allInstruments = Resources(false/*don't lock again*/);
744 for (int i = 0; i < allInstruments.size(); i++)
745 if (
746 (::gig::File*) allInstruments[i]->GetParent()
747 == pFile
748 ) result.push_back(allInstruments[i]);
749 if (bLock) Unlock();
750 return result;
751 }
752
753 /**
754 * Returns a list with all gig engine channels that are currently using
755 * the given real-time instrument script (provided as source code).
756 *
757 * @param pScript - search criteria
758 * @param bLock - whether we should lock (mutex) the instrument manager
759 * during this call and unlock at the end of this call
760 */
761 std::set<EngineChannel*> InstrumentResourceManager::GetEngineChannelsUsingScriptSourceCode(const String& code, bool bLock) {
762 if (bLock) Lock();
763 std::set<EngineChannel*> result;
764 std::set<InstrumentScriptConsumer*> consumers = scripts.ConsumersOf({
765 .code = code,
766 .patchVars = std::map<String,String>(), // just required for GCC
767 .engineChannel = NULL, // just required for GCC
768 .wildcardPatchVars = true,
769 .wildcardEngineChannel = true
770 });
771 std::set<InstrumentScriptConsumer*>::iterator iter = consumers.begin();
772 std::set<InstrumentScriptConsumer*>::iterator end = consumers.end();
773 for (; iter != end; ++iter) {
774 EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
775 if (!pEngineChannel) continue;
776 result.insert(pEngineChannel);
777 }
778 if (bLock) Unlock();
779 return result;
780 }
781
782 /**
783 * Returns a list with all gig engine channels that are currently using
784 * the given instrument.
785 *
786 * @param pInstrument - search criteria
787 * @param bLock - whether we should lock (mutex) the instrument manager
788 * during this call and unlock at the end of this call
789 */
790 std::set<EngineChannel*> InstrumentResourceManager::GetEngineChannelsUsing(::gig::Instrument* pInstrument, bool bLock) {
791 if (bLock) Lock();
792 std::set<EngineChannel*> result;
793 std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(pInstrument);
794 std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
795 std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end = consumers.end();
796 for (; iter != end; ++iter) {
797 EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
798 if (!pEngineChannel) continue;
799 result.insert(pEngineChannel);
800 }
801 if (bLock) Unlock();
802 return result;
803 }
804
805 /**
806 * Returns a list with all gig Engines that are currently using the given
807 * instrument.
808 *
809 * @param pInstrument - search criteria
810 * @param bLock - whether we should lock (mutex) the instrument manager
811 * during this call and unlock at the end of this call
812 */
813 std::set<Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::Instrument* pInstrument, bool bLock) {
814 if (bLock) Lock();
815 std::set<Engine*> result;
816 std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(pInstrument);
817 std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
818 std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end = consumers.end();
819 for (; iter != end; ++iter) {
820 EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
821 if (!pEngineChannel) continue;
822 Engine* pEngine = dynamic_cast<Engine*>(pEngineChannel->GetEngine());
823 if (!pEngine) continue;
824 result.insert(pEngine);
825 }
826 if (bLock) Unlock();
827 return result;
828 }
829
830 /**
831 * Returns a list with all gig Engines that are currently using an
832 * instrument that is part of the given instrument file.
833 *
834 * @param pFile - search criteria
835 * @param bLock - whether we should lock (mutex) the instrument manager
836 * during this call and unlock at the end of this call
837 */
838 std::set<Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::File* pFile, bool bLock) {
839 if (bLock) Lock();
840 // get all instruments (currently in usage) that use that same gig::File
841 std::vector< ::gig::Instrument*> instrumentsOfInterest =
842 GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
843
844 // get all engines that use that same gig::File
845 std::set<Engine*> result;
846 {
847 for (int i = 0; i < instrumentsOfInterest.size(); i++) {
848 std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(instrumentsOfInterest[i]);
849 std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
850 std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end = consumers.end();
851 for (; iter != end; ++iter) {
852 EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
853 if (!pEngineChannel) continue;
854 Engine* pEngine = dynamic_cast<Engine*>(pEngineChannel->GetEngine());
855 if (!pEngine) continue;
856 // the unique, sorted container std::set makes
857 // sure we won't have duplicates
858 result.insert(pEngine);
859 }
860 }
861 }
862 if (bLock) Unlock();
863 return result;
864 }
865
866 /**
867 * Returns @c true in case the given sample is referenced somewhere by the
868 * given instrument, @c false otherwise.
869 *
870 * @param pSample - sample reference
871 * @param pInstrument - instrument that might use that sample
872 */
873 bool InstrumentResourceManager::SampleReferencedByInstrument(::gig::Sample* pSample, ::gig::Instrument* pInstrument) {
874 size_t iRgn = 0;
875 for (
876 ::gig::Region* pRegion = pInstrument->GetRegionAt(iRgn);
877 pRegion; pRegion = pInstrument->GetRegionAt(++iRgn)
878 ) {
879 for (
880 int i = 0; i < pRegion->DimensionRegions &&
881 pRegion->pDimensionRegions[i]; i++
882 ) {
883 if (pRegion->pDimensionRegions[i]->pSample == pSample)
884 return true;
885 }
886 }
887 return false;
888 }
889
890 /**
891 * Suspend all gig engines that use the given instrument. This means
892 * completely stopping playback on those engines and killing all their
893 * voices and disk streams. This method will block until all voices AND
894 * their disk streams are finally deleted and the engine turned into a
895 * complete idle loop.
896 *
897 * All @c SuspendEnginesUsing() methods only serve one thread by one and
898 * block all other threads until the current active thread called
899 * @c ResumeAllEngines() .
900 *
901 * @param pInstrument - search criteria
902 */
903 void InstrumentResourceManager::SuspendEnginesUsing(::gig::Instrument* pInstrument) {
904 // make sure no other thread suspends whole engines at the same time
905 suspendedEnginesMutex.Lock();
906 // get all engines that use that same gig::Instrument
907 suspendedEngines = GetEnginesUsing(pInstrument, true/*lock*/);
908 // finally, completely suspend all engines that use that same gig::Instrument
909 std::set<Engine*>::iterator iter = suspendedEngines.begin();
910 std::set<Engine*>::iterator end = suspendedEngines.end();
911 for (; iter != end; ++iter) (*iter)->SuspendAll();
912 }
913
914 /**
915 * Suspend all gig engines that use the given instrument file. This means
916 * completely stopping playback on those engines and killing all their
917 * voices and disk streams. This method will block until all voices AND
918 * their disk streams are finally deleted and the engine turned into a
919 * complete idle loop.
920 *
921 * All @c SuspendEnginesUsing() methods only serve one thread by one and
922 * block all other threads until the current active thread called
923 * @c ResumeAllEngines() .
924 *
925 * @param pFile - search criteria
926 */
927 void InstrumentResourceManager::SuspendEnginesUsing(::gig::File* pFile) {
928 // make sure no other thread suspends whole engines at the same time
929 suspendedEnginesMutex.Lock();
930 // get all engines that use that same gig::File
931 suspendedEngines = GetEnginesUsing(pFile, true/*lock*/);
932 // finally, completely suspend all engines that use that same gig::File
933 std::set<Engine*>::iterator iter = suspendedEngines.begin();
934 std::set<Engine*>::iterator end = suspendedEngines.end();
935 for (; iter != end; ++iter) (*iter)->SuspendAll();
936 }
937
938 /**
939 * MUST be called after one called one of the @c SuspendEnginesUsing()
940 * methods, to resume normal playback on all previously suspended engines.
941 * As it's only possible for one thread to suspend whole engines at the
942 * same time, this method doesn't take any arguments.
943 */
944 void InstrumentResourceManager::ResumeAllEngines() {
945 // resume all previously completely suspended engines
946 std::set<Engine*>::iterator iter = suspendedEngines.begin();
947 std::set<Engine*>::iterator end = suspendedEngines.end();
948 for (; iter != end; ++iter) (*iter)->ResumeAll();
949 // no more suspended engines ...
950 suspendedEngines.clear();
951 // allow another thread to suspend whole engines
952 suspendedEnginesMutex.Unlock();
953 }
954
955
956
957 // internal gig file manager
958
959 ::gig::File* InstrumentResourceManager::GigResourceManager::Create(String Key, GigConsumer* pConsumer, void*& pArg) {
960 dmsg(1,("Loading gig file \'%s\'...", Key.c_str()));
961 ::RIFF::File* pRIFF = new ::RIFF::File(Key);
962 // due to the multi-threaded scenario use separate file I/O handles for
963 // each thread to avoid file I/O concurrency issues with .gig file
964 pRIFF->SetIOPerThread(true);
965
966 ::gig::File* pGig = new ::gig::File(pRIFF);
967 pArg = pRIFF;
968 dmsg(1,("OK\n"));
969 return pGig;
970 }
971
972 void InstrumentResourceManager::GigResourceManager::Destroy(::gig::File* pResource, void* pArg) {
973 dmsg(1,("Freeing gig file '%s' from memory ...", pResource->GetFileName().c_str()));
974
975 // Delete as much as possible of the gig file. Some of the
976 // dimension regions and samples may still be in use - these
977 // will be deleted later by the HandBackDimReg function.
978 bool deleteFile = true;
979 ssize_t iInstr = pResource->CountInstruments();
980 for (--iInstr; iInstr >= 0; --iInstr) {
981 ::gig::Instrument* instrument = pResource->GetInstrument(iInstr);
982 bool deleteInstrument = true;
983 ssize_t iRgn = instrument->CountRegions();
984 for (--iRgn; iRgn >= 0; --iRgn) {
985 ::gig::Region* region = instrument->GetRegionAt(iRgn);
986 bool deleteRegion = true;
987 for (int i = 0 ; i < region->DimensionRegions ; i++)
988 {
989 ::gig::DimensionRegion *d = region->pDimensionRegions[i];
990 std::map< ::gig::DimensionRegion*, region_info_t>::iterator iter = parent->RegionInfo.find(d);
991 if (iter != parent->RegionInfo.end()) {
992 region_info_t& dimRegInfo = (*iter).second;
993 dimRegInfo.file = pResource;
994 dimRegInfo.pArg = (::RIFF::File*)pArg;
995 deleteFile = deleteInstrument = deleteRegion = false;
996 }
997 }
998 if (deleteRegion) instrument->DeleteRegion(region);
999 }
1000 if (deleteInstrument) pResource->DeleteInstrument(instrument);
1001 }
1002 if (deleteFile) {
1003 delete pResource;
1004 delete (::RIFF::File*) pArg;
1005 } else {
1006 dmsg(2,("keeping some samples that are in use..."));
1007 ssize_t i = pResource->CountSamples();
1008 for (--i; i >= 0; --i) {
1009 ::gig::Sample* sample = pResource->GetSample(i);
1010 if (parent->SampleRefCount.find(sample) == parent->SampleRefCount.end()) {
1011 pResource->DeleteSample(sample);
1012 }
1013 }
1014 }
1015 dmsg(1,("OK\n"));
1016 }
1017
1018 }} // namespace LinuxSampler::gig

  ViewVC Help
Powered by ViewVC