/[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 1646 by persson, Sun Jan 20 15:04:51 2008 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 - 2008 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 "../../common/global_private.h"  #include "../../common/global_private.h"
32  #include "../../plugins/InstrumentEditorFactory.h"  #include "../../plugins/InstrumentEditorFactory.h"
33    
 // 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  
   
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 53  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 67  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 79  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 144  namespace LinuxSampler { namespace gig { Line 124  namespace LinuxSampler { namespace gig {
124      }      }
125    
126      InstrumentResourceManager::instrument_info_t InstrumentResourceManager::GetInstrumentInfo(instrument_id_t ID) throw (InstrumentManagerException) {      InstrumentResourceManager::instrument_info_t InstrumentResourceManager::GetInstrumentInfo(instrument_id_t ID) throw (InstrumentManagerException) {
127          std::vector<instrument_id_t> result;          Lock();
128            ::gig::Instrument* pInstrument = Resource(ID, false);
129            bool loaded = (pInstrument != NULL);
130            if (!loaded) Unlock();
131    
132          ::RIFF::File* riff = NULL;          ::RIFF::File* riff = NULL;
133          ::gig::File*  gig  = NULL;          ::gig::File*  gig  = NULL;
134          try {          try {
135              riff = new ::RIFF::File(ID.FileName);              if (!loaded) {
136              gig  = new ::gig::File(riff);                  riff = new ::RIFF::File(ID.FileName);
137              gig->SetAutoLoad(false); // avoid time consuming samples scanning                  gig  = new ::gig::File(riff);
138              ::gig::Instrument* pInstrument = gig->GetInstrument(ID.Index);                  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);              if (!pInstrument) throw InstrumentManagerException("There is no instrument " + ToString(ID.Index) + " in " + ID.FileName);
143    
144              instrument_info_t info;              instrument_info_t info;
145              if (gig->pVersion) {              for (int i = 0; i < 128; i++) { info.KeyBindings[i] = info.KeySwitchBindings[i] = 0; }
146                  info.FormatVersion = ToString(gig->pVersion->major);  
147                  info.Product = gig->pInfo->Product;              ::gig::File* pFile = (::gig::File*) pInstrument->GetParent();
148                  info.Artists = gig->pInfo->Artists;  
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;              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;              if (gig)  delete gig;
199              if (riff) delete riff;              if (riff) delete riff;
200              return info;              return info;
201          } catch (::RIFF::Exception e) {          } catch (::RIFF::Exception e) {
202                if (loaded) Unlock();
203              if (gig)  delete gig;              if (gig)  delete gig;
204              if (riff) delete riff;              if (riff) delete riff;
205              throw InstrumentManagerException(e.Message);              throw InstrumentManagerException(e.Message);
206          } catch (...) {          } catch (...) {
207                if (loaded) Unlock();
208              if (gig)  delete gig;              if (gig)  delete gig;
209              if (riff) delete riff;              if (riff) delete riff;
210              throw InstrumentManagerException("Unknown exception while trying to parse '" + ID.FileName + "'");              throw InstrumentManagerException("Unknown exception while trying to parse '" + ID.FileName + "'");
211          }          }
212      }      }
213    
214      void InstrumentResourceManager::LaunchInstrumentEditor(instrument_id_t ID) throw (InstrumentManagerException) {      InstrumentEditor* InstrumentResourceManager::LaunchInstrumentEditor(LinuxSampler::EngineChannel* pEngineChannel, instrument_id_t ID, void* pUserData) throw (InstrumentManagerException) {
215          const String sDataType    = GetInstrumentDataStructureName(ID);          const String sDataType    = GetInstrumentDataStructureName(ID);
216          const String sDataVersion = GetInstrumentDataStructureVersion(ID);          const String sDataVersion = GetInstrumentDataStructureVersion(ID);
217          // find instrument editors capable to handle given instrument          // find instrument editors capable to handle given instrument
# Line 196  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 212  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              InstrumentEditorProxy* pProxy =          int iProxyIndex                = -1;
275                  dynamic_cast<InstrumentEditorProxy*>(  
276                      InstrumentEditorProxies[pSender]          // first find the editor proxy entry for this editor
277                  );          {
278              InstrumentEditorProxies.erase(pSender);              LockGuard lock(InstrumentEditorProxiesMutex);
279              InstrumentEditorProxiesMutex.Unlock();              for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
280              HandBack(pProxy->pInstrument, pProxy);                  InstrumentEditorProxy* pCurProxy =
281              if (pProxy) delete pProxy;                      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 {          } else {
311              InstrumentEditorProxiesMutex.Unlock();              std::cerr << "Could not unregister editor as not longer acting as "
312              std::cerr << "Eeeek, could not find instrument editor proxy, this is a bug!\n" << std::flush;                           "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          // Note that we don't need to free the editor here. As it
# Line 233  namespace LinuxSampler { namespace gig { Line 329  namespace LinuxSampler { namespace gig {
329          // dies.          // 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 =
366                    dynamic_cast<InstrumentEditorProxy*>(
367                        InstrumentEditorProxies[i]
368                    );
369                if (pProxy->pInstrument == pInstrument)
370                    pProxy->pEditor->SendNoteOffToDevice(Key, Velocity);
371            }
372            InstrumentEditorProxiesMutex.Unlock(); // naively assumes RT safe implementation
373        }
374    #endif // unused
375    
376      void InstrumentResourceManager::OnSamplesToBeRemoved(std::set<void*> Samples, InstrumentEditor* pSender) {      void InstrumentResourceManager::OnSamplesToBeRemoved(std::set<void*> Samples, InstrumentEditor* pSender) {
377          if (Samples.empty()) {          if (Samples.empty()) {
378              std::cerr << "gig::InstrumentResourceManager: WARNING, "              std::cerr << "gig::InstrumentResourceManager: WARNING, "
# Line 255  namespace LinuxSampler { namespace gig { Line 395  namespace LinuxSampler { namespace gig {
395      }      }
396    
397      void InstrumentResourceManager::OnDataStructureToBeChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {      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          //TODO: remove code duplication
400          if (sStructType == "gig::File") {          if (sStructType == "gig::File") {
401              // completely suspend all engines that use that file              // completely suspend all engines that use that file
# Line 272  namespace LinuxSampler { namespace gig { Line 413  namespace LinuxSampler { namespace gig {
413              ::gig::Instrument* pInstrument =              ::gig::Instrument* pInstrument =
414                  (::gig::Instrument*) pRegion->GetParent();                  (::gig::Instrument*) pRegion->GetParent();
415              Lock();              Lock();
416              std::set<gig::Engine*> engines =              std::set<Engine*> engines =
417                  GetEnginesUsing(pInstrument, false/*don't lock again*/);                  GetEnginesUsing(pInstrument, false/*don't lock again*/);
418              std::set<gig::Engine*>::iterator iter = engines.begin();              std::set<Engine*>::iterator iter = engines.begin();
419              std::set<gig::Engine*>::iterator end  = engines.end();              std::set<Engine*>::iterator end  = engines.end();
420              for (; iter != end; ++iter) (*iter)->Suspend(pRegion);              for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
421              Unlock();              Unlock();
422          } else if (sStructType == "gig::DimensionRegion") {          } else if (sStructType == "gig::DimensionRegion") {
# Line 289  namespace LinuxSampler { namespace gig { Line 430  namespace LinuxSampler { namespace gig {
430              ::gig::Instrument* pInstrument =              ::gig::Instrument* pInstrument =
431                  (::gig::Instrument*) pRegion->GetParent();                  (::gig::Instrument*) pRegion->GetParent();
432              Lock();              Lock();
433              std::set<gig::Engine*> engines =              std::set<Engine*> engines =
434                  GetEnginesUsing(pInstrument, false/*don't lock again*/);                  GetEnginesUsing(pInstrument, false/*don't lock again*/);
435              std::set<gig::Engine*>::iterator iter = engines.begin();              std::set<Engine*>::iterator iter = engines.begin();
436              std::set<gig::Engine*>::iterator end  = engines.end();              std::set<Engine*>::iterator end  = engines.end();
437              for (; iter != end; ++iter) (*iter)->Suspend(pRegion);              for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
438              Unlock();              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 {          } else {
450              std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "              std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
451                           "structure '" << sStructType << "' requested to be "                           "structure '" << sStructType << "' requested to be "
# Line 305  namespace LinuxSampler { namespace gig { Line 456  namespace LinuxSampler { namespace gig {
456      }      }
457    
458      void InstrumentResourceManager::OnDataStructureChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {      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          //TODO: remove code duplication
461          if (sStructType == "gig::File") {          if (sStructType == "gig::File") {
462              // resume all previously suspended engines              // resume all previously suspended engines
# Line 312  namespace LinuxSampler { namespace gig { Line 464  namespace LinuxSampler { namespace gig {
464          } else if (sStructType == "gig::Instrument") {          } else if (sStructType == "gig::Instrument") {
465              // resume all previously suspended engines              // resume all previously suspended engines
466              ResumeAllEngines();              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") {          } else if (sStructType == "gig::Region") {
490              // advice the engines to resume the given region, that is to              // advice the engines to resume the given region, that is to
491              // using it for playback again              // using it for playback again
# Line 319  namespace LinuxSampler { namespace gig { Line 493  namespace LinuxSampler { namespace gig {
493              ::gig::Instrument* pInstrument =              ::gig::Instrument* pInstrument =
494                  (::gig::Instrument*) pRegion->GetParent();                  (::gig::Instrument*) pRegion->GetParent();
495              Lock();              Lock();
496              std::set<gig::Engine*> engines =              std::set<Engine*> engines =
497                  GetEnginesUsing(pInstrument, false/*don't lock again*/);                  GetEnginesUsing(pInstrument, false/*don't lock again*/);
498              std::set<gig::Engine*>::iterator iter = engines.begin();              std::set<Engine*>::iterator iter = engines.begin();
499              std::set<gig::Engine*>::iterator end  = engines.end();              std::set<Engine*>::iterator end  = engines.end();
500              for (; iter != end; ++iter) (*iter)->Resume(pRegion);              for (; iter != end; ++iter) (*iter)->Resume(pRegion);
501              Unlock();              Unlock();
502          } else if (sStructType == "gig::DimensionRegion") {          } else if (sStructType == "gig::DimensionRegion") {
# Line 334  namespace LinuxSampler { namespace gig { Line 508  namespace LinuxSampler { namespace gig {
508              ::gig::Instrument* pInstrument =              ::gig::Instrument* pInstrument =
509                  (::gig::Instrument*) pRegion->GetParent();                  (::gig::Instrument*) pRegion->GetParent();
510              Lock();              Lock();
511              std::set<gig::Engine*> engines =              std::set<Engine*> engines =
512                  GetEnginesUsing(pInstrument, false/*don't lock again*/);                  GetEnginesUsing(pInstrument, false/*don't lock again*/);
513              std::set<gig::Engine*>::iterator iter = engines.begin();              std::set<Engine*>::iterator iter = engines.begin();
514              std::set<gig::Engine*>::iterator end  = engines.end();              std::set<Engine*>::iterator end  = engines.end();
515              for (; iter != end; ++iter) (*iter)->Resume(pRegion);              for (; iter != end; ++iter) (*iter)->Resume(pRegion);
516              Unlock();              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              std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "              std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
533                           "structure '" << sStructType << "' requested to be "                           "structure '" << sStructType << "' requested to be "
# Line 355  namespace LinuxSampler { namespace gig { Line 543  namespace LinuxSampler { namespace gig {
543              Lock();              Lock();
544              ::gig::Sample* pSample = (::gig::Sample*) pOldSample;              ::gig::Sample* pSample = (::gig::Sample*) pOldSample;
545              ::gig::File* pFile = (::gig::File*) pSample->GetParent();              ::gig::File* pFile = (::gig::File*) pSample->GetParent();
546                bool bSampleStillInUse = false;
547              std::vector< ::gig::Instrument*> instruments =              std::vector< ::gig::Instrument*> instruments =
548                  GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);                  GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
549              for (int i = 0; i < instruments.size(); i++)              for (int i = 0; i < instruments.size(); i++) {
550                  if (!SampleReferencedByInstrument(pSample, instruments[i]))                  if (SampleReferencedByInstrument(pSample, instruments[i])) {
551                      UncacheInitialSamples(pSample);                      bSampleStillInUse = true;
552                        break;
553                    }
554                }
555                if (!bSampleStillInUse) UncacheInitialSamples(pSample);
556              Unlock();              Unlock();
557          }          }
558          // make sure new sample reference is cached          // make sure new sample reference is cached
# Line 368  namespace LinuxSampler { namespace gig { Line 561  namespace LinuxSampler { namespace gig {
561              ::gig::Sample* pSample = (::gig::Sample*) pNewSample;              ::gig::Sample* pSample = (::gig::Sample*) pNewSample;
562              ::gig::File* pFile = (::gig::File*) pSample->GetParent();              ::gig::File* pFile = (::gig::File*) pSample->GetParent();
563              // get all engines that use that same gig::File              // get all engines that use that same gig::File
564              std::set<gig::Engine*> engines = GetEnginesUsing(pFile, false/*don't lock again*/);              std::set<Engine*> engines = GetEnginesUsing(pFile, false/*don't lock again*/);
565              std::set<gig::Engine*>::iterator iter = engines.begin();              std::set<Engine*>::iterator iter = engines.begin();
566              std::set<gig::Engine*>::iterator end  = engines.end();              std::set<Engine*>::iterator end  = engines.end();
567              for (; iter != end; ++iter)              for (; iter != end; ++iter)
568                  CacheInitialSamples(pSample, *iter);                  CacheInitialSamples(pSample, *iter);
569              Unlock();              Unlock();
# Line 379  namespace LinuxSampler { namespace gig { Line 572  namespace LinuxSampler { namespace gig {
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 internal 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 400  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 411  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 427  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 are 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                                                         RTList< ::gig::DimensionRegion*>* pDimRegionsInUse) {                  delete riff;
         DimRegInfoMutex.Lock();  
         for (RTList< ::gig::DimensionRegion*>::Iterator i = pDimRegionsInUse->first() ; i != pDimRegionsInUse->end() ; i++) {  
             DimRegInfo[*i].refCount++;  
             SampleRefCount[(*i)->pSample]++;  
         }  
         HandBack(pResource, pConsumer, true);  
         DimRegInfoMutex.Unlock();  
     }  
   
     /**  
      * Give back a dimension region that belongs to an instrument that  
      * was previously handed back.  
      */  
     void InstrumentResourceManager::HandBackDimReg(::gig::DimensionRegion* pDimReg) {  
         DimRegInfoMutex.Lock();  
         dimreg_info_t& dimRegInfo = DimRegInfo[pDimReg];  
         int dimRegRefCount = --dimRegInfo.refCount;  
         int sampleRefCount = --SampleRefCount[pDimReg->pSample];  
         if (dimRegRefCount == 0) {  
             ::gig::File* gig = dimRegInfo.file;  
             ::RIFF::File* riff = dimRegInfo.riff;  
             DimRegInfo.erase(pDimReg);  
             // 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;  
                     }  
                 }  
655              }              }
656          }          }
         DimRegInfoMutex.Unlock();  
657      }      }
658    
659      /**      /**
# Line 517  namespace LinuxSampler { namespace gig { Line 664  namespace LinuxSampler { namespace gig {
664       *                   (may be NULL, in this case default amount of samples       *                   (may be NULL, in this case default amount of samples
665       *                   will be cached)       *                   will be cached)
666       */       */
667      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::EngineChannel* pEngineChannel) {      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, EngineChannel* pEngineChannel) {
668          gig::Engine* pEngine =          Engine* pEngine =
669              (pEngineChannel && pEngineChannel->GetEngine()) ?              (pEngineChannel && pEngineChannel->GetEngine()) ?
670                  dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine()) : NULL;                  dynamic_cast<Engine*>(pEngineChannel->GetEngine()) : NULL;
671          CacheInitialSamples(pSample, pEngine);          CacheInitialSamples(pSample, pEngine);
672      }      }
673    
# Line 535  namespace LinuxSampler { namespace gig { Line 682  namespace LinuxSampler { namespace gig {
682       *                   (may be NULL, in this case default amount of samples       *                   (may be NULL, in this case default amount of samples
683       *                   will be cached)       *                   will be cached)
684       */       */
685      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::Engine* pEngine) {      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 548  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                  (pEngine) ? pEngine->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 567  namespace LinuxSampler { namespace gig { Line 718  namespace LinuxSampler { namespace gig {
718      }      }
719    
720      void InstrumentResourceManager::UncacheInitialSamples(::gig::Sample* pSample) {      void InstrumentResourceManager::UncacheInitialSamples(::gig::Sample* pSample) {
721          dmsg(1,("Uncaching sample %x\n",pSample));          dmsg(1,("Uncaching sample %p\n",(void*)pSample));
722          if (pSample->GetCache().Size) pSample->ReleaseSampleData();          if (pSample->GetCache().Size) pSample->ReleaseSampleData();
723      }      }
724    
# Line 593  namespace LinuxSampler { namespace gig { Line 744  namespace LinuxSampler { namespace gig {
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       * Returns a list with all gig Engines that are currently using the given
798       * instrument.       * instrument.
799       *       *
# Line 600  namespace LinuxSampler { namespace gig { Line 801  namespace LinuxSampler { namespace gig {
801       * @param bLock - whether we should lock (mutex) the instrument manager       * @param bLock - whether we should lock (mutex) the instrument manager
802       *                during this call and unlock at the end of this call       *                during this call and unlock at the end of this call
803       */       */
804      std::set<gig::Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::Instrument* pInstrument, bool bLock) {      std::set<Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::Instrument* pInstrument, bool bLock) {
805          if (bLock) Lock();          if (bLock) Lock();
806          std::set<gig::Engine*> result;          std::set<Engine*> result;
807          std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(pInstrument);          std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(pInstrument);
808          std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();          std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
809          std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();          std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();
810          for (; iter != end; ++iter) {          for (; iter != end; ++iter) {
811              gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(*iter);              EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
812              if (!pEngineChannel) continue;              if (!pEngineChannel) continue;
813              gig::Engine* pEngine = dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine());              Engine* pEngine = dynamic_cast<Engine*>(pEngineChannel->GetEngine());
814              if (!pEngine) continue;              if (!pEngine) continue;
815              result.insert(pEngine);              result.insert(pEngine);
816          }          }
# Line 625  namespace LinuxSampler { namespace gig { Line 826  namespace LinuxSampler { namespace gig {
826       * @param bLock - whether we should lock (mutex) the instrument manager       * @param bLock - whether we should lock (mutex) the instrument manager
827       *                during this call and unlock at the end of this call       *                during this call and unlock at the end of this call
828       */       */
829      std::set<gig::Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::File* pFile, bool bLock) {      std::set<Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::File* pFile, bool bLock) {
830          if (bLock) Lock();          if (bLock) Lock();
831          // get all instruments (currently in usage) that use that same gig::File          // get all instruments (currently in usage) that use that same gig::File
832          std::vector< ::gig::Instrument*> instrumentsOfInterest =          std::vector< ::gig::Instrument*> instrumentsOfInterest =
833              GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);              GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
834    
835          // get all engines that use that same gig::File          // get all engines that use that same gig::File
836          std::set<gig::Engine*> result;          std::set<Engine*> result;
837          {          {
838              for (int i = 0; i < instrumentsOfInterest.size(); i++) {              for (int i = 0; i < instrumentsOfInterest.size(); i++) {
839                  std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(instrumentsOfInterest[i]);                  std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(instrumentsOfInterest[i]);
840                  std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();                  std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
841                  std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();                  std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();
842                  for (; iter != end; ++iter) {                  for (; iter != end; ++iter) {
843                      gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(*iter);                      EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
844                      if (!pEngineChannel) continue;                      if (!pEngineChannel) continue;
845                      gig::Engine* pEngine = dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine());                      Engine* pEngine = dynamic_cast<Engine*>(pEngineChannel->GetEngine());
846                      if (!pEngine) continue;                      if (!pEngine) continue;
847                      // the unique, sorted container std::set makes                      // the unique, sorted container std::set makes
848                      // sure we won't have duplicates                      // sure we won't have duplicates
# Line 695  namespace LinuxSampler { namespace gig { Line 896  namespace LinuxSampler { namespace gig {
896          // get all engines that use that same gig::Instrument          // get all engines that use that same gig::Instrument
897          suspendedEngines = GetEnginesUsing(pInstrument, true/*lock*/);          suspendedEngines = GetEnginesUsing(pInstrument, true/*lock*/);
898          // finally, completely suspend all engines that use that same gig::Instrument          // finally, completely suspend all engines that use that same gig::Instrument
899          std::set<gig::Engine*>::iterator iter = suspendedEngines.begin();          std::set<Engine*>::iterator iter = suspendedEngines.begin();
900          std::set<gig::Engine*>::iterator end  = suspendedEngines.end();          std::set<Engine*>::iterator end  = suspendedEngines.end();
901          for (; iter != end; ++iter) (*iter)->SuspendAll();          for (; iter != end; ++iter) (*iter)->SuspendAll();
902      }      }
903    
# Line 719  namespace LinuxSampler { namespace gig { Line 920  namespace LinuxSampler { namespace gig {
920          // get all engines that use that same gig::File          // get all engines that use that same gig::File
921          suspendedEngines = GetEnginesUsing(pFile, true/*lock*/);          suspendedEngines = GetEnginesUsing(pFile, true/*lock*/);
922          // finally, completely suspend all engines that use that same gig::File          // finally, completely suspend all engines that use that same gig::File
923          std::set<gig::Engine*>::iterator iter = suspendedEngines.begin();          std::set<Engine*>::iterator iter = suspendedEngines.begin();
924          std::set<gig::Engine*>::iterator end  = suspendedEngines.end();          std::set<Engine*>::iterator end  = suspendedEngines.end();
925          for (; iter != end; ++iter) (*iter)->SuspendAll();          for (; iter != end; ++iter) (*iter)->SuspendAll();
926      }      }
927    
# Line 755  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 776  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.1646  
changed lines
  Added in v.3734

  ViewVC Help
Powered by ViewVC