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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1212 by schoenebeck, Tue May 29 23:59:36 2007 UTC revision 3734 by schoenebeck, Sat Feb 1 19:06:13 2020 UTC
# Line 1  Line 1 
1    
2  /***************************************************************************  /***************************************************************************
3   *                                                                         *   *                                                                         *
4   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
5   *                                                                         *   *                                                                         *
6   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
7   *   Copyright (C) 2005 - 2007 Christian Schoenebeck                       *   *   Copyright (C) 2005 - 2020 Christian Schoenebeck                       *
8   *                                                                         *   *                                                                         *
9   *   This program is free software; you can redistribute it and/or modify  *   *   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  *   *   it under the terms of the GNU General Public License as published by  *
# Line 24  Line 25 
25  #include <sstream>  #include <sstream>
26    
27  #include "InstrumentResourceManager.h"  #include "InstrumentResourceManager.h"
28    #include "EngineChannel.h"
29    #include "Engine.h"
30    
31  #include "../InstrumentEditorFactory.h"  #include "../../common/global_private.h"
32    #include "../../plugins/InstrumentEditorFactory.h"
 // We need to know the maximum number of sample points which are going to  
 // be processed for each render cycle of the audio output driver, to know  
 // how much initial sample points we need to cache into RAM. If the given  
 // sampler channel does not have an audio output device assigned yet  
 // though, we simply use this default value.  
 #define GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE     128  
33    
34  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
35    
     // data stored as long as an instrument resource exists  
     struct instr_entry_t {  
         InstrumentManager::instrument_id_t ID;  
         ::gig::File*                       pGig;  
         uint                               MaxSamplesPerCycle; ///< if some engine requests an already allocated instrument with a higher value, we have to reallocate the instrument  
     };  
   
36      // some data needed for the libgig callback function      // some data needed for the libgig callback function
37      struct progress_callback_arg_t {      struct progress_callback_arg_t {
38          InstrumentResourceManager*          pManager;          InstrumentResourceManager*          pManager;
# Line 52  namespace LinuxSampler { namespace gig { Line 42  namespace LinuxSampler { namespace gig {
42      // we use this to react on events concerning an instrument on behalf of an instrument editor      // we use this to react on events concerning an instrument on behalf of an instrument editor
43      class InstrumentEditorProxy : public InstrumentConsumer {      class InstrumentEditorProxy : public InstrumentConsumer {
44      public:      public:
45            virtual ~InstrumentEditorProxy() {}
46    
47          virtual void ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {          virtual void ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {
48              //TODO: inform the instrument editor about the pending update              //TODO: inform the instrument editor about the pending update
49          }          }
# Line 66  namespace LinuxSampler { namespace gig { Line 58  namespace LinuxSampler { namespace gig {
58    
59          // the instrument we borrowed on behalf of the editor          // the instrument we borrowed on behalf of the editor
60          ::gig::Instrument* pInstrument;          ::gig::Instrument* pInstrument;
61            // the instrument editor we work on behalf
62            InstrumentEditor* pEditor;
63      };      };
64    
65      /**      /**
# Line 78  namespace LinuxSampler { namespace gig { Line 72  namespace LinuxSampler { namespace gig {
72       *                    instrument ID       *                    instrument ID
73       */       */
74      void InstrumentResourceManager::OnInstrumentLoadingProgress(::gig::progress_t* pProgress) {      void InstrumentResourceManager::OnInstrumentLoadingProgress(::gig::progress_t* pProgress) {
75          dmsg(7,("gig::InstrumentResourceManager: progress %f%", pProgress->factor));          dmsg(7,("gig::InstrumentResourceManager: progress %f%%", pProgress->factor));
76          progress_callback_arg_t* pArg = static_cast<progress_callback_arg_t*>(pProgress->custom);          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          // 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;          const float localProgress = 0.9f * pProgress->factor;
79          pArg->pManager->DispatchResourceProgressEvent(*pArg->pInstrumentKey, localProgress);          pArg->pManager->DispatchResourceProgressEvent(*pArg->pInstrumentKey, localProgress);
80      }      }
81    
     std::vector<InstrumentResourceManager::instrument_id_t> InstrumentResourceManager::Instruments() {  
         return Entries();  
     }  
   
     InstrumentManager::mode_t InstrumentResourceManager::GetMode(const instrument_id_t& ID) {  
         return static_cast<InstrumentManager::mode_t>(AvailabilityMode(ID));  
     }  
   
     void InstrumentResourceManager::SetMode(const instrument_id_t& ID, InstrumentManager::mode_t Mode) {  
         dmsg(2,("gig::InstrumentResourceManager: setting mode for %s (Index=%d) to %d\n",ID.FileName.c_str(),ID.Index,Mode));  
         SetAvailabilityMode(ID, static_cast<ResourceManager<InstrumentManager::instrument_id_t, ::gig::Instrument>::mode_t>(Mode));  
     }  
   
82      String InstrumentResourceManager::GetInstrumentName(instrument_id_t ID) {      String InstrumentResourceManager::GetInstrumentName(instrument_id_t ID) {
83          Lock();          Lock();
84          ::gig::Instrument* pInstrument = Resource(ID, false);          ::gig::Instrument* pInstrument = Resource(ID, false);
# Line 106  namespace LinuxSampler { namespace gig { Line 87  namespace LinuxSampler { namespace gig {
87          return res;          return res;
88      }      }
89    
90      String InstrumentResourceManager::GetInstrumentTypeName(instrument_id_t ID) {      String InstrumentResourceManager::GetInstrumentDataStructureName(instrument_id_t ID) {
91          return ::gig::libraryName();          return ::gig::libraryName();
92      }      }
93    
94      String InstrumentResourceManager::GetInstrumentTypeVersion(instrument_id_t ID) {      String InstrumentResourceManager::GetInstrumentDataStructureVersion(instrument_id_t ID) {
95          return ::gig::libraryVersion();          return ::gig::libraryVersion();
96      }      }
97    
98      void InstrumentResourceManager::LaunchInstrumentEditor(instrument_id_t ID) throw (InstrumentManagerException) {      std::vector<InstrumentResourceManager::instrument_id_t> InstrumentResourceManager::GetInstrumentFileContent(String File) throw (InstrumentManagerException) {
99          const String sDataType    = GetInstrumentTypeName(ID);          ::RIFF::File* riff = NULL;
100          const String sDataVersion = GetInstrumentTypeVersion(ID);          ::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                ::gig::Region* pRegion = pInstrument->GetFirstRegion();
158                while (pRegion) {
159                    int low = pRegion->KeyRange.low;
160                    int high = pRegion->KeyRange.high;
161                    if (low < 0 || low > 127 || high < 0 || high > 127 || low > high) {
162                        std::cerr << "Invalid key range: " << low << " - " << high << std::endl;
163                    } else {
164                        for (int i = low; i <= high; i++) info.KeyBindings[i] = 1;
165                    }
166    
167                    pRegion = pInstrument->GetNextRegion();
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                    for (::gig::Region* pRegion = pInstrument->GetFirstRegion() ;
175                         pRegion && !hasKeyswitches ;
176                         pRegion = pInstrument->GetNextRegion()) {
177                        for (int i = 0 ; i < pRegion->Dimensions ; i++) {
178                            if (pRegion->pDimensionDefinitions[i].dimension == ::gig::dimension_keyboard) {
179                                hasKeyswitches = true;
180                                break;
181                            }
182                        }
183                    }
184    
185                    if (hasKeyswitches) {
186                        int low = pInstrument->DimensionKeyRange.low;
187                        int high = pInstrument->DimensionKeyRange.high;
188                        if (low < 0 || low > 127 || high < 0 || high > 127 || low > high) {
189                            std::cerr << "Invalid keyswitch range: " << low << " - " << high << std::endl;
190                        } else {
191                            for (int i = low; i <= high; i++) info.KeySwitchBindings[i] = 1;
192                        }
193                    }
194                }
195    
196                if (loaded) Unlock();
197    
198                if (gig)  delete gig;
199                if (riff) delete riff;
200                return info;
201            } catch (::RIFF::Exception e) {
202                if (loaded) Unlock();
203                if (gig)  delete gig;
204                if (riff) delete riff;
205                throw InstrumentManagerException(e.Message);
206            } catch (...) {
207                if (loaded) Unlock();
208                if (gig)  delete gig;
209                if (riff) delete riff;
210                throw InstrumentManagerException("Unknown exception while trying to parse '" + ID.FileName + "'");
211            }
212        }
213    
214        InstrumentEditor* InstrumentResourceManager::LaunchInstrumentEditor(LinuxSampler::EngineChannel* pEngineChannel, instrument_id_t ID, void* pUserData) throw (InstrumentManagerException) {
215            const String sDataType    = GetInstrumentDataStructureName(ID);
216            const String sDataVersion = GetInstrumentDataStructureVersion(ID);
217          // find instrument editors capable to handle given instrument          // find instrument editors capable to handle given instrument
218          std::vector<String> vEditors =          std::vector<String> vEditors =
219              InstrumentEditorFactory::MatchingEditors(sDataType, sDataVersion);              InstrumentEditorFactory::MatchingEditors(sDataType, sDataVersion);
# Line 128  namespace LinuxSampler { namespace gig { Line 225  namespace LinuxSampler { namespace gig {
225          dmsg(1,("Found matching editor '%s' for instrument ('%s', %d) having data structure ('%s','%s')\n",          dmsg(1,("Found matching editor '%s' for instrument ('%s', %d) having data structure ('%s','%s')\n",
226              vEditors[0].c_str(), ID.FileName.c_str(), ID.Index, sDataType.c_str(), sDataVersion.c_str()));              vEditors[0].c_str(), ID.FileName.c_str(), ID.Index, sDataType.c_str(), sDataVersion.c_str()));
227          InstrumentEditor* pEditor = InstrumentEditorFactory::Create(vEditors[0]);          InstrumentEditor* pEditor = InstrumentEditorFactory::Create(vEditors[0]);
228          // we want to know when you'll die X| (see OnInstrumentEditorQuit())          // register for receiving notifications from the instrument editor
229          pEditor->AddListener(this);          pEditor->AddListener(this);
230          // create a proxy that reacts on notification on behalf of the editor          // create a proxy that reacts on notification on behalf of the editor
231          InstrumentEditorProxy* pProxy = new InstrumentEditorProxy;          InstrumentEditorProxy* pProxy = new InstrumentEditorProxy;
# Line 136  namespace LinuxSampler { namespace gig { Line 233  namespace LinuxSampler { namespace gig {
233          ::gig::Instrument* pInstrument = Borrow(ID, pProxy);          ::gig::Instrument* pInstrument = Borrow(ID, pProxy);
234          // remember the proxy and instrument for this instrument editor          // remember the proxy and instrument for this instrument editor
235          pProxy->pInstrument = pInstrument;          pProxy->pInstrument = pInstrument;
236            pProxy->pEditor     = pEditor;
237          InstrumentEditorProxiesMutex.Lock();          InstrumentEditorProxiesMutex.Lock();
238          InstrumentEditorProxies[pEditor] = pProxy;          InstrumentEditorProxies.add(pProxy);
239          InstrumentEditorProxiesMutex.Unlock();          InstrumentEditorProxiesMutex.Unlock();
240          // launch the instrument editor for the given instrument          // launch the instrument editor for the given instrument
241          pEditor->Launch(pInstrument, sDataType, sDataVersion);          pEditor->Launch(pEngineChannel, pInstrument, sDataType, sDataVersion, pUserData);
242    
243            // register the instrument editor as virtual MIDI device as well ...
244            VirtualMidiDevice* pVirtualMidiDevice =
245                dynamic_cast<VirtualMidiDevice*>(pEditor);
246            if (!pVirtualMidiDevice) {
247                std::cerr << "Instrument editor not a virtual MIDI device\n" << std::flush;
248                return pEditor;
249            }
250            // 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 ? )
251            Lock();
252            std::set<EngineChannel*> engineChannels =
253                GetEngineChannelsUsing(pInstrument, false/*don't lock again*/);
254            std::set<EngineChannel*>::iterator iter = engineChannels.begin();
255            std::set<EngineChannel*>::iterator end  = engineChannels.end();
256            for (; iter != end; ++iter) (static_cast<AbstractEngineChannel*>(*iter))->Connect(pVirtualMidiDevice);
257            Unlock();
258    
259            return pEditor;
260      }      }
261    
262      /**      /**
# Line 152  namespace LinuxSampler { namespace gig { Line 268  namespace LinuxSampler { namespace gig {
268       */       */
269      void InstrumentResourceManager::OnInstrumentEditorQuit(InstrumentEditor* pSender) {      void InstrumentResourceManager::OnInstrumentEditorQuit(InstrumentEditor* pSender) {
270          dmsg(1,("InstrumentResourceManager: instrument editor quit, doing cleanup\n"));          dmsg(1,("InstrumentResourceManager: instrument editor quit, doing cleanup\n"));
271          // hand back instrument and free proxy  
272          InstrumentEditorProxiesMutex.Lock();          ::gig::Instrument* pInstrument = NULL;
273          if (InstrumentEditorProxies.count(pSender)) {          InstrumentEditorProxy* pProxy  = NULL;
274            int iProxyIndex                = -1;
275    
276            // first find the editor proxy entry for this editor
277            {
278                LockGuard lock(InstrumentEditorProxiesMutex);
279                for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
280                    InstrumentEditorProxy* pCurProxy =
281                        dynamic_cast<InstrumentEditorProxy*>(
282                            InstrumentEditorProxies[i]
283                            );
284                    if (pCurProxy->pEditor == pSender) {
285                        pProxy      = pCurProxy;
286                        iProxyIndex = i;
287                        pInstrument = pCurProxy->pInstrument;
288                    }
289                }
290            }
291    
292            if (!pProxy) {
293                std::cerr << "Eeeek, could not find instrument editor proxy, "
294                             "this is a bug!\n" << std::flush;
295                return;
296            }
297    
298            // now unregister editor as not being available as a virtual MIDI device anymore
299            VirtualMidiDevice* pVirtualMidiDevice =
300                dynamic_cast<VirtualMidiDevice*>(pSender);
301            if (pVirtualMidiDevice) {
302                Lock();
303                // NOTE: see note in LaunchInstrumentEditor()
304                std::set<EngineChannel*> engineChannels =
305                    GetEngineChannelsUsing(pInstrument, false/*don't lock again*/);
306                std::set<EngineChannel*>::iterator iter = engineChannels.begin();
307                std::set<EngineChannel*>::iterator end  = engineChannels.end();
308                for (; iter != end; ++iter) (*iter)->Disconnect(pVirtualMidiDevice);
309                Unlock();
310            } else {
311                std::cerr << "Could not unregister editor as not longer acting as "
312                             "virtual MIDI device. Wasn't it registered?\n"
313                          << std::flush;
314            }
315    
316            // finally delete proxy entry and hand back instrument
317            if (pInstrument) {
318                {
319                    LockGuard lock(InstrumentEditorProxiesMutex);
320                    InstrumentEditorProxies.remove(iProxyIndex);
321                }
322    
323                HandBack(pInstrument, pProxy);
324                delete pProxy;
325            }
326    
327            // Note that we don't need to free the editor here. As it
328            // derives from Thread, it will delete itself when the thread
329            // dies.
330        }
331    
332    #if 0 // currently unused :
333        /**
334         * Try to inform the respective instrument editor(s), that a note on
335         * event just occured. This method is called by the MIDI thread. If any
336         * obstacles are in the way (e.g. if a wait for an unlock would be
337         * required) we give up immediately, since the RT safeness of the MIDI
338         * thread has absolute priority.
339         */
340        void InstrumentResourceManager::TrySendNoteOnToEditors(uint8_t Key, uint8_t Velocity, ::gig::Instrument* pInstrument) {
341            const bool bGotLock = InstrumentEditorProxiesMutex.Trylock(); // naively assumes RT safe implementation
342            if (!bGotLock) return; // hell, forget it, not worth the hassle
343            for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
344                InstrumentEditorProxy* pProxy =
345                    dynamic_cast<InstrumentEditorProxy*>(
346                        InstrumentEditorProxies[i]
347                    );
348                if (pProxy->pInstrument == pInstrument)
349                    pProxy->pEditor->SendNoteOnToDevice(Key, Velocity);
350            }
351            InstrumentEditorProxiesMutex.Unlock(); // naively assumes RT safe implementation
352        }
353    
354        /**
355         * Try to inform the respective instrument editor(s), that a note off
356         * event just occured. This method is called by the MIDI thread. If any
357         * obstacles are in the way (e.g. if a wait for an unlock would be
358         * required) we give up immediately, since the RT safeness of the MIDI
359         * thread has absolute priority.
360         */
361        void InstrumentResourceManager::TrySendNoteOffToEditors(uint8_t Key, uint8_t Velocity, ::gig::Instrument* pInstrument) {
362            const bool bGotLock = InstrumentEditorProxiesMutex.Trylock(); // naively assumes RT safe implementation
363            if (!bGotLock) return; // hell, forget it, not worth the hassle
364            for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
365              InstrumentEditorProxy* pProxy =              InstrumentEditorProxy* pProxy =
366                  dynamic_cast<InstrumentEditorProxy*>(                  dynamic_cast<InstrumentEditorProxy*>(
367                      InstrumentEditorProxies[pSender]                      InstrumentEditorProxies[i]
368                  );                  );
369              InstrumentEditorProxies.erase(pSender);              if (pProxy->pInstrument == pInstrument)
370              InstrumentEditorProxiesMutex.Unlock();                  pProxy->pEditor->SendNoteOffToDevice(Key, Velocity);
371              HandBack(pProxy->pInstrument, pProxy);          }
372              if (pProxy) delete pProxy;          InstrumentEditorProxiesMutex.Unlock(); // naively assumes RT safe implementation
373        }
374    #endif // unused
375    
376        void InstrumentResourceManager::OnSamplesToBeRemoved(std::set<void*> Samples, InstrumentEditor* pSender) {
377            if (Samples.empty()) {
378                std::cerr << "gig::InstrumentResourceManager: WARNING, "
379                             "OnSamplesToBeRemoved() called with empty list, this "
380                             "is a bug!\n" << std::flush;
381                return;
382            }
383            // TODO: ATM we assume here that all samples are from the same file
384            ::gig::Sample* pFirstSample = (::gig::Sample*) *Samples.begin();
385            ::gig::File* pCriticalFile = dynamic_cast< ::gig::File*>(pFirstSample->GetParent());
386            // completely suspend all engines that use that same file
387            SuspendEnginesUsing(pCriticalFile);
388        }
389    
390        void InstrumentResourceManager::OnSamplesRemoved(InstrumentEditor* pSender) {
391            // resume all previously, completely suspended engines
392            // (we don't have to un-cache the removed samples here, since that is
393            // automatically done by the gig::Sample destructor)
394            ResumeAllEngines();
395        }
396    
397        void InstrumentResourceManager::OnDataStructureToBeChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {
398            dmsg(5,("gig::InstrumentResourceManager::OnDataStructureToBeChanged(%s)\n", sStructType.c_str()));
399            //TODO: remove code duplication
400            if (sStructType == "gig::File") {
401                // completely suspend all engines that use that file
402                ::gig::File* pFile = (::gig::File*) pStruct;
403                SuspendEnginesUsing(pFile);
404            } else if (sStructType == "gig::Instrument") {
405                // completely suspend all engines that use that instrument
406                ::gig::Instrument* pInstrument = (::gig::Instrument*) pStruct;
407                SuspendEnginesUsing(pInstrument);
408            } else if (sStructType == "gig::Region") {
409                // only advice the engines to suspend the given region, so they'll
410                // only ignore that region (and probably already other suspended
411                // ones), but beside that continue normal playback
412                ::gig::Region* pRegion = (::gig::Region*) pStruct;
413                ::gig::Instrument* pInstrument =
414                    (::gig::Instrument*) pRegion->GetParent();
415                Lock();
416                std::set<Engine*> engines =
417                    GetEnginesUsing(pInstrument, false/*don't lock again*/);
418                std::set<Engine*>::iterator iter = engines.begin();
419                std::set<Engine*>::iterator end  = engines.end();
420                for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
421                Unlock();
422            } else if (sStructType == "gig::DimensionRegion") {
423                // only advice the engines to suspend the given DimensionRegions's
424                // parent region, so they'll only ignore that region (and probably
425                // already other suspended ones), but beside that continue normal
426                // playback
427                ::gig::DimensionRegion* pDimReg =
428                    (::gig::DimensionRegion*) pStruct;
429                ::gig::Region* pRegion = pDimReg->GetParent();
430                ::gig::Instrument* pInstrument =
431                    (::gig::Instrument*) pRegion->GetParent();
432                Lock();
433                std::set<Engine*> engines =
434                    GetEnginesUsing(pInstrument, false/*don't lock again*/);
435                std::set<Engine*>::iterator iter = engines.begin();
436                std::set<Engine*>::iterator end  = engines.end();
437                for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
438                Unlock();
439            } else if (sStructType == "gig::Script") {
440                // no need to suspend anything here, since the sampler is
441                // processing a translated VM representation of the original script
442                // source code, not accessing the source code itself during playback
443                ::gig::Script* pScript = (::gig::Script*) pStruct;
444                // remember the original source code of the script, since the script
445                // resource manager uses the source code as key
446                pendingScriptUpdatesMutex.Lock();
447                pendingScriptUpdates[pScript] = pScript->GetScriptAsText();
448                pendingScriptUpdatesMutex.Unlock();
449            } else {
450                std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
451                             "structure '" << sStructType << "' requested to be "
452                             "suspended by instrument editor. This is a bug!\n"
453                          << std::flush;
454                //TODO: we should inform the instrument editor that something seriously went wrong
455            }
456        }
457    
458        void InstrumentResourceManager::OnDataStructureChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {
459            dmsg(5,("gig::InstrumentResourceManager::OnDataStructureChanged(%s)\n", sStructType.c_str()));
460            //TODO: remove code duplication
461            if (sStructType == "gig::File") {
462                // resume all previously suspended engines
463                ResumeAllEngines();
464            } else if (sStructType == "gig::Instrument") {
465                // resume all previously suspended engines
466                ResumeAllEngines();
467            } else if (sStructType == "gig::Sample") {
468                // we're assuming here, that OnDataStructureToBeChanged() with
469                // "gig::File" was called previously, so we won't resume anything
470                // here, but just re-cache the given sample
471                Lock();
472                ::gig::Sample* pSample = (::gig::Sample*) pStruct;
473                ::gig::File* pFile = (::gig::File*) pSample->GetParent();
474                UncacheInitialSamples(pSample);
475                // now re-cache ...
476                std::vector< ::gig::Instrument*> instruments =
477                    GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
478                for (int i = 0; i < instruments.size(); i++) {
479                    if (SampleReferencedByInstrument(pSample, instruments[i])) {
480                        std::set<EngineChannel*> engineChannels =
481                            GetEngineChannelsUsing(instruments[i], false/*don't lock again*/);
482                        std::set<EngineChannel*>::iterator iter = engineChannels.begin();
483                        std::set<EngineChannel*>::iterator end  = engineChannels.end();
484                        for (; iter != end; ++iter)
485                            CacheInitialSamples(pSample, *iter);
486                    }
487                }
488                Unlock();
489            } else if (sStructType == "gig::Region") {
490                // advice the engines to resume the given region, that is to
491                // using it for playback again
492                ::gig::Region* pRegion = (::gig::Region*) pStruct;
493                ::gig::Instrument* pInstrument =
494                    (::gig::Instrument*) pRegion->GetParent();
495                Lock();
496                std::set<Engine*> engines =
497                    GetEnginesUsing(pInstrument, false/*don't lock again*/);
498                std::set<Engine*>::iterator iter = engines.begin();
499                std::set<Engine*>::iterator end  = engines.end();
500                for (; iter != end; ++iter) (*iter)->Resume(pRegion);
501                Unlock();
502            } else if (sStructType == "gig::DimensionRegion") {
503                // advice the engines to resume the given DimensionRegion's parent
504                // region, that is to using it for playback again
505                ::gig::DimensionRegion* pDimReg =
506                    (::gig::DimensionRegion*) pStruct;
507                ::gig::Region* pRegion = pDimReg->GetParent();
508                ::gig::Instrument* pInstrument =
509                    (::gig::Instrument*) pRegion->GetParent();
510                Lock();
511                std::set<Engine*> engines =
512                    GetEnginesUsing(pInstrument, false/*don't lock again*/);
513                std::set<Engine*>::iterator iter = engines.begin();
514                std::set<Engine*>::iterator end  = engines.end();
515                for (; iter != end; ++iter) (*iter)->Resume(pRegion);
516                Unlock();
517            } else if (sStructType == "gig::Script") {
518                // inform all engine channels which are using this script, that
519                // they need to reload (parse) the script's source code text
520                ::gig::Script* pScript = (::gig::Script*) pStruct;
521                pendingScriptUpdatesMutex.Lock();
522                if (pendingScriptUpdates.count(pScript)) {
523                    const String& code = pendingScriptUpdates[pScript];
524                    std::set<EngineChannel*> channels = GetEngineChannelsUsingScriptSourceCode(code, true/*lock*/);
525                    pendingScriptUpdates.erase(pScript);
526                    std::set<EngineChannel*>::iterator iter = channels.begin();
527                    std::set<EngineChannel*>::iterator end  = channels.end();
528                    for (; iter != end; ++iter) (*iter)->reloadScript(pScript);
529                }
530                pendingScriptUpdatesMutex.Unlock();
531          } else {          } else {
532              InstrumentEditorProxiesMutex.Unlock();              std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
533              std::cerr << "Eeeek, could not find instrument editor proxy, this is a bug!\n" << std::flush;                           "structure '" << sStructType << "' requested to be "
534                             "resumed by instrument editor. This is a bug!\n"
535                          << std::flush;
536                //TODO: we should inform the instrument editor that something seriously went wrong
537            }
538        }
539    
540        void InstrumentResourceManager::OnSampleReferenceChanged(void* pOldSample, void* pNewSample, InstrumentEditor* pSender) {
541            // uncache old sample in case it's not used by anybody anymore
542            if (pOldSample) {
543                Lock();
544                ::gig::Sample* pSample = (::gig::Sample*) pOldSample;
545                ::gig::File* pFile = (::gig::File*) pSample->GetParent();
546                bool bSampleStillInUse = false;
547                std::vector< ::gig::Instrument*> instruments =
548                    GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
549                for (int i = 0; i < instruments.size(); i++) {
550                    if (SampleReferencedByInstrument(pSample, instruments[i])) {
551                        bSampleStillInUse = true;
552                        break;
553                    }
554                }
555                if (!bSampleStillInUse) UncacheInitialSamples(pSample);
556                Unlock();
557            }
558            // make sure new sample reference is cached
559            if (pNewSample) {
560                Lock();
561                ::gig::Sample* pSample = (::gig::Sample*) pNewSample;
562                ::gig::File* pFile = (::gig::File*) pSample->GetParent();
563                // get all engines that use that same gig::File
564                std::set<Engine*> engines = GetEnginesUsing(pFile, false/*don't lock again*/);
565                std::set<Engine*>::iterator iter = engines.begin();
566                std::set<Engine*>::iterator end  = engines.end();
567                for (; iter != end; ++iter)
568                    CacheInitialSamples(pSample, *iter);
569                Unlock();
570          }          }
         // free the editor  
         InstrumentEditorFactory::Destroy(pSender);  
571      }      }
572    
573      ::gig::Instrument* InstrumentResourceManager::Create(instrument_id_t Key, InstrumentConsumer* pConsumer, void*& pArg) {      ::gig::Instrument* InstrumentResourceManager::Create(instrument_id_t Key, InstrumentConsumer* pConsumer, void*& pArg) {
574          // get gig file from inernal gig file manager          // get gig file from internal gig file manager
575          ::gig::File* pGig = Gigs.Borrow(Key.FileName, (GigConsumer*) Key.Index); // conversion kinda hackish :/          ::gig::File* pGig = Gigs.Borrow(Key.FileName, reinterpret_cast<GigConsumer*>(Key.Index)); // conversion kinda hackish :/
576    
577          // we pass this to the progress callback mechanism of libgig          // we pass this to the progress callback mechanism of libgig
578          progress_callback_arg_t callbackArg;          progress_callback_arg_t callbackArg;
# Line 194  namespace LinuxSampler { namespace gig { Line 593  namespace LinuxSampler { namespace gig {
593          pGig->GetFirstSample(); // just to force complete instrument loading          pGig->GetFirstSample(); // just to force complete instrument loading
594          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
595    
596            uint maxSamplesPerCycle = GetMaxSamplesPerCycle(pConsumer);
597    
598          // cache initial samples points (for actually needed samples)          // cache initial samples points (for actually needed samples)
599          dmsg(1,("Caching initial samples..."));          dmsg(1,("Caching initial samples..."));
600          uint iRegion = 0; // just for progress calculation          uint iRegion = 0; // just for progress calculation
# Line 205  namespace LinuxSampler { namespace gig { Line 606  namespace LinuxSampler { namespace gig {
606    
607              if (pRgn->GetSample() && !pRgn->GetSample()->GetCache().Size) {              if (pRgn->GetSample() && !pRgn->GetSample()->GetCache().Size) {
608                  dmsg(2,("C"));                  dmsg(2,("C"));
609                  CacheInitialSamples(pRgn->GetSample(), (gig::EngineChannel*) pConsumer);                  CacheInitialSamples(pRgn->GetSample(), maxSamplesPerCycle);
610              }              }
611              for (uint i = 0; i < pRgn->DimensionRegions; i++) {              for (uint i = 0; i < pRgn->DimensionRegions; i++) {
612                  CacheInitialSamples(pRgn->pDimensionRegions[i]->pSample, (gig::EngineChannel*) pConsumer);                  CacheInitialSamples(pRgn->pDimensionRegions[i]->pSample, maxSamplesPerCycle);
613              }              }
614    
615              pRgn = pInstrument->GetNextRegion();              pRgn = pInstrument->GetNextRegion();
# Line 221  namespace LinuxSampler { namespace gig { Line 622  namespace LinuxSampler { namespace gig {
622          instr_entry_t* pEntry = new instr_entry_t;          instr_entry_t* pEntry = new instr_entry_t;
623          pEntry->ID.FileName   = Key.FileName;          pEntry->ID.FileName   = Key.FileName;
624          pEntry->ID.Index      = Key.Index;          pEntry->ID.Index      = Key.Index;
625          pEntry->pGig          = pGig;          pEntry->pFile         = pGig;
626    
627          gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(pConsumer);          // and we save this to check if we need to reallocate for an engine with higher value of 'MaxSamplesPerSecond'
628          // and we save this to check if we need to reallocate for a engine with higher value of 'MaxSamplesPerSecond'          pEntry->MaxSamplesPerCycle = maxSamplesPerCycle;
629          pEntry->MaxSamplesPerCycle =          
             (!pEngineChannel) ? 0 /* don't care for instrument editors */ :  
                 (pEngineChannel->GetEngine()) ?  
                     dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()  
                     : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;  
630          pArg = pEntry;          pArg = pEntry;
631    
632          return pInstrument;          return pInstrument;
633      }      }
634    
635      void InstrumentResourceManager::Destroy( ::gig::Instrument* pResource, void* pArg) {      void InstrumentResourceManager::Destroy(::gig::Instrument* pResource, void* pArg) {
636          instr_entry_t* pEntry = (instr_entry_t*) pArg;          instr_entry_t* pEntry = (instr_entry_t*) pArg;
637          // we don't need the .gig file here anymore          // we don't need the .gig file here anymore
638          Gigs.HandBack(pEntry->pGig, (GigConsumer*) pEntry->ID.Index); // conversion kinda hackish :/          Gigs.HandBack(pEntry->pFile, reinterpret_cast<GigConsumer*>(pEntry->ID.Index)); // conversion kinda hackish :/
639          delete pEntry;          delete pEntry;
640      }      }
641    
642      void InstrumentResourceManager::OnBorrow(::gig::Instrument* pResource, InstrumentConsumer* pConsumer, void*& pArg) {      void InstrumentResourceManager::DeleteRegionIfNotUsed(::gig::DimensionRegion* pRegion, region_info_t* pRegInfo) {
643          instr_entry_t* pEntry = (instr_entry_t*) pArg;          // TODO: we could delete Region and Instrument here if they have become unused
         gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(pConsumer);  
         uint maxSamplesPerCycle =  
             (pEngineChannel && pEngineChannel->GetEngine()) ? dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()  
                                           : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;  
         if (pEntry->MaxSamplesPerCycle < maxSamplesPerCycle) {  
             Update(pResource, pConsumer);  
         }  
644      }      }
645    
646      /**      void InstrumentResourceManager::DeleteSampleIfNotUsed(::gig::Sample* pSample, region_info_t* pRegInfo) {
647       * Give back an instrument. This should be used instead of          ::gig::File* gig = pRegInfo->file;
648       * HandBack if there are some dimension regions that are still in          ::RIFF::File* riff = static_cast< ::RIFF::File*>(pRegInfo->pArg);
649       * use. (When an instrument is changed, the voices currently          if (gig) {
650       * playing is allowed to keep playing with the old instrument              gig->DeleteSample(pSample);
651       * until note off arrives. New notes will use the new instrument.)              if (!gig->GetFirstSample()) {
652       */                  dmsg(2,("No more samples in use - freeing gig\n"));
653      void InstrumentResourceManager::HandBackInstrument(::gig::Instrument* pResource, InstrumentConsumer* pConsumer,                  delete gig;
654                                                         ::gig::DimensionRegion** dimRegionsInUse) {                  delete riff;
655          DimRegInfoMutex.Lock();              }
656          for (int i = 0 ; dimRegionsInUse[i] ; i++) {          }
             DimRegInfo[dimRegionsInUse[i]].refCount++;  
             SampleRefCount[dimRegionsInUse[i]->pSample]++;  
         }  
         HandBack(pResource, pConsumer, true);  
         DimRegInfoMutex.Unlock();  
657      }      }
658    
659      /**      /**
660       * Give back a dimension region that belongs to an instrument that       * Just a wrapper around the other @c CacheInitialSamples() method.
661       * was previously handed back.       *
662       */       *  @param pSample - points to the sample to be cached
663      void InstrumentResourceManager::HandBackDimReg(::gig::DimensionRegion* pDimReg) {       *  @param pEngine - pointer to Gig Engine Channel which caused this call
664          DimRegInfoMutex.Lock();       *                   (may be NULL, in this case default amount of samples
665          dimreg_info_t& dimRegInfo = DimRegInfo[pDimReg];       *                   will be cached)
666          int dimRegRefCount = --dimRegInfo.refCount;       */
667          int sampleRefCount = --SampleRefCount[pDimReg->pSample];      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, EngineChannel* pEngineChannel) {
668          if (dimRegRefCount == 0) {          Engine* pEngine =
669              ::gig::File* gig = dimRegInfo.file;              (pEngineChannel && pEngineChannel->GetEngine()) ?
670              ::RIFF::File* riff = dimRegInfo.riff;                  dynamic_cast<Engine*>(pEngineChannel->GetEngine()) : NULL;
671              DimRegInfo.erase(pDimReg);          CacheInitialSamples(pSample, pEngine);
             // TODO: we could delete Region and Instrument here if  
             // they have become unused  
   
             if (sampleRefCount == 0) {  
                 SampleRefCount.erase(pDimReg->pSample);  
   
                 if (gig) {  
                     gig->DeleteSample(pDimReg->pSample);  
                     if (!gig->GetFirstSample()) {  
                         dmsg(2,("No more samples in use - freeing gig\n"));  
                         delete gig;  
                         delete riff;  
                     }  
                 }  
             }  
         }  
         DimRegInfoMutex.Unlock();  
672      }      }
673    
674      /**      /**
# Line 310  namespace LinuxSampler { namespace gig { Line 678  namespace LinuxSampler { namespace gig {
678       *  samples is needed to compensate disk reading latency.       *  samples is needed to compensate disk reading latency.
679       *       *
680       *  @param pSample - points to the sample to be cached       *  @param pSample - points to the sample to be cached
681       *  @param pEngineChannel - pointer to Gig Engine Channel which caused this call       *  @param pEngine - pointer to Gig Engine which caused this call
682         *                   (may be NULL, in this case default amount of samples
683         *                   will be cached)
684       */       */
685      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::EngineChannel* pEngineChannel) {      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, AbstractEngine* pEngine) {
686            uint maxSamplesPerCycle =
687                (pEngine) ? pEngine->pAudioOutputDevice->MaxSamplesPerCycle() :
688                DefaultMaxSamplesPerCycle();
689            CacheInitialSamples(pSample, maxSamplesPerCycle);
690        }
691    
692        void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, uint maxSamplesPerCycle) {
693          if (!pSample) {          if (!pSample) {
694              dmsg(4,("gig::InstrumentResourceManager: Skipping sample (pSample == NULL)\n"));              dmsg(4,("gig::InstrumentResourceManager: Skipping sample (pSample == NULL)\n"));
695              return;              return;
# Line 325  namespace LinuxSampler { namespace gig { Line 702  namespace LinuxSampler { namespace gig {
702              // number of '0' samples (silence samples) behind the official buffer              // number of '0' samples (silence samples) behind the official buffer
703              // border, to allow the interpolator do it's work even at the end of              // border, to allow the interpolator do it's work even at the end of
704              // the sample.              // the sample.
705              const uint maxSamplesPerCycle =              const uint neededSilenceSamples = uint((maxSamplesPerCycle << CONFIG_MAX_PITCH) + 6);
706                  (pEngineChannel && pEngineChannel->GetEngine()) ? dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()              const uint currentlyCachedSilenceSamples = uint(pSample->GetCache().NullExtensionSize / pSample->FrameSize);
                                               : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;  
             const uint neededSilenceSamples = (maxSamplesPerCycle << CONFIG_MAX_PITCH) + 3;  
             const uint currentlyCachedSilenceSamples = pSample->GetCache().NullExtensionSize / pSample->FrameSize;  
707              if (currentlyCachedSilenceSamples < neededSilenceSamples) {              if (currentlyCachedSilenceSamples < neededSilenceSamples) {
708                  dmsg(3,("Caching whole sample (sample name: \"%s\", sample size: %d)\n", pSample->pInfo->Name.c_str(), pSample->SamplesTotal));                  dmsg(3,("Caching whole sample (sample name: \"%s\", sample size: %llu)\n", pSample->pInfo->Name.c_str(), (long long)pSample->SamplesTotal));
709                  ::gig::buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(neededSilenceSamples);                  ::gig::buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(neededSilenceSamples);
710                  dmsg(4,("Cached %d Bytes, %d silence bytes.\n", buf.Size, buf.NullExtensionSize));                  dmsg(4,("Cached %llu Bytes, %llu silence bytes.\n", (long long)buf.Size, (long long)buf.NullExtensionSize));
711              }              }
712          }          }
713          else { // we only cache CONFIG_PRELOAD_SAMPLES and stream the other sample points from disk          else { // we only cache CONFIG_PRELOAD_SAMPLES and stream the other sample points from disk
# Line 343  namespace LinuxSampler { namespace gig { Line 717  namespace LinuxSampler { namespace gig {
717          if (!pSample->GetCache().Size) std::cerr << "Unable to cache sample - maybe memory full!" << std::endl << std::flush;          if (!pSample->GetCache().Size) std::cerr << "Unable to cache sample - maybe memory full!" << std::endl << std::flush;
718      }      }
719    
720        void InstrumentResourceManager::UncacheInitialSamples(::gig::Sample* pSample) {
721            dmsg(1,("Uncaching sample %p\n",(void*)pSample));
722            if (pSample->GetCache().Size) pSample->ReleaseSampleData();
723        }
724    
725        /**
726         * Returns a list with all instruments currently in use, that are part of
727         * the given file.
728         *
729         * @param pFile - search criteria
730         * @param bLock - whether we should lock (mutex) the instrument manager
731         *                during this call and unlock at the end of this call
732         */
733        std::vector< ::gig::Instrument*> InstrumentResourceManager::GetInstrumentsCurrentlyUsedOf(::gig::File* pFile, bool bLock) {
734            if (bLock) Lock();
735            std::vector< ::gig::Instrument*> result;
736            std::vector< ::gig::Instrument*> allInstruments = Resources(false/*don't lock again*/);
737            for (int i = 0; i < allInstruments.size(); i++)
738                if (
739                    (::gig::File*) allInstruments[i]->GetParent()
740                    == pFile
741                ) result.push_back(allInstruments[i]);
742            if (bLock) Unlock();
743            return result;
744        }
745    
746        /**
747         * Returns a list with all gig engine channels that are currently using
748         * the given real-time instrument script (provided as source code).
749         *
750         * @param pScript - search criteria
751         * @param bLock - whether we should lock (mutex) the instrument manager
752         *                during this call and unlock at the end of this call
753         */
754        std::set<EngineChannel*> InstrumentResourceManager::GetEngineChannelsUsingScriptSourceCode(const String& code, bool bLock) {
755            if (bLock) Lock();
756            std::set<EngineChannel*> result;
757            std::set<InstrumentScriptConsumer*> consumers = scripts.ConsumersOf({
758                .code = code,
759                .patchVars = std::map<String,String>(), // just required for GCC
760                .wildcardPatchVars = true
761            });
762            std::set<InstrumentScriptConsumer*>::iterator iter = consumers.begin();
763            std::set<InstrumentScriptConsumer*>::iterator end  = consumers.end();
764            for (; iter != end; ++iter) {
765                EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
766                if (!pEngineChannel) continue;
767                result.insert(pEngineChannel);
768            }
769            if (bLock) Unlock();
770            return result;
771        }
772    
773        /**
774         * Returns a list with all gig engine channels that are currently using
775         * the given instrument.
776         *
777         * @param pInstrument - search criteria
778         * @param bLock - whether we should lock (mutex) the instrument manager
779         *                during this call and unlock at the end of this call
780         */
781        std::set<EngineChannel*> InstrumentResourceManager::GetEngineChannelsUsing(::gig::Instrument* pInstrument, bool bLock) {
782            if (bLock) Lock();
783            std::set<EngineChannel*> result;
784            std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(pInstrument);
785            std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
786            std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();
787            for (; iter != end; ++iter) {
788                EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
789                if (!pEngineChannel) continue;
790                result.insert(pEngineChannel);
791            }
792            if (bLock) Unlock();
793            return result;
794        }
795    
796        /**
797         * Returns a list with all gig Engines that are currently using the given
798         * instrument.
799         *
800         * @param pInstrument - search criteria
801         * @param bLock - whether we should lock (mutex) the instrument manager
802         *                during this call and unlock at the end of this call
803         */
804        std::set<Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::Instrument* pInstrument, bool bLock) {
805            if (bLock) Lock();
806            std::set<Engine*> result;
807            std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(pInstrument);
808            std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
809            std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();
810            for (; iter != end; ++iter) {
811                EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
812                if (!pEngineChannel) continue;
813                Engine* pEngine = dynamic_cast<Engine*>(pEngineChannel->GetEngine());
814                if (!pEngine) continue;
815                result.insert(pEngine);
816            }
817            if (bLock) Unlock();
818            return result;
819        }
820    
821        /**
822         * Returns a list with all gig Engines that are currently using an
823         * instrument that is part of the given instrument file.
824         *
825         * @param pFile - search criteria
826         * @param bLock - whether we should lock (mutex) the instrument manager
827         *                during this call and unlock at the end of this call
828         */
829        std::set<Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::File* pFile, bool bLock) {
830            if (bLock) Lock();
831            // get all instruments (currently in usage) that use that same gig::File
832            std::vector< ::gig::Instrument*> instrumentsOfInterest =
833                GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
834    
835            // get all engines that use that same gig::File
836            std::set<Engine*> result;
837            {
838                for (int i = 0; i < instrumentsOfInterest.size(); i++) {
839                    std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(instrumentsOfInterest[i]);
840                    std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
841                    std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();
842                    for (; iter != end; ++iter) {
843                        EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
844                        if (!pEngineChannel) continue;
845                        Engine* pEngine = dynamic_cast<Engine*>(pEngineChannel->GetEngine());
846                        if (!pEngine) continue;
847                        // the unique, sorted container std::set makes
848                        // sure we won't have duplicates
849                        result.insert(pEngine);
850                    }
851                }
852            }
853            if (bLock) Unlock();
854            return result;
855        }
856    
857        /**
858         * Returns @c true in case the given sample is referenced somewhere by the
859         * given instrument, @c false otherwise.
860         *
861         * @param pSample - sample reference
862         * @param pInstrument - instrument that might use that sample
863         */
864        bool InstrumentResourceManager::SampleReferencedByInstrument(::gig::Sample* pSample, ::gig::Instrument* pInstrument) {
865            for (
866                ::gig::Region* pRegion = pInstrument->GetFirstRegion();
867                pRegion; pRegion = pInstrument->GetNextRegion()
868            ) {
869                for (
870                    int i = 0; i < pRegion->DimensionRegions &&
871                    pRegion->pDimensionRegions[i]; i++
872                ) {
873                    if (pRegion->pDimensionRegions[i]->pSample == pSample)
874                        return true;
875                }
876            }
877            return false;
878        }
879    
880        /**
881         * Suspend all gig engines that use the given instrument. This means
882         * completely stopping playback on those engines and killing all their
883         * voices and disk streams. This method will block until all voices AND
884         * their disk streams are finally deleted and the engine turned into a
885         * complete idle loop.
886         *
887         * All @c SuspendEnginesUsing() methods only serve one thread by one and
888         * block all other threads until the current active thread called
889         * @c ResumeAllEngines() .
890         *
891         * @param pInstrument - search criteria
892         */
893        void InstrumentResourceManager::SuspendEnginesUsing(::gig::Instrument* pInstrument) {
894            // make sure no other thread suspends whole engines at the same time
895            suspendedEnginesMutex.Lock();
896            // get all engines that use that same gig::Instrument
897            suspendedEngines = GetEnginesUsing(pInstrument, true/*lock*/);
898            // finally, completely suspend all engines that use that same gig::Instrument
899            std::set<Engine*>::iterator iter = suspendedEngines.begin();
900            std::set<Engine*>::iterator end  = suspendedEngines.end();
901            for (; iter != end; ++iter) (*iter)->SuspendAll();
902        }
903    
904        /**
905         * Suspend all gig engines that use the given instrument file. This means
906         * completely stopping playback on those engines and killing all their
907         * voices and disk streams. This method will block until all voices AND
908         * their disk streams are finally deleted and the engine turned into a
909         * complete idle loop.
910         *
911         * All @c SuspendEnginesUsing() methods only serve one thread by one and
912         * block all other threads until the current active thread called
913         * @c ResumeAllEngines() .
914         *
915         * @param pFile - search criteria
916         */
917        void InstrumentResourceManager::SuspendEnginesUsing(::gig::File* pFile) {
918            // make sure no other thread suspends whole engines at the same time
919            suspendedEnginesMutex.Lock();
920            // get all engines that use that same gig::File
921            suspendedEngines = GetEnginesUsing(pFile, true/*lock*/);
922            // finally, completely suspend all engines that use that same gig::File
923            std::set<Engine*>::iterator iter = suspendedEngines.begin();
924            std::set<Engine*>::iterator end  = suspendedEngines.end();
925            for (; iter != end; ++iter) (*iter)->SuspendAll();
926        }
927    
928        /**
929         * MUST be called after one called one of the @c SuspendEnginesUsing()
930         * methods, to resume normal playback on all previously suspended engines.
931         * As it's only possible for one thread to suspend whole engines at the
932         * same time, this method doesn't take any arguments.
933         */
934        void InstrumentResourceManager::ResumeAllEngines() {
935            // resume all previously completely suspended engines
936            std::set<Engine*>::iterator iter = suspendedEngines.begin();
937            std::set<Engine*>::iterator end  = suspendedEngines.end();
938            for (; iter != end; ++iter) (*iter)->ResumeAll();
939            // no more suspended engines ...
940            suspendedEngines.clear();
941            // allow another thread to suspend whole engines
942            suspendedEnginesMutex.Unlock();
943        }
944    
945    
946    
947      // internal gig file manager      // internal gig file manager
# Line 357  namespace LinuxSampler { namespace gig { Line 956  namespace LinuxSampler { namespace gig {
956      }      }
957    
958      void InstrumentResourceManager::GigResourceManager::Destroy(::gig::File* pResource, void* pArg) {      void InstrumentResourceManager::GigResourceManager::Destroy(::gig::File* pResource, void* pArg) {
959          dmsg(1,("Freeing gig file from memory..."));          dmsg(1,("Freeing gig file '%s' from memory ...", pResource->GetFileName().c_str()));
960    
961          // Delete as much as possible of the gig file. Some of the          // Delete as much as possible of the gig file. Some of the
962          // dimension regions and samples may still be in use - these          // dimension regions and samples may still be in use - these
# Line 378  namespace LinuxSampler { namespace gig { Line 977  namespace LinuxSampler { namespace gig {
977                  for (int i = 0 ; i < region->DimensionRegions ; i++)                  for (int i = 0 ; i < region->DimensionRegions ; i++)
978                  {                  {
979                      ::gig::DimensionRegion *d = region->pDimensionRegions[i];                      ::gig::DimensionRegion *d = region->pDimensionRegions[i];
980                      std::map< ::gig::DimensionRegion*, dimreg_info_t>::iterator iter = parent->DimRegInfo.find(d);                      std::map< ::gig::DimensionRegion*, region_info_t>::iterator iter = parent->RegionInfo.find(d);
981                      if (iter != parent->DimRegInfo.end()) {                      if (iter != parent->RegionInfo.end()) {
982                          dimreg_info_t& dimRegInfo = (*iter).second;                          region_info_t& dimRegInfo = (*iter).second;
983                          dimRegInfo.file = pResource;                          dimRegInfo.file = pResource;
984                          dimRegInfo.riff = (::RIFF::File*)pArg;                          dimRegInfo.pArg = (::RIFF::File*)pArg;
985                          deleteFile = deleteInstrument = deleteRegion = false;                          deleteFile = deleteInstrument = deleteRegion = false;
986                      }                      }
987                  }                  }

Legend:
Removed from v.1212  
changed lines
  Added in v.3734

  ViewVC Help
Powered by ViewVC