/[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 2275 by schoenebeck, Mon Sep 19 21:48:45 2011 UTC
# Line 3  Line 3 
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6   *   Copyright (C) 2005 - 2008 Christian Schoenebeck                       *   *   Copyright (C) 2005 - 2011 Christian Schoenebeck                       *
7   *                                                                         *   *                                                                         *
8   *   This program is free software; you can redistribute it and/or modify  *   *   This program is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 24  Line 24 
24  #include <sstream>  #include <sstream>
25    
26  #include "InstrumentResourceManager.h"  #include "InstrumentResourceManager.h"
27    #include "EngineChannel.h"
28    #include "Engine.h"
29    
30  #include "../../common/global_private.h"  #include "../../common/global_private.h"
31  #include "../../plugins/InstrumentEditorFactory.h"  #include "../../plugins/InstrumentEditorFactory.h"
32    
 // 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  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
34    
35      // data stored as long as an instrument resource exists      // data stored as long as an instrument resource exists
# Line 67  namespace LinuxSampler { namespace gig { Line 62  namespace LinuxSampler { namespace gig {
62    
63          // the instrument we borrowed on behalf of the editor          // the instrument we borrowed on behalf of the editor
64          ::gig::Instrument* pInstrument;          ::gig::Instrument* pInstrument;
65            // the instrument editor we work on behalf
66            InstrumentEditor* pEditor;
67      };      };
68    
69      /**      /**
# Line 90  namespace LinuxSampler { namespace gig { Line 87  namespace LinuxSampler { namespace gig {
87          return Entries();          return Entries();
88      }      }
89    
     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));  
     }  
   
90      String InstrumentResourceManager::GetInstrumentName(instrument_id_t ID) {      String InstrumentResourceManager::GetInstrumentName(instrument_id_t ID) {
91          Lock();          Lock();
92          ::gig::Instrument* pInstrument = Resource(ID, false);          ::gig::Instrument* pInstrument = Resource(ID, false);
# Line 144  namespace LinuxSampler { namespace gig { Line 132  namespace LinuxSampler { namespace gig {
132      }      }
133    
134      InstrumentResourceManager::instrument_info_t InstrumentResourceManager::GetInstrumentInfo(instrument_id_t ID) throw (InstrumentManagerException) {      InstrumentResourceManager::instrument_info_t InstrumentResourceManager::GetInstrumentInfo(instrument_id_t ID) throw (InstrumentManagerException) {
135          std::vector<instrument_id_t> result;          Lock();
136            ::gig::Instrument* pInstrument = Resource(ID, false);
137            bool loaded = (pInstrument != NULL);
138            if (!loaded) Unlock();
139    
140          ::RIFF::File* riff = NULL;          ::RIFF::File* riff = NULL;
141          ::gig::File*  gig  = NULL;          ::gig::File*  gig  = NULL;
142          try {          try {
143              riff = new ::RIFF::File(ID.FileName);              if(!loaded) {
144              gig  = new ::gig::File(riff);                  riff = new ::RIFF::File(ID.FileName);
145              gig->SetAutoLoad(false); // avoid time consuming samples scanning                  gig  = new ::gig::File(riff);
146              ::gig::Instrument* pInstrument = gig->GetInstrument(ID.Index);                  gig->SetAutoLoad(false); // avoid time consuming samples scanning
147                    pInstrument = gig->GetInstrument(ID.Index);
148                }
149    
150              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);
151    
152              instrument_info_t info;              instrument_info_t info;
153              if (gig->pVersion) {              for (int i = 0; i < 128; i++) { info.KeyBindings[i] = info.KeySwitchBindings[i] = 0; }
154                  info.FormatVersion = ToString(gig->pVersion->major);  
155                  info.Product = gig->pInfo->Product;              ::gig::File* pFile = (::gig::File*) pInstrument->GetParent();
156                  info.Artists = gig->pInfo->Artists;  
157                if (pFile->pVersion) {
158                    info.FormatVersion = ToString(pFile->pVersion->major);
159                    info.Product = pFile->pInfo->Product;
160                    info.Artists = pFile->pInfo->Artists;
161              }              }
162    
163              info.InstrumentName = pInstrument->pInfo->Name;              info.InstrumentName = pInstrument->pInfo->Name;
164    
165                ::gig::Region* pRegion = pInstrument->GetFirstRegion();
166                while (pRegion) {
167                    int low = pRegion->KeyRange.low;
168                    int high = pRegion->KeyRange.high;
169                    if (low < 0 || low > 127 || high < 0 || high > 127 || low > high) {
170                        std::cerr << "Invalid key range: " << low << " - " << high << std::endl;
171                    } else {
172                        for (int i = low; i <= high; i++) info.KeyBindings[i] = 1;
173                    }
174    
175                    pRegion = pInstrument->GetNextRegion();
176                }
177    
178                if (loaded) { // retrieve keyswitching only if the instrument is fully loaded.
179    
180                    // only return keyswitch range if keyswitching is used
181                    bool hasKeyswitches = false;
182                    for (::gig::Region* pRegion = pInstrument->GetFirstRegion() ;
183                         pRegion && !hasKeyswitches ;
184                         pRegion = pInstrument->GetNextRegion()) {
185                        for (int i = 0 ; i < pRegion->Dimensions ; i++) {
186                            if (pRegion->pDimensionDefinitions[i].dimension == ::gig::dimension_keyboard) {
187                                hasKeyswitches = true;
188                                break;
189                            }
190                        }
191                    }
192    
193                    if (hasKeyswitches) {
194                        int low = pInstrument->DimensionKeyRange.low;
195                        int high = pInstrument->DimensionKeyRange.high;
196                        if (low < 0 || low > 127 || high < 0 || high > 127 || low > high) {
197                            std::cerr << "Invalid keyswitch range: " << low << " - " << high << std::endl;
198                        } else {
199                            for (int i = low; i <= high; i++) info.KeySwitchBindings[i] = 1;
200                        }
201                    }
202                }
203    
204                if (loaded) Unlock();
205    
206              if (gig)  delete gig;              if (gig)  delete gig;
207              if (riff) delete riff;              if (riff) delete riff;
208              return info;              return info;
209          } catch (::RIFF::Exception e) {          } catch (::RIFF::Exception e) {
210                if (loaded) Unlock();
211              if (gig)  delete gig;              if (gig)  delete gig;
212              if (riff) delete riff;              if (riff) delete riff;
213              throw InstrumentManagerException(e.Message);              throw InstrumentManagerException(e.Message);
214          } catch (...) {          } catch (...) {
215                if (loaded) Unlock();
216              if (gig)  delete gig;              if (gig)  delete gig;
217              if (riff) delete riff;              if (riff) delete riff;
218              throw InstrumentManagerException("Unknown exception while trying to parse '" + ID.FileName + "'");              throw InstrumentManagerException("Unknown exception while trying to parse '" + ID.FileName + "'");
219          }          }
220      }      }
221    
222      void InstrumentResourceManager::LaunchInstrumentEditor(instrument_id_t ID) throw (InstrumentManagerException) {      InstrumentEditor* InstrumentResourceManager::LaunchInstrumentEditor(instrument_id_t ID, void* pUserData) throw (InstrumentManagerException) {
223          const String sDataType    = GetInstrumentDataStructureName(ID);          const String sDataType    = GetInstrumentDataStructureName(ID);
224          const String sDataVersion = GetInstrumentDataStructureVersion(ID);          const String sDataVersion = GetInstrumentDataStructureVersion(ID);
225          // find instrument editors capable to handle given instrument          // find instrument editors capable to handle given instrument
# Line 196  namespace LinuxSampler { namespace gig { Line 241  namespace LinuxSampler { namespace gig {
241          ::gig::Instrument* pInstrument = Borrow(ID, pProxy);          ::gig::Instrument* pInstrument = Borrow(ID, pProxy);
242          // remember the proxy and instrument for this instrument editor          // remember the proxy and instrument for this instrument editor
243          pProxy->pInstrument = pInstrument;          pProxy->pInstrument = pInstrument;
244            pProxy->pEditor     = pEditor;
245          InstrumentEditorProxiesMutex.Lock();          InstrumentEditorProxiesMutex.Lock();
246          InstrumentEditorProxies[pEditor] = pProxy;          InstrumentEditorProxies.add(pProxy);
247          InstrumentEditorProxiesMutex.Unlock();          InstrumentEditorProxiesMutex.Unlock();
248          // launch the instrument editor for the given instrument          // launch the instrument editor for the given instrument
249          pEditor->Launch(pInstrument, sDataType, sDataVersion);          pEditor->Launch(pInstrument, sDataType, sDataVersion, pUserData);
250    
251            // register the instrument editor as virtual MIDI device as well ...
252            VirtualMidiDevice* pVirtualMidiDevice =
253                dynamic_cast<VirtualMidiDevice*>(pEditor);
254            if (!pVirtualMidiDevice) {
255                std::cerr << "Instrument editor not a virtual MIDI device\n" << std::flush;
256                return pEditor;
257            }
258            // 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 ? )
259            Lock();
260            std::set<EngineChannel*> engineChannels =
261                GetEngineChannelsUsing(pInstrument, false/*don't lock again*/);
262            std::set<EngineChannel*>::iterator iter = engineChannels.begin();
263            std::set<EngineChannel*>::iterator end  = engineChannels.end();
264            for (; iter != end; ++iter) (static_cast<AbstractEngineChannel*>(*iter))->Connect(pVirtualMidiDevice);
265            Unlock();
266    
267            return pEditor;
268      }      }
269    
270      /**      /**
# Line 212  namespace LinuxSampler { namespace gig { Line 276  namespace LinuxSampler { namespace gig {
276       */       */
277      void InstrumentResourceManager::OnInstrumentEditorQuit(InstrumentEditor* pSender) {      void InstrumentResourceManager::OnInstrumentEditorQuit(InstrumentEditor* pSender) {
278          dmsg(1,("InstrumentResourceManager: instrument editor quit, doing cleanup\n"));          dmsg(1,("InstrumentResourceManager: instrument editor quit, doing cleanup\n"));
279          // hand back instrument and free proxy  
280            ::gig::Instrument* pInstrument = NULL;
281            InstrumentEditorProxy* pProxy  = NULL;
282            int iProxyIndex                = -1;
283    
284            // first find the editor proxy entry for this editor
285          InstrumentEditorProxiesMutex.Lock();          InstrumentEditorProxiesMutex.Lock();
286          if (InstrumentEditorProxies.count(pSender)) {          for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
287              InstrumentEditorProxy* pProxy =              InstrumentEditorProxy* pCurProxy =
288                  dynamic_cast<InstrumentEditorProxy*>(                  dynamic_cast<InstrumentEditorProxy*>(
289                      InstrumentEditorProxies[pSender]                      InstrumentEditorProxies[i]
290                  );                  );
291              InstrumentEditorProxies.erase(pSender);              if (pCurProxy->pEditor == pSender) {
292              InstrumentEditorProxiesMutex.Unlock();                  pProxy      = pCurProxy;
293              HandBack(pProxy->pInstrument, pProxy);                  iProxyIndex = i;
294              if (pProxy) delete pProxy;                  pInstrument = pCurProxy->pInstrument;
295                }
296            }
297            InstrumentEditorProxiesMutex.Unlock();
298    
299            if (!pProxy) {
300                std::cerr << "Eeeek, could not find instrument editor proxy, "
301                             "this is a bug!\n" << std::flush;
302                return;
303            }
304    
305            // now unregister editor as not being available as a virtual MIDI device anymore
306            VirtualMidiDevice* pVirtualMidiDevice =
307                dynamic_cast<VirtualMidiDevice*>(pSender);
308            if (pVirtualMidiDevice) {
309                Lock();
310                // NOTE: see note in LaunchInstrumentEditor()
311                std::set<EngineChannel*> engineChannels =
312                    GetEngineChannelsUsing(pInstrument, false/*don't lock again*/);
313                std::set<EngineChannel*>::iterator iter = engineChannels.begin();
314                std::set<EngineChannel*>::iterator end  = engineChannels.end();
315                for (; iter != end; ++iter) (*iter)->Disconnect(pVirtualMidiDevice);
316                Unlock();
317          } else {          } else {
318                std::cerr << "Could not unregister editor as not longer acting as "
319                             "virtual MIDI device. Wasn't it registered?\n"
320                          << std::flush;
321            }
322    
323            // finally delete proxy entry and hand back instrument
324            if (pInstrument) {
325                InstrumentEditorProxiesMutex.Lock();
326                InstrumentEditorProxies.remove(iProxyIndex);
327              InstrumentEditorProxiesMutex.Unlock();              InstrumentEditorProxiesMutex.Unlock();
328              std::cerr << "Eeeek, could not find instrument editor proxy, this is a bug!\n" << std::flush;  
329                HandBack(pInstrument, pProxy);
330                delete pProxy;
331          }          }
332    
333          // 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 335  namespace LinuxSampler { namespace gig {
335          // dies.          // dies.
336      }      }
337    
338    #if 0 // currently unused :
339        /**
340         * Try to inform the respective instrument editor(s), that a note on
341         * event just occured. This method is called by the MIDI thread. If any
342         * obstacles are in the way (e.g. if a wait for an unlock would be
343         * required) we give up immediately, since the RT safeness of the MIDI
344         * thread has absolute priority.
345         */
346        void InstrumentResourceManager::TrySendNoteOnToEditors(uint8_t Key, uint8_t Velocity, ::gig::Instrument* pInstrument) {
347            const bool bGotLock = InstrumentEditorProxiesMutex.Trylock(); // naively assumes RT safe implementation
348            if (!bGotLock) return; // hell, forget it, not worth the hassle
349            for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
350                InstrumentEditorProxy* pProxy =
351                    dynamic_cast<InstrumentEditorProxy*>(
352                        InstrumentEditorProxies[i]
353                    );
354                if (pProxy->pInstrument == pInstrument)
355                    pProxy->pEditor->SendNoteOnToDevice(Key, Velocity);
356            }
357            InstrumentEditorProxiesMutex.Unlock(); // naively assumes RT safe implementation
358        }
359    
360        /**
361         * Try to inform the respective instrument editor(s), that a note off
362         * event just occured. This method is called by the MIDI thread. If any
363         * obstacles are in the way (e.g. if a wait for an unlock would be
364         * required) we give up immediately, since the RT safeness of the MIDI
365         * thread has absolute priority.
366         */
367        void InstrumentResourceManager::TrySendNoteOffToEditors(uint8_t Key, uint8_t Velocity, ::gig::Instrument* pInstrument) {
368            const bool bGotLock = InstrumentEditorProxiesMutex.Trylock(); // naively assumes RT safe implementation
369            if (!bGotLock) return; // hell, forget it, not worth the hassle
370            for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
371                InstrumentEditorProxy* pProxy =
372                    dynamic_cast<InstrumentEditorProxy*>(
373                        InstrumentEditorProxies[i]
374                    );
375                if (pProxy->pInstrument == pInstrument)
376                    pProxy->pEditor->SendNoteOffToDevice(Key, Velocity);
377            }
378            InstrumentEditorProxiesMutex.Unlock(); // naively assumes RT safe implementation
379        }
380    #endif // unused
381    
382      void InstrumentResourceManager::OnSamplesToBeRemoved(std::set<void*> Samples, InstrumentEditor* pSender) {      void InstrumentResourceManager::OnSamplesToBeRemoved(std::set<void*> Samples, InstrumentEditor* pSender) {
383          if (Samples.empty()) {          if (Samples.empty()) {
384              std::cerr << "gig::InstrumentResourceManager: WARNING, "              std::cerr << "gig::InstrumentResourceManager: WARNING, "
# Line 272  namespace LinuxSampler { namespace gig { Line 418  namespace LinuxSampler { namespace gig {
418              ::gig::Instrument* pInstrument =              ::gig::Instrument* pInstrument =
419                  (::gig::Instrument*) pRegion->GetParent();                  (::gig::Instrument*) pRegion->GetParent();
420              Lock();              Lock();
421              std::set<gig::Engine*> engines =              std::set<Engine*> engines =
422                  GetEnginesUsing(pInstrument, false/*don't lock again*/);                  GetEnginesUsing(pInstrument, false/*don't lock again*/);
423              std::set<gig::Engine*>::iterator iter = engines.begin();              std::set<Engine*>::iterator iter = engines.begin();
424              std::set<gig::Engine*>::iterator end  = engines.end();              std::set<Engine*>::iterator end  = engines.end();
425              for (; iter != end; ++iter) (*iter)->Suspend(pRegion);              for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
426              Unlock();              Unlock();
427          } else if (sStructType == "gig::DimensionRegion") {          } else if (sStructType == "gig::DimensionRegion") {
# Line 289  namespace LinuxSampler { namespace gig { Line 435  namespace LinuxSampler { namespace gig {
435              ::gig::Instrument* pInstrument =              ::gig::Instrument* pInstrument =
436                  (::gig::Instrument*) pRegion->GetParent();                  (::gig::Instrument*) pRegion->GetParent();
437              Lock();              Lock();
438              std::set<gig::Engine*> engines =              std::set<Engine*> engines =
439                  GetEnginesUsing(pInstrument, false/*don't lock again*/);                  GetEnginesUsing(pInstrument, false/*don't lock again*/);
440              std::set<gig::Engine*>::iterator iter = engines.begin();              std::set<Engine*>::iterator iter = engines.begin();
441              std::set<gig::Engine*>::iterator end  = engines.end();              std::set<Engine*>::iterator end  = engines.end();
442              for (; iter != end; ++iter) (*iter)->Suspend(pRegion);              for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
443              Unlock();              Unlock();
444          } else {          } else {
# Line 312  namespace LinuxSampler { namespace gig { Line 458  namespace LinuxSampler { namespace gig {
458          } else if (sStructType == "gig::Instrument") {          } else if (sStructType == "gig::Instrument") {
459              // resume all previously suspended engines              // resume all previously suspended engines
460              ResumeAllEngines();              ResumeAllEngines();
461            } else if (sStructType == "gig::Sample") {
462                // we're assuming here, that OnDataStructureToBeChanged() with
463                // "gig::File" was called previously, so we won't resume anything
464                // here, but just re-cache the given sample
465                Lock();
466                ::gig::Sample* pSample = (::gig::Sample*) pStruct;
467                ::gig::File* pFile = (::gig::File*) pSample->GetParent();
468                UncacheInitialSamples(pSample);
469                // now re-cache ...
470                std::vector< ::gig::Instrument*> instruments =
471                    GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
472                for (int i = 0; i < instruments.size(); i++) {
473                    if (SampleReferencedByInstrument(pSample, instruments[i])) {
474                        std::set<EngineChannel*> engineChannels =
475                            GetEngineChannelsUsing(instruments[i], false/*don't lock again*/);
476                        std::set<EngineChannel*>::iterator iter = engineChannels.begin();
477                        std::set<EngineChannel*>::iterator end  = engineChannels.end();
478                        for (; iter != end; ++iter)
479                            CacheInitialSamples(pSample, *iter);
480                    }
481                }
482                Unlock();
483          } else if (sStructType == "gig::Region") {          } else if (sStructType == "gig::Region") {
484              // advice the engines to resume the given region, that is to              // advice the engines to resume the given region, that is to
485              // using it for playback again              // using it for playback again
# Line 319  namespace LinuxSampler { namespace gig { Line 487  namespace LinuxSampler { namespace gig {
487              ::gig::Instrument* pInstrument =              ::gig::Instrument* pInstrument =
488                  (::gig::Instrument*) pRegion->GetParent();                  (::gig::Instrument*) pRegion->GetParent();
489              Lock();              Lock();
490              std::set<gig::Engine*> engines =              std::set<Engine*> engines =
491                  GetEnginesUsing(pInstrument, false/*don't lock again*/);                  GetEnginesUsing(pInstrument, false/*don't lock again*/);
492              std::set<gig::Engine*>::iterator iter = engines.begin();              std::set<Engine*>::iterator iter = engines.begin();
493              std::set<gig::Engine*>::iterator end  = engines.end();              std::set<Engine*>::iterator end  = engines.end();
494              for (; iter != end; ++iter) (*iter)->Resume(pRegion);              for (; iter != end; ++iter) (*iter)->Resume(pRegion);
495              Unlock();              Unlock();
496          } else if (sStructType == "gig::DimensionRegion") {          } else if (sStructType == "gig::DimensionRegion") {
# Line 334  namespace LinuxSampler { namespace gig { Line 502  namespace LinuxSampler { namespace gig {
502              ::gig::Instrument* pInstrument =              ::gig::Instrument* pInstrument =
503                  (::gig::Instrument*) pRegion->GetParent();                  (::gig::Instrument*) pRegion->GetParent();
504              Lock();              Lock();
505              std::set<gig::Engine*> engines =              std::set<Engine*> engines =
506                  GetEnginesUsing(pInstrument, false/*don't lock again*/);                  GetEnginesUsing(pInstrument, false/*don't lock again*/);
507              std::set<gig::Engine*>::iterator iter = engines.begin();              std::set<Engine*>::iterator iter = engines.begin();
508              std::set<gig::Engine*>::iterator end  = engines.end();              std::set<Engine*>::iterator end  = engines.end();
509              for (; iter != end; ++iter) (*iter)->Resume(pRegion);              for (; iter != end; ++iter) (*iter)->Resume(pRegion);
510              Unlock();              Unlock();
511          } else {          } else {
# Line 355  namespace LinuxSampler { namespace gig { Line 523  namespace LinuxSampler { namespace gig {
523              Lock();              Lock();
524              ::gig::Sample* pSample = (::gig::Sample*) pOldSample;              ::gig::Sample* pSample = (::gig::Sample*) pOldSample;
525              ::gig::File* pFile = (::gig::File*) pSample->GetParent();              ::gig::File* pFile = (::gig::File*) pSample->GetParent();
526                bool bSampleStillInUse = false;
527              std::vector< ::gig::Instrument*> instruments =              std::vector< ::gig::Instrument*> instruments =
528                  GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);                  GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
529              for (int i = 0; i < instruments.size(); i++)              for (int i = 0; i < instruments.size(); i++) {
530                  if (!SampleReferencedByInstrument(pSample, instruments[i]))                  if (SampleReferencedByInstrument(pSample, instruments[i])) {
531                      UncacheInitialSamples(pSample);                      bSampleStillInUse = true;
532                        break;
533                    }
534                }
535                if (!bSampleStillInUse) UncacheInitialSamples(pSample);
536              Unlock();              Unlock();
537          }          }
538          // make sure new sample reference is cached          // make sure new sample reference is cached
# Line 368  namespace LinuxSampler { namespace gig { Line 541  namespace LinuxSampler { namespace gig {
541              ::gig::Sample* pSample = (::gig::Sample*) pNewSample;              ::gig::Sample* pSample = (::gig::Sample*) pNewSample;
542              ::gig::File* pFile = (::gig::File*) pSample->GetParent();              ::gig::File* pFile = (::gig::File*) pSample->GetParent();
543              // get all engines that use that same gig::File              // get all engines that use that same gig::File
544              std::set<gig::Engine*> engines = GetEnginesUsing(pFile, false/*don't lock again*/);              std::set<Engine*> engines = GetEnginesUsing(pFile, false/*don't lock again*/);
545              std::set<gig::Engine*>::iterator iter = engines.begin();              std::set<Engine*>::iterator iter = engines.begin();
546              std::set<gig::Engine*>::iterator end  = engines.end();              std::set<Engine*>::iterator end  = engines.end();
547              for (; iter != end; ++iter)              for (; iter != end; ++iter)
548                  CacheInitialSamples(pSample, *iter);                  CacheInitialSamples(pSample, *iter);
549              Unlock();              Unlock();
# Line 379  namespace LinuxSampler { namespace gig { Line 552  namespace LinuxSampler { namespace gig {
552    
553      ::gig::Instrument* InstrumentResourceManager::Create(instrument_id_t Key, InstrumentConsumer* pConsumer, void*& pArg) {      ::gig::Instrument* InstrumentResourceManager::Create(instrument_id_t Key, InstrumentConsumer* pConsumer, void*& pArg) {
554          // get gig file from internal gig file manager          // get gig file from internal gig file manager
555          ::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 :/
556    
557          // we pass this to the progress callback mechanism of libgig          // we pass this to the progress callback mechanism of libgig
558          progress_callback_arg_t callbackArg;          progress_callback_arg_t callbackArg;
# Line 411  namespace LinuxSampler { namespace gig { Line 584  namespace LinuxSampler { namespace gig {
584    
585              if (pRgn->GetSample() && !pRgn->GetSample()->GetCache().Size) {              if (pRgn->GetSample() && !pRgn->GetSample()->GetCache().Size) {
586                  dmsg(2,("C"));                  dmsg(2,("C"));
587                  CacheInitialSamples(pRgn->GetSample(), (gig::EngineChannel*) pConsumer);                  CacheInitialSamples(pRgn->GetSample(), (EngineChannel*) pConsumer);
588              }              }
589              for (uint i = 0; i < pRgn->DimensionRegions; i++) {              for (uint i = 0; i < pRgn->DimensionRegions; i++) {
590                  CacheInitialSamples(pRgn->pDimensionRegions[i]->pSample, (gig::EngineChannel*) pConsumer);                  CacheInitialSamples(pRgn->pDimensionRegions[i]->pSample, (EngineChannel*) pConsumer);
591              }              }
592    
593              pRgn = pInstrument->GetNextRegion();              pRgn = pInstrument->GetNextRegion();
# Line 429  namespace LinuxSampler { namespace gig { Line 602  namespace LinuxSampler { namespace gig {
602          pEntry->ID.Index      = Key.Index;          pEntry->ID.Index      = Key.Index;
603          pEntry->pGig          = pGig;          pEntry->pGig          = pGig;
604    
605          gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(pConsumer);          // (try to resolve the audio device context)
606            EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(pConsumer);
607            AudioOutputDevice* pDevice =
608                (pEngineChannel) ? dynamic_cast<Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice : NULL;
609            
610          // and we save this to check if we need to reallocate for a engine with higher value of 'MaxSamplesPerSecond'          // and we save this to check if we need to reallocate for a engine with higher value of 'MaxSamplesPerSecond'
611          pEntry->MaxSamplesPerCycle =          pEntry->MaxSamplesPerCycle =
612              (!pEngineChannel) ? 0 /* don't care for instrument editors */ :              (pDevice) ? pDevice->MaxSamplesPerCycle() : DefaultMaxSamplesPerCycle();
613                  (pEngineChannel->GetEngine()) ?          
                     dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()  
                     : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;  
614          pArg = pEntry;          pArg = pEntry;
615    
616          return pInstrument;          return pInstrument;
# Line 444  namespace LinuxSampler { namespace gig { Line 619  namespace LinuxSampler { namespace gig {
619      void InstrumentResourceManager::Destroy( ::gig::Instrument* pResource, void* pArg) {      void InstrumentResourceManager::Destroy( ::gig::Instrument* pResource, void* pArg) {
620          instr_entry_t* pEntry = (instr_entry_t*) pArg;          instr_entry_t* pEntry = (instr_entry_t*) pArg;
621          // we don't need the .gig file here anymore          // we don't need the .gig file here anymore
622          Gigs.HandBack(pEntry->pGig, (GigConsumer*) pEntry->ID.Index); // conversion kinda hackish :/          Gigs.HandBack(pEntry->pGig, reinterpret_cast<GigConsumer*>(pEntry->ID.Index)); // conversion kinda hackish :/
623          delete pEntry;          delete pEntry;
624      }      }
625    
626      void InstrumentResourceManager::OnBorrow(::gig::Instrument* pResource, InstrumentConsumer* pConsumer, void*& pArg) {      void InstrumentResourceManager::OnBorrow(::gig::Instrument* pResource, InstrumentConsumer* pConsumer, void*& pArg) {
627          instr_entry_t* pEntry = (instr_entry_t*) pArg;          instr_entry_t* pEntry = (instr_entry_t*) pArg;
628          gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(pConsumer);          
629            // (try to resolve the audio device context)
630            EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(pConsumer);
631            AudioOutputDevice* pDevice =
632                (pEngineChannel) ? dynamic_cast<Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice : NULL;
633            
634          uint maxSamplesPerCycle =          uint maxSamplesPerCycle =
635              (pEngineChannel && pEngineChannel->GetEngine()) ? dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()              (pDevice) ? pDevice->MaxSamplesPerCycle() : DefaultMaxSamplesPerCycle();
636                                            : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;  
637          if (pEntry->MaxSamplesPerCycle < maxSamplesPerCycle) {          if (pEntry->MaxSamplesPerCycle < maxSamplesPerCycle) {
638                dmsg(1,("Completely reloading instrument due to insufficient precached samples ...\n"));
639              Update(pResource, pConsumer);              Update(pResource, pConsumer);
640          }          }
641      }      }
642    
643      /**      void InstrumentResourceManager::DeleteRegionIfNotUsed(::gig::DimensionRegion* pRegion, region_info_t* pRegInfo) {
644       * Give back an instrument. This should be used instead of          // TODO: we could delete Region and Instrument here if they have become unused
      * HandBack if there are some dimension regions that are still in  
      * use. (When an instrument is changed, the voices currently  
      * playing are allowed to keep playing with the old instrument  
      * until note off arrives. New notes will use the new instrument.)  
      */  
     void InstrumentResourceManager::HandBackInstrument(::gig::Instrument* pResource, InstrumentConsumer* pConsumer,  
                                                        RTList< ::gig::DimensionRegion*>* pDimRegionsInUse) {  
         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();  
645      }      }
646    
647      /**      void InstrumentResourceManager::DeleteSampleIfNotUsed(::gig::Sample* pSample, region_info_t* pRegInfo) {
648       * Give back a dimension region that belongs to an instrument that          ::gig::File* gig = pRegInfo->file;
649       * was previously handed back.          ::RIFF::File* riff = static_cast< ::RIFF::File*>(pRegInfo->pArg);
650       */          if (gig) {
651      void InstrumentResourceManager::HandBackDimReg(::gig::DimensionRegion* pDimReg) {              gig->DeleteSample(pSample);
652          DimRegInfoMutex.Lock();              if (!gig->GetFirstSample()) {
653          dimreg_info_t& dimRegInfo = DimRegInfo[pDimReg];                  dmsg(2,("No more samples in use - freeing gig\n"));
654          int dimRegRefCount = --dimRegInfo.refCount;                  delete gig;
655          int sampleRefCount = --SampleRefCount[pDimReg->pSample];                  delete riff;
         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;  
                     }  
                 }  
656              }              }
657          }          }
         DimRegInfoMutex.Unlock();  
658      }      }
659    
660      /**      /**
# Line 517  namespace LinuxSampler { namespace gig { Line 665  namespace LinuxSampler { namespace gig {
665       *                   (may be NULL, in this case default amount of samples       *                   (may be NULL, in this case default amount of samples
666       *                   will be cached)       *                   will be cached)
667       */       */
668      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::EngineChannel* pEngineChannel) {      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, EngineChannel* pEngineChannel) {
669          gig::Engine* pEngine =          Engine* pEngine =
670              (pEngineChannel && pEngineChannel->GetEngine()) ?              (pEngineChannel && pEngineChannel->GetEngine()) ?
671                  dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine()) : NULL;                  dynamic_cast<Engine*>(pEngineChannel->GetEngine()) : NULL;
672          CacheInitialSamples(pSample, pEngine);          CacheInitialSamples(pSample, pEngine);
673      }      }
674    
# Line 535  namespace LinuxSampler { namespace gig { Line 683  namespace LinuxSampler { namespace gig {
683       *                   (may be NULL, in this case default amount of samples       *                   (may be NULL, in this case default amount of samples
684       *                   will be cached)       *                   will be cached)
685       */       */
686      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::Engine* pEngine) {      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, AbstractEngine* pEngine) {
687          if (!pSample) {          if (!pSample) {
688              dmsg(4,("gig::InstrumentResourceManager: Skipping sample (pSample == NULL)\n"));              dmsg(4,("gig::InstrumentResourceManager: Skipping sample (pSample == NULL)\n"));
689              return;              return;
# Line 550  namespace LinuxSampler { namespace gig { Line 698  namespace LinuxSampler { namespace gig {
698              // the sample.              // the sample.
699              const uint maxSamplesPerCycle =              const uint maxSamplesPerCycle =
700                  (pEngine) ? pEngine->pAudioOutputDevice->MaxSamplesPerCycle()                  (pEngine) ? pEngine->pAudioOutputDevice->MaxSamplesPerCycle()
701                            : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;                            : DefaultMaxSamplesPerCycle();
702              const uint neededSilenceSamples = (maxSamplesPerCycle << CONFIG_MAX_PITCH) + 3;              const uint neededSilenceSamples = (maxSamplesPerCycle << CONFIG_MAX_PITCH) + 3;
703              const uint currentlyCachedSilenceSamples = pSample->GetCache().NullExtensionSize / pSample->FrameSize;              const uint currentlyCachedSilenceSamples = pSample->GetCache().NullExtensionSize / pSample->FrameSize;
704              if (currentlyCachedSilenceSamples < neededSilenceSamples) {              if (currentlyCachedSilenceSamples < neededSilenceSamples) {
# Line 593  namespace LinuxSampler { namespace gig { Line 741  namespace LinuxSampler { namespace gig {
741      }      }
742    
743      /**      /**
744         * Returns a list with all gig engine channels that are currently using
745         * the given instrument.
746         *
747         * @param pInstrument - search criteria
748         * @param bLock - whether we should lock (mutex) the instrument manager
749         *                during this call and unlock at the end of this call
750         */
751        std::set<EngineChannel*> InstrumentResourceManager::GetEngineChannelsUsing(::gig::Instrument* pInstrument, bool bLock) {
752            if (bLock) Lock();
753            std::set<EngineChannel*> result;
754            std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(pInstrument);
755            std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
756            std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();
757            for (; iter != end; ++iter) {
758                EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
759                if (!pEngineChannel) continue;
760                result.insert(pEngineChannel);
761            }
762            if (bLock) Unlock();
763            return result;
764        }
765    
766        /**
767       * 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
768       * instrument.       * instrument.
769       *       *
# Line 600  namespace LinuxSampler { namespace gig { Line 771  namespace LinuxSampler { namespace gig {
771       * @param bLock - whether we should lock (mutex) the instrument manager       * @param bLock - whether we should lock (mutex) the instrument manager
772       *                during this call and unlock at the end of this call       *                during this call and unlock at the end of this call
773       */       */
774      std::set<gig::Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::Instrument* pInstrument, bool bLock) {      std::set<Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::Instrument* pInstrument, bool bLock) {
775          if (bLock) Lock();          if (bLock) Lock();
776          std::set<gig::Engine*> result;          std::set<Engine*> result;
777          std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(pInstrument);          std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(pInstrument);
778          std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();          std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
779          std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();          std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();
780          for (; iter != end; ++iter) {          for (; iter != end; ++iter) {
781              gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(*iter);              EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
782              if (!pEngineChannel) continue;              if (!pEngineChannel) continue;
783              gig::Engine* pEngine = dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine());              Engine* pEngine = dynamic_cast<Engine*>(pEngineChannel->GetEngine());
784              if (!pEngine) continue;              if (!pEngine) continue;
785              result.insert(pEngine);              result.insert(pEngine);
786          }          }
# Line 625  namespace LinuxSampler { namespace gig { Line 796  namespace LinuxSampler { namespace gig {
796       * @param bLock - whether we should lock (mutex) the instrument manager       * @param bLock - whether we should lock (mutex) the instrument manager
797       *                during this call and unlock at the end of this call       *                during this call and unlock at the end of this call
798       */       */
799      std::set<gig::Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::File* pFile, bool bLock) {      std::set<Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::File* pFile, bool bLock) {
800          if (bLock) Lock();          if (bLock) Lock();
801          // get all instruments (currently in usage) that use that same gig::File          // get all instruments (currently in usage) that use that same gig::File
802          std::vector< ::gig::Instrument*> instrumentsOfInterest =          std::vector< ::gig::Instrument*> instrumentsOfInterest =
803              GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);              GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
804    
805          // get all engines that use that same gig::File          // get all engines that use that same gig::File
806          std::set<gig::Engine*> result;          std::set<Engine*> result;
807          {          {
808              for (int i = 0; i < instrumentsOfInterest.size(); i++) {              for (int i = 0; i < instrumentsOfInterest.size(); i++) {
809                  std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(instrumentsOfInterest[i]);                  std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(instrumentsOfInterest[i]);
810                  std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();                  std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
811                  std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();                  std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();
812                  for (; iter != end; ++iter) {                  for (; iter != end; ++iter) {
813                      gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(*iter);                      EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
814                      if (!pEngineChannel) continue;                      if (!pEngineChannel) continue;
815                      gig::Engine* pEngine = dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine());                      Engine* pEngine = dynamic_cast<Engine*>(pEngineChannel->GetEngine());
816                      if (!pEngine) continue;                      if (!pEngine) continue;
817                      // the unique, sorted container std::set makes                      // the unique, sorted container std::set makes
818                      // sure we won't have duplicates                      // sure we won't have duplicates
# Line 695  namespace LinuxSampler { namespace gig { Line 866  namespace LinuxSampler { namespace gig {
866          // get all engines that use that same gig::Instrument          // get all engines that use that same gig::Instrument
867          suspendedEngines = GetEnginesUsing(pInstrument, true/*lock*/);          suspendedEngines = GetEnginesUsing(pInstrument, true/*lock*/);
868          // finally, completely suspend all engines that use that same gig::Instrument          // finally, completely suspend all engines that use that same gig::Instrument
869          std::set<gig::Engine*>::iterator iter = suspendedEngines.begin();          std::set<Engine*>::iterator iter = suspendedEngines.begin();
870          std::set<gig::Engine*>::iterator end  = suspendedEngines.end();          std::set<Engine*>::iterator end  = suspendedEngines.end();
871          for (; iter != end; ++iter) (*iter)->SuspendAll();          for (; iter != end; ++iter) (*iter)->SuspendAll();
872      }      }
873    
# Line 719  namespace LinuxSampler { namespace gig { Line 890  namespace LinuxSampler { namespace gig {
890          // get all engines that use that same gig::File          // get all engines that use that same gig::File
891          suspendedEngines = GetEnginesUsing(pFile, true/*lock*/);          suspendedEngines = GetEnginesUsing(pFile, true/*lock*/);
892          // finally, completely suspend all engines that use that same gig::File          // finally, completely suspend all engines that use that same gig::File
893          std::set<gig::Engine*>::iterator iter = suspendedEngines.begin();          std::set<Engine*>::iterator iter = suspendedEngines.begin();
894          std::set<gig::Engine*>::iterator end  = suspendedEngines.end();          std::set<Engine*>::iterator end  = suspendedEngines.end();
895          for (; iter != end; ++iter) (*iter)->SuspendAll();          for (; iter != end; ++iter) (*iter)->SuspendAll();
896      }      }
897    
# Line 755  namespace LinuxSampler { namespace gig { Line 926  namespace LinuxSampler { namespace gig {
926      }      }
927    
928      void InstrumentResourceManager::GigResourceManager::Destroy(::gig::File* pResource, void* pArg) {      void InstrumentResourceManager::GigResourceManager::Destroy(::gig::File* pResource, void* pArg) {
929          dmsg(1,("Freeing gig file from memory..."));          dmsg(1,("Freeing gig file '%s' from memory ...", pResource->GetFileName().c_str()));
930    
931          // Delete as much as possible of the gig file. Some of the          // Delete as much as possible of the gig file. Some of the
932          // 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 947  namespace LinuxSampler { namespace gig {
947                  for (int i = 0 ; i < region->DimensionRegions ; i++)                  for (int i = 0 ; i < region->DimensionRegions ; i++)
948                  {                  {
949                      ::gig::DimensionRegion *d = region->pDimensionRegions[i];                      ::gig::DimensionRegion *d = region->pDimensionRegions[i];
950                      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);
951                      if (iter != parent->DimRegInfo.end()) {                      if (iter != parent->RegionInfo.end()) {
952                          dimreg_info_t& dimRegInfo = (*iter).second;                          region_info_t& dimRegInfo = (*iter).second;
953                          dimRegInfo.file = pResource;                          dimRegInfo.file = pResource;
954                          dimRegInfo.riff = (::RIFF::File*)pArg;                          dimRegInfo.pArg = (::RIFF::File*)pArg;
955                          deleteFile = deleteInstrument = deleteRegion = false;                          deleteFile = deleteInstrument = deleteRegion = false;
956                      }                      }
957                  }                  }

Legend:
Removed from v.1646  
changed lines
  Added in v.2275

  ViewVC Help
Powered by ViewVC