/[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 2309 by iliev, Mon Jan 30 10:40:19 2012 UTC revision 3034 by schoenebeck, Mon Oct 31 00:05:00 2016 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 - 2011 Christian Schoenebeck                       *   *   Copyright (C) 2005 - 2016 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 32  Line 32 
32    
33  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
34    
     // 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  
     };  
   
35      // some data needed for the libgig callback function      // some data needed for the libgig callback function
36      struct progress_callback_arg_t {      struct progress_callback_arg_t {
37          InstrumentResourceManager*          pManager;          InstrumentResourceManager*          pManager;
# Line 48  namespace LinuxSampler { namespace gig { Line 41  namespace LinuxSampler { namespace gig {
41      // 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
42      class InstrumentEditorProxy : public InstrumentConsumer {      class InstrumentEditorProxy : public InstrumentConsumer {
43      public:      public:
44            virtual ~InstrumentEditorProxy() {}
45    
46          virtual void ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {          virtual void ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {
47              //TODO: inform the instrument editor about the pending update              //TODO: inform the instrument editor about the pending update
48          }          }
# Line 76  namespace LinuxSampler { namespace gig { Line 71  namespace LinuxSampler { namespace gig {
71       *                    instrument ID       *                    instrument ID
72       */       */
73      void InstrumentResourceManager::OnInstrumentLoadingProgress(::gig::progress_t* pProgress) {      void InstrumentResourceManager::OnInstrumentLoadingProgress(::gig::progress_t* pProgress) {
74          dmsg(7,("gig::InstrumentResourceManager: progress %f%", pProgress->factor));          dmsg(7,("gig::InstrumentResourceManager: progress %f%%", pProgress->factor));
75          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);
76          // 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
77          const float localProgress = 0.9f * pProgress->factor;          const float localProgress = 0.9f * pProgress->factor;
78          pArg->pManager->DispatchResourceProgressEvent(*pArg->pInstrumentKey, localProgress);          pArg->pManager->DispatchResourceProgressEvent(*pArg->pInstrumentKey, localProgress);
79      }      }
80    
     std::vector<InstrumentResourceManager::instrument_id_t> InstrumentResourceManager::Instruments() {  
         return Entries();  
     }  
   
81      String InstrumentResourceManager::GetInstrumentName(instrument_id_t ID) {      String InstrumentResourceManager::GetInstrumentName(instrument_id_t ID) {
82          Lock();          Lock();
83          ::gig::Instrument* pInstrument = Resource(ID, false);          ::gig::Instrument* pInstrument = Resource(ID, false);
# Line 140  namespace LinuxSampler { namespace gig { Line 131  namespace LinuxSampler { namespace gig {
131          ::RIFF::File* riff = NULL;          ::RIFF::File* riff = NULL;
132          ::gig::File*  gig  = NULL;          ::gig::File*  gig  = NULL;
133          try {          try {
134              if(!loaded) {              if (!loaded) {
135                  riff = new ::RIFF::File(ID.FileName);                  riff = new ::RIFF::File(ID.FileName);
136                  gig  = new ::gig::File(riff);                  gig  = new ::gig::File(riff);
137                  gig->SetAutoLoad(false); // avoid time consuming samples scanning                  gig->SetAutoLoad(false); // avoid time consuming samples scanning
# Line 219  namespace LinuxSampler { namespace gig { Line 210  namespace LinuxSampler { namespace gig {
210          }          }
211      }      }
212    
213      InstrumentEditor* InstrumentResourceManager::LaunchInstrumentEditor(instrument_id_t ID, void* pUserData) throw (InstrumentManagerException) {      InstrumentEditor* InstrumentResourceManager::LaunchInstrumentEditor(LinuxSampler::EngineChannel* pEngineChannel, instrument_id_t ID, void* pUserData) throw (InstrumentManagerException) {
214          const String sDataType    = GetInstrumentDataStructureName(ID);          const String sDataType    = GetInstrumentDataStructureName(ID);
215          const String sDataVersion = GetInstrumentDataStructureVersion(ID);          const String sDataVersion = GetInstrumentDataStructureVersion(ID);
216          // find instrument editors capable to handle given instrument          // find instrument editors capable to handle given instrument
# Line 246  namespace LinuxSampler { namespace gig { Line 237  namespace LinuxSampler { namespace gig {
237          InstrumentEditorProxies.add(pProxy);          InstrumentEditorProxies.add(pProxy);
238          InstrumentEditorProxiesMutex.Unlock();          InstrumentEditorProxiesMutex.Unlock();
239          // launch the instrument editor for the given instrument          // launch the instrument editor for the given instrument
240          pEditor->Launch(pInstrument, sDataType, sDataVersion, pUserData);          pEditor->Launch(pEngineChannel, pInstrument, sDataType, sDataVersion, pUserData);
241    
242          // register the instrument editor as virtual MIDI device as well ...          // register the instrument editor as virtual MIDI device as well ...
243          VirtualMidiDevice* pVirtualMidiDevice =          VirtualMidiDevice* pVirtualMidiDevice =
# Line 282  namespace LinuxSampler { namespace gig { Line 273  namespace LinuxSampler { namespace gig {
273          int iProxyIndex                = -1;          int iProxyIndex                = -1;
274    
275          // first find the editor proxy entry for this editor          // first find the editor proxy entry for this editor
276          InstrumentEditorProxiesMutex.Lock();          {
277          for (int i = 0; i < InstrumentEditorProxies.size(); i++) {              LockGuard lock(InstrumentEditorProxiesMutex);
278              InstrumentEditorProxy* pCurProxy =              for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
279                  dynamic_cast<InstrumentEditorProxy*>(                  InstrumentEditorProxy* pCurProxy =
280                      InstrumentEditorProxies[i]                      dynamic_cast<InstrumentEditorProxy*>(
281                  );                          InstrumentEditorProxies[i]
282              if (pCurProxy->pEditor == pSender) {                          );
283                  pProxy      = pCurProxy;                  if (pCurProxy->pEditor == pSender) {
284                  iProxyIndex = i;                      pProxy      = pCurProxy;
285                  pInstrument = pCurProxy->pInstrument;                      iProxyIndex = i;
286                        pInstrument = pCurProxy->pInstrument;
287                    }
288              }              }
289          }          }
         InstrumentEditorProxiesMutex.Unlock();  
290    
291          if (!pProxy) {          if (!pProxy) {
292              std::cerr << "Eeeek, could not find instrument editor proxy, "              std::cerr << "Eeeek, could not find instrument editor proxy, "
# Line 322  namespace LinuxSampler { namespace gig { Line 314  namespace LinuxSampler { namespace gig {
314    
315          // finally delete proxy entry and hand back instrument          // finally delete proxy entry and hand back instrument
316          if (pInstrument) {          if (pInstrument) {
317              InstrumentEditorProxiesMutex.Lock();              {
318              InstrumentEditorProxies.remove(iProxyIndex);                  LockGuard lock(InstrumentEditorProxiesMutex);
319              InstrumentEditorProxiesMutex.Unlock();                  InstrumentEditorProxies.remove(iProxyIndex);
320                }
321    
322              HandBack(pInstrument, pProxy);              HandBack(pInstrument, pProxy);
323              delete pProxy;              delete pProxy;
# Line 401  namespace LinuxSampler { namespace gig { Line 394  namespace LinuxSampler { namespace gig {
394      }      }
395    
396      void InstrumentResourceManager::OnDataStructureToBeChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {      void InstrumentResourceManager::OnDataStructureToBeChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {
397            dmsg(5,("gig::InstrumentResourceManager::OnDataStructureToBeChanged(%s)\n", sStructType.c_str()));
398          //TODO: remove code duplication          //TODO: remove code duplication
399          if (sStructType == "gig::File") {          if (sStructType == "gig::File") {
400              // completely suspend all engines that use that file              // completely suspend all engines that use that file
# Line 441  namespace LinuxSampler { namespace gig { Line 435  namespace LinuxSampler { namespace gig {
435              std::set<Engine*>::iterator end  = engines.end();              std::set<Engine*>::iterator end  = engines.end();
436              for (; iter != end; ++iter) (*iter)->Suspend(pRegion);              for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
437              Unlock();              Unlock();
438            } else if (sStructType == "gig::Script") {
439                // no need to suspend anything here, since the sampler is
440                // processing a translated VM representation of the original script
441                // source code, not accessing the source code itself during playback
442                ::gig::Script* pScript = (::gig::Script*) pStruct;
443                // remember the original source code of the script, since the script
444                // resource manager uses the source code as key
445                pendingScriptUpdatesMutex.Lock();
446                pendingScriptUpdates[pScript] = pScript->GetScriptAsText();
447                pendingScriptUpdatesMutex.Unlock();
448          } else {          } else {
449              std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "              std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
450                           "structure '" << sStructType << "' requested to be "                           "structure '" << sStructType << "' requested to be "
# Line 451  namespace LinuxSampler { namespace gig { Line 455  namespace LinuxSampler { namespace gig {
455      }      }
456    
457      void InstrumentResourceManager::OnDataStructureChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {      void InstrumentResourceManager::OnDataStructureChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {
458            dmsg(5,("gig::InstrumentResourceManager::OnDataStructureChanged(%s)\n", sStructType.c_str()));
459          //TODO: remove code duplication          //TODO: remove code duplication
460          if (sStructType == "gig::File") {          if (sStructType == "gig::File") {
461              // resume all previously suspended engines              // resume all previously suspended engines
# Line 508  namespace LinuxSampler { namespace gig { Line 513  namespace LinuxSampler { namespace gig {
513              std::set<Engine*>::iterator end  = engines.end();              std::set<Engine*>::iterator end  = engines.end();
514              for (; iter != end; ++iter) (*iter)->Resume(pRegion);              for (; iter != end; ++iter) (*iter)->Resume(pRegion);
515              Unlock();              Unlock();
516            } else if (sStructType == "gig::Script") {
517                // inform all engine channels which are using this script, that
518                // they need to reload (parse) the script's source code text
519                ::gig::Script* pScript = (::gig::Script*) pStruct;
520                pendingScriptUpdatesMutex.Lock();
521                if (pendingScriptUpdates.count(pScript)) {
522                    const String& code = pendingScriptUpdates[pScript];
523                    std::set<EngineChannel*> channels = GetEngineChannelsUsingScriptSourceCode(code, true/*lock*/);
524                    pendingScriptUpdates.erase(pScript);
525                    std::set<EngineChannel*>::iterator iter = channels.begin();
526                    std::set<EngineChannel*>::iterator end  = channels.end();
527                    for (; iter != end; ++iter) (*iter)->reloadScript(pScript);
528                }
529                pendingScriptUpdatesMutex.Unlock();
530          } else {          } else {
531              std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "              std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
532                           "structure '" << sStructType << "' requested to be "                           "structure '" << sStructType << "' requested to be "
# Line 573  namespace LinuxSampler { namespace gig { Line 592  namespace LinuxSampler { namespace gig {
592          pGig->GetFirstSample(); // just to force complete instrument loading          pGig->GetFirstSample(); // just to force complete instrument loading
593          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
594    
595            uint maxSamplesPerCycle = GetMaxSamplesPerCycle(pConsumer);
596    
597          // cache initial samples points (for actually needed samples)          // cache initial samples points (for actually needed samples)
598          dmsg(1,("Caching initial samples..."));          dmsg(1,("Caching initial samples..."));
599          uint iRegion = 0; // just for progress calculation          uint iRegion = 0; // just for progress calculation
# Line 584  namespace LinuxSampler { namespace gig { Line 605  namespace LinuxSampler { namespace gig {
605    
606              if (pRgn->GetSample() && !pRgn->GetSample()->GetCache().Size) {              if (pRgn->GetSample() && !pRgn->GetSample()->GetCache().Size) {
607                  dmsg(2,("C"));                  dmsg(2,("C"));
608                  CacheInitialSamples(pRgn->GetSample(), (EngineChannel*) pConsumer);                  CacheInitialSamples(pRgn->GetSample(), maxSamplesPerCycle);
609              }              }
610              for (uint i = 0; i < pRgn->DimensionRegions; i++) {              for (uint i = 0; i < pRgn->DimensionRegions; i++) {
611                  CacheInitialSamples(pRgn->pDimensionRegions[i]->pSample, (EngineChannel*) pConsumer);                  CacheInitialSamples(pRgn->pDimensionRegions[i]->pSample, maxSamplesPerCycle);
612              }              }
613    
614              pRgn = pInstrument->GetNextRegion();              pRgn = pInstrument->GetNextRegion();
# Line 600  namespace LinuxSampler { namespace gig { Line 621  namespace LinuxSampler { namespace gig {
621          instr_entry_t* pEntry = new instr_entry_t;          instr_entry_t* pEntry = new instr_entry_t;
622          pEntry->ID.FileName   = Key.FileName;          pEntry->ID.FileName   = Key.FileName;
623          pEntry->ID.Index      = Key.Index;          pEntry->ID.Index      = Key.Index;
624          pEntry->pGig          = pGig;          pEntry->pFile         = pGig;
625    
626          // (try to resolve the audio device context)          // and we save this to check if we need to reallocate for an engine with higher value of 'MaxSamplesPerSecond'
627          EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(pConsumer);          pEntry->MaxSamplesPerCycle = maxSamplesPerCycle;
         Engine* pEngine = dynamic_cast<Engine*>(pEngineChannel->GetEngine());  
         AudioOutputDevice* pDevice = (pEngine) ? pEngine->pAudioOutputDevice : NULL;  
         // and we save this to check if we need to reallocate for a engine with higher value of 'MaxSamplesPerSecond'  
         pEntry->MaxSamplesPerCycle =  
             (pDevice) ? pDevice->MaxSamplesPerCycle() : DefaultMaxSamplesPerCycle();  
628                    
629          pArg = pEntry;          pArg = pEntry;
630    
631          return pInstrument;          return pInstrument;
632      }      }
633    
634      void InstrumentResourceManager::Destroy( ::gig::Instrument* pResource, void* pArg) {      void InstrumentResourceManager::Destroy(::gig::Instrument* pResource, void* pArg) {
635          instr_entry_t* pEntry = (instr_entry_t*) pArg;          instr_entry_t* pEntry = (instr_entry_t*) pArg;
636          // we don't need the .gig file here anymore          // we don't need the .gig file here anymore
637          Gigs.HandBack(pEntry->pGig, reinterpret_cast<GigConsumer*>(pEntry->ID.Index)); // conversion kinda hackish :/          Gigs.HandBack(pEntry->pFile, reinterpret_cast<GigConsumer*>(pEntry->ID.Index)); // conversion kinda hackish :/
638          delete pEntry;          delete pEntry;
639      }      }
640    
     void InstrumentResourceManager::OnBorrow(::gig::Instrument* pResource, InstrumentConsumer* pConsumer, void*& pArg) {  
         instr_entry_t* pEntry = (instr_entry_t*) pArg;  
           
         // (try to resolve the audio device context)  
         EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(pConsumer);  
         Engine* pEngine = pEngineChannel ? dynamic_cast<Engine*>(pEngineChannel->GetEngine()) : NULL;  
         AudioOutputDevice* pDevice = (pEngine) ? pEngine->pAudioOutputDevice : NULL;  
           
         uint maxSamplesPerCycle =  
             (pDevice) ? pDevice->MaxSamplesPerCycle() : DefaultMaxSamplesPerCycle();  
   
         if (pEntry->MaxSamplesPerCycle < maxSamplesPerCycle) {  
             dmsg(1,("Completely reloading instrument due to insufficient precached samples ...\n"));  
             Update(pResource, pConsumer);  
         }  
     }  
   
641      void InstrumentResourceManager::DeleteRegionIfNotUsed(::gig::DimensionRegion* pRegion, region_info_t* pRegInfo) {      void InstrumentResourceManager::DeleteRegionIfNotUsed(::gig::DimensionRegion* pRegion, region_info_t* pRegInfo) {
642          // TODO: we could delete Region and Instrument here if they have become unused          // TODO: we could delete Region and Instrument here if they have become unused
643      }      }
# Line 683  namespace LinuxSampler { namespace gig { Line 682  namespace LinuxSampler { namespace gig {
682       *                   will be cached)       *                   will be cached)
683       */       */
684      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, AbstractEngine* pEngine) {      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, AbstractEngine* pEngine) {
685            uint maxSamplesPerCycle =
686                (pEngine) ? pEngine->pAudioOutputDevice->MaxSamplesPerCycle() :
687                DefaultMaxSamplesPerCycle();
688            CacheInitialSamples(pSample, maxSamplesPerCycle);
689        }
690    
691        void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, uint maxSamplesPerCycle) {
692          if (!pSample) {          if (!pSample) {
693              dmsg(4,("gig::InstrumentResourceManager: Skipping sample (pSample == NULL)\n"));              dmsg(4,("gig::InstrumentResourceManager: Skipping sample (pSample == NULL)\n"));
694              return;              return;
# Line 695  namespace LinuxSampler { namespace gig { Line 701  namespace LinuxSampler { namespace gig {
701              // number of '0' samples (silence samples) behind the official buffer              // number of '0' samples (silence samples) behind the official buffer
702              // 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
703              // the sample.              // the sample.
             const uint maxSamplesPerCycle =  
                 (pEngine) ? pEngine->pAudioOutputDevice->MaxSamplesPerCycle()  
                           : DefaultMaxSamplesPerCycle();  
704              const uint neededSilenceSamples = (maxSamplesPerCycle << CONFIG_MAX_PITCH) + 3;              const uint neededSilenceSamples = (maxSamplesPerCycle << CONFIG_MAX_PITCH) + 3;
705              const uint currentlyCachedSilenceSamples = pSample->GetCache().NullExtensionSize / pSample->FrameSize;              const uint currentlyCachedSilenceSamples = pSample->GetCache().NullExtensionSize / pSample->FrameSize;
706              if (currentlyCachedSilenceSamples < neededSilenceSamples) {              if (currentlyCachedSilenceSamples < neededSilenceSamples) {
707                  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: %lu)\n", pSample->pInfo->Name.c_str(), pSample->SamplesTotal));
708                  ::gig::buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(neededSilenceSamples);                  ::gig::buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(neededSilenceSamples);
709                  dmsg(4,("Cached %d Bytes, %d silence bytes.\n", buf.Size, buf.NullExtensionSize));                  dmsg(4,("Cached %lu Bytes, %lu silence bytes.\n", buf.Size, buf.NullExtensionSize));
710              }              }
711          }          }
712          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 714  namespace LinuxSampler { namespace gig { Line 717  namespace LinuxSampler { namespace gig {
717      }      }
718    
719      void InstrumentResourceManager::UncacheInitialSamples(::gig::Sample* pSample) {      void InstrumentResourceManager::UncacheInitialSamples(::gig::Sample* pSample) {
720          dmsg(1,("Uncaching sample %x\n",pSample));          dmsg(1,("Uncaching sample %p\n",(void*)pSample));
721          if (pSample->GetCache().Size) pSample->ReleaseSampleData();          if (pSample->GetCache().Size) pSample->ReleaseSampleData();
722      }      }
723    
# Line 738  namespace LinuxSampler { namespace gig { Line 741  namespace LinuxSampler { namespace gig {
741          if (bLock) Unlock();          if (bLock) Unlock();
742          return result;          return result;
743      }      }
744    
745        /**
746         * Returns a list with all gig engine channels that are currently using
747         * the given real-time instrument script (provided as source code).
748         *
749         * @param pScript - search criteria
750         * @param bLock - whether we should lock (mutex) the instrument manager
751         *                during this call and unlock at the end of this call
752         */
753        std::set<EngineChannel*> InstrumentResourceManager::GetEngineChannelsUsingScriptSourceCode(const String& code, bool bLock) {
754            if (bLock) Lock();
755            std::set<EngineChannel*> result;
756            std::set<InstrumentScriptConsumer*> consumers = scripts.ConsumersOf(code);
757            std::set<InstrumentScriptConsumer*>::iterator iter = consumers.begin();
758            std::set<InstrumentScriptConsumer*>::iterator end  = consumers.end();
759            for (; iter != end; ++iter) {
760                EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
761                if (!pEngineChannel) continue;
762                result.insert(pEngineChannel);
763            }
764            if (bLock) Unlock();
765            return result;
766        }
767    
768      /**      /**
769       * Returns a list with all gig engine channels that are currently using       * Returns a list with all gig engine channels that are currently using

Legend:
Removed from v.2309  
changed lines
  Added in v.3034

  ViewVC Help
Powered by ViewVC