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

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

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

revision 1212 by schoenebeck, Tue May 29 23:59:36 2007 UTC revision 1455 by persson, Sun Oct 21 11:59:59 2007 UTC
# Line 25  Line 25 
25    
26  #include "InstrumentResourceManager.h"  #include "InstrumentResourceManager.h"
27    
28  #include "../InstrumentEditorFactory.h"  #include "../../common/global_private.h"
29    #include "../../plugins/InstrumentEditorFactory.h"
30    
31  // We need to know the maximum number of sample points which are going to  // We need to know the maximum number of sample points which are going to
32  // be processed for each render cycle of the audio output driver, to know  // be processed for each render cycle of the audio output driver, to know
# Line 106  namespace LinuxSampler { namespace gig { Line 107  namespace LinuxSampler { namespace gig {
107          return res;          return res;
108      }      }
109    
110      String InstrumentResourceManager::GetInstrumentTypeName(instrument_id_t ID) {      String InstrumentResourceManager::GetInstrumentDataStructureName(instrument_id_t ID) {
111          return ::gig::libraryName();          return ::gig::libraryName();
112      }      }
113    
114      String InstrumentResourceManager::GetInstrumentTypeVersion(instrument_id_t ID) {      String InstrumentResourceManager::GetInstrumentDataStructureVersion(instrument_id_t ID) {
115          return ::gig::libraryVersion();          return ::gig::libraryVersion();
116      }      }
117    
118      void InstrumentResourceManager::LaunchInstrumentEditor(instrument_id_t ID) throw (InstrumentManagerException) {      void InstrumentResourceManager::LaunchInstrumentEditor(instrument_id_t ID) throw (InstrumentManagerException) {
119          const String sDataType    = GetInstrumentTypeName(ID);          const String sDataType    = GetInstrumentDataStructureName(ID);
120          const String sDataVersion = GetInstrumentTypeVersion(ID);          const String sDataVersion = GetInstrumentDataStructureVersion(ID);
121          // find instrument editors capable to handle given instrument          // find instrument editors capable to handle given instrument
122          std::vector<String> vEditors =          std::vector<String> vEditors =
123              InstrumentEditorFactory::MatchingEditors(sDataType, sDataVersion);              InstrumentEditorFactory::MatchingEditors(sDataType, sDataVersion);
# Line 128  namespace LinuxSampler { namespace gig { Line 129  namespace LinuxSampler { namespace gig {
129          dmsg(1,("Found matching editor '%s' for instrument ('%s', %d) having data structure ('%s','%s')\n",          dmsg(1,("Found matching editor '%s' for instrument ('%s', %d) having data structure ('%s','%s')\n",
130              vEditors[0].c_str(), ID.FileName.c_str(), ID.Index, sDataType.c_str(), sDataVersion.c_str()));              vEditors[0].c_str(), ID.FileName.c_str(), ID.Index, sDataType.c_str(), sDataVersion.c_str()));
131          InstrumentEditor* pEditor = InstrumentEditorFactory::Create(vEditors[0]);          InstrumentEditor* pEditor = InstrumentEditorFactory::Create(vEditors[0]);
132          // we want to know when you'll die X| (see OnInstrumentEditorQuit())          // register for receiving notifications from the instrument editor
133          pEditor->AddListener(this);          pEditor->AddListener(this);
134          // create a proxy that reacts on notification on behalf of the editor          // create a proxy that reacts on notification on behalf of the editor
135          InstrumentEditorProxy* pProxy = new InstrumentEditorProxy;          InstrumentEditorProxy* pProxy = new InstrumentEditorProxy;
# Line 167  namespace LinuxSampler { namespace gig { Line 168  namespace LinuxSampler { namespace gig {
168              InstrumentEditorProxiesMutex.Unlock();              InstrumentEditorProxiesMutex.Unlock();
169              std::cerr << "Eeeek, could not find instrument editor proxy, this is a bug!\n" << std::flush;              std::cerr << "Eeeek, could not find instrument editor proxy, this is a bug!\n" << std::flush;
170          }          }
171          // free the editor  
172          InstrumentEditorFactory::Destroy(pSender);          // Note that we don't need to free the editor here. As it
173            // derives from Thread, it will delete itself when the thread
174            // dies.
175        }
176    
177        void InstrumentResourceManager::OnSamplesToBeRemoved(std::set<void*> Samples, InstrumentEditor* pSender) {
178            if (Samples.empty()) {
179                std::cerr << "gig::InstrumentResourceManager: WARNING, "
180                             "OnSamplesToBeRemoved() called with empty list, this "
181                             "is a bug!\n" << std::flush;
182                return;
183            }
184            // TODO: ATM we assume here that all samples are from the same file
185            ::gig::Sample* pFirstSample = (::gig::Sample*) *Samples.begin();
186            ::gig::File* pCriticalFile = dynamic_cast< ::gig::File*>(pFirstSample->GetParent());
187            // completely suspend all engines that use that same file
188            SuspendEnginesUsing(pCriticalFile);
189        }
190    
191        void InstrumentResourceManager::OnSamplesRemoved(InstrumentEditor* pSender) {
192            // resume all previously, completely suspended engines
193            // (we don't have to un-cache the removed samples here, since that is
194            // automatically done by the gig::Sample destructor)
195            ResumeAllEngines();
196        }
197    
198        void InstrumentResourceManager::OnDataStructureToBeChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {
199            //TODO: remove code duplication
200            if (sStructType == "gig::File") {
201                // completely suspend all engines that use that file
202                ::gig::File* pFile = (::gig::File*) pStruct;
203                SuspendEnginesUsing(pFile);
204            } else if (sStructType == "gig::Instrument") {
205                // completely suspend all engines that use that instrument
206                ::gig::Instrument* pInstrument = (::gig::Instrument*) pStruct;
207                SuspendEnginesUsing(pInstrument);
208            } else if (sStructType == "gig::Region") {
209                // only advice the engines to suspend the given region, so they'll
210                // only ignore that region (and probably already other suspended
211                // ones), but beside that continue normal playback
212                ::gig::Region* pRegion = (::gig::Region*) pStruct;
213                ::gig::Instrument* pInstrument =
214                    (::gig::Instrument*) pRegion->GetParent();
215                Lock();
216                std::set<gig::Engine*> engines =
217                    GetEnginesUsing(pInstrument, false/*don't lock again*/);
218                std::set<gig::Engine*>::iterator iter = engines.begin();
219                std::set<gig::Engine*>::iterator end  = engines.end();
220                for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
221                Unlock();
222            } else if (sStructType == "gig::DimensionRegion") {
223                // only advice the engines to suspend the given DimensionRegions's
224                // parent region, so they'll only ignore that region (and probably
225                // already other suspended ones), but beside that continue normal
226                // playback
227                ::gig::DimensionRegion* pDimReg =
228                    (::gig::DimensionRegion*) pStruct;
229                ::gig::Region* pRegion = pDimReg->GetParent();
230                ::gig::Instrument* pInstrument =
231                    (::gig::Instrument*) pRegion->GetParent();
232                Lock();
233                std::set<gig::Engine*> engines =
234                    GetEnginesUsing(pInstrument, false/*don't lock again*/);
235                std::set<gig::Engine*>::iterator iter = engines.begin();
236                std::set<gig::Engine*>::iterator end  = engines.end();
237                for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
238                Unlock();
239            } else {
240                std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
241                             "structure '" << sStructType << "' requested to be "
242                             "suspended by instrument editor. This is a bug!\n"
243                          << std::flush;
244                //TODO: we should inform the instrument editor that something seriously went wrong
245            }
246        }
247    
248        void InstrumentResourceManager::OnDataStructureChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {
249            //TODO: remove code duplication
250            if (sStructType == "gig::File") {
251                // resume all previously suspended engines
252                ResumeAllEngines();
253            } else if (sStructType == "gig::Instrument") {
254                // resume all previously suspended engines
255                ResumeAllEngines();
256            } else if (sStructType == "gig::Region") {
257                // advice the engines to resume the given region, that is to
258                // using it for playback again
259                ::gig::Region* pRegion = (::gig::Region*) pStruct;
260                ::gig::Instrument* pInstrument =
261                    (::gig::Instrument*) pRegion->GetParent();
262                Lock();
263                std::set<gig::Engine*> engines =
264                    GetEnginesUsing(pInstrument, false/*don't lock again*/);
265                std::set<gig::Engine*>::iterator iter = engines.begin();
266                std::set<gig::Engine*>::iterator end  = engines.end();
267                for (; iter != end; ++iter) (*iter)->Resume(pRegion);
268                Unlock();
269            } else if (sStructType == "gig::DimensionRegion") {
270                // advice the engines to resume the given DimensionRegion's parent
271                // region, that is to using it for playback again
272                ::gig::DimensionRegion* pDimReg =
273                    (::gig::DimensionRegion*) pStruct;
274                ::gig::Region* pRegion = pDimReg->GetParent();
275                ::gig::Instrument* pInstrument =
276                    (::gig::Instrument*) pRegion->GetParent();
277                Lock();
278                std::set<gig::Engine*> engines =
279                    GetEnginesUsing(pInstrument, false/*don't lock again*/);
280                std::set<gig::Engine*>::iterator iter = engines.begin();
281                std::set<gig::Engine*>::iterator end  = engines.end();
282                for (; iter != end; ++iter) (*iter)->Resume(pRegion);
283                Unlock();
284            } else {
285                std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
286                             "structure '" << sStructType << "' requested to be "
287                             "resumed by instrument editor. This is a bug!\n"
288                          << std::flush;
289                //TODO: we should inform the instrument editor that something seriously went wrong
290            }
291        }
292    
293        void InstrumentResourceManager::OnSampleReferenceChanged(void* pOldSample, void* pNewSample, InstrumentEditor* pSender) {
294            // uncache old sample in case it's not used by anybody anymore
295            if (pOldSample) {
296                Lock();
297                ::gig::Sample* pSample = (::gig::Sample*) pOldSample;
298                ::gig::File* pFile = (::gig::File*) pSample->GetParent();
299                std::vector< ::gig::Instrument*> instruments =
300                    GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
301                for (int i = 0; i < instruments.size(); i++)
302                    if (!SampleReferencedByInstrument(pSample, instruments[i]))
303                        UncacheInitialSamples(pSample);
304                Unlock();
305            }
306            // make sure new sample reference is cached
307            if (pNewSample) {
308                Lock();
309                ::gig::Sample* pSample = (::gig::Sample*) pNewSample;
310                ::gig::File* pFile = (::gig::File*) pSample->GetParent();
311                // get all engines that use that same gig::File
312                std::set<gig::Engine*> engines = GetEnginesUsing(pFile, false/*don't lock again*/);
313                std::set<gig::Engine*>::iterator iter = engines.begin();
314                std::set<gig::Engine*>::iterator end  = engines.end();
315                for (; iter != end; ++iter)
316                    CacheInitialSamples(pSample, *iter);
317                Unlock();
318            }
319      }      }
320    
321      ::gig::Instrument* InstrumentResourceManager::Create(instrument_id_t Key, InstrumentConsumer* pConsumer, void*& pArg) {      ::gig::Instrument* InstrumentResourceManager::Create(instrument_id_t Key, InstrumentConsumer* pConsumer, void*& pArg) {
322          // get gig file from inernal gig file manager          // get gig file from internal gig file manager
323          ::gig::File* pGig = Gigs.Borrow(Key.FileName, (GigConsumer*) Key.Index); // conversion kinda hackish :/          ::gig::File* pGig = Gigs.Borrow(Key.FileName, (GigConsumer*) Key.Index); // conversion kinda hackish :/
324    
325          // we pass this to the progress callback mechanism of libgig          // we pass this to the progress callback mechanism of libgig
# Line 304  namespace LinuxSampler { namespace gig { Line 451  namespace LinuxSampler { namespace gig {
451      }      }
452    
453      /**      /**
454         * Just a wrapper around the other @c CacheInitialSamples() method.
455         *
456         *  @param pSample - points to the sample to be cached
457         *  @param pEngine - pointer to Gig Engine Channel which caused this call
458         *                   (may be NULL, in this case default amount of samples
459         *                   will be cached)
460         */
461        void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::EngineChannel* pEngineChannel) {
462            gig::Engine* pEngine =
463                (pEngineChannel && pEngineChannel->GetEngine()) ?
464                    dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine()) : NULL;
465            CacheInitialSamples(pSample, pEngine);
466        }
467    
468        /**
469       *  Caches a certain size at the beginning of the given sample in RAM. If the       *  Caches a certain size at the beginning of the given sample in RAM. If the
470       *  sample is very short, the whole sample will be loaded into RAM and thus       *  sample is very short, the whole sample will be loaded into RAM and thus
471       *  no disk streaming is needed for this sample. Caching an initial part of       *  no disk streaming is needed for this sample. Caching an initial part of
472       *  samples is needed to compensate disk reading latency.       *  samples is needed to compensate disk reading latency.
473       *       *
474       *  @param pSample - points to the sample to be cached       *  @param pSample - points to the sample to be cached
475       *  @param pEngineChannel - pointer to Gig Engine Channel which caused this call       *  @param pEngine - pointer to Gig Engine which caused this call
476         *                   (may be NULL, in this case default amount of samples
477         *                   will be cached)
478       */       */
479      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::EngineChannel* pEngineChannel) {      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::Engine* pEngine) {
480          if (!pSample) {          if (!pSample) {
481              dmsg(4,("gig::InstrumentResourceManager: Skipping sample (pSample == NULL)\n"));              dmsg(4,("gig::InstrumentResourceManager: Skipping sample (pSample == NULL)\n"));
482              return;              return;
# Line 326  namespace LinuxSampler { namespace gig { Line 490  namespace LinuxSampler { namespace gig {
490              // 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
491              // the sample.              // the sample.
492              const uint maxSamplesPerCycle =              const uint maxSamplesPerCycle =
493                  (pEngineChannel && pEngineChannel->GetEngine()) ? dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()                  (pEngine) ? pEngine->pAudioOutputDevice->MaxSamplesPerCycle()
494                                                : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;                            : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;
495              const uint neededSilenceSamples = (maxSamplesPerCycle << CONFIG_MAX_PITCH) + 3;              const uint neededSilenceSamples = (maxSamplesPerCycle << CONFIG_MAX_PITCH) + 3;
496              const uint currentlyCachedSilenceSamples = pSample->GetCache().NullExtensionSize / pSample->FrameSize;              const uint currentlyCachedSilenceSamples = pSample->GetCache().NullExtensionSize / pSample->FrameSize;
497              if (currentlyCachedSilenceSamples < neededSilenceSamples) {              if (currentlyCachedSilenceSamples < neededSilenceSamples) {
# Line 343  namespace LinuxSampler { namespace gig { Line 507  namespace LinuxSampler { namespace gig {
507          if (!pSample->GetCache().Size) std::cerr << "Unable to cache sample - maybe memory full!" << std::endl << std::flush;          if (!pSample->GetCache().Size) std::cerr << "Unable to cache sample - maybe memory full!" << std::endl << std::flush;
508      }      }
509    
510        void InstrumentResourceManager::UncacheInitialSamples(::gig::Sample* pSample) {
511            dmsg(1,("Uncaching sample %x\n",pSample));
512            if (pSample->GetCache().Size) pSample->ReleaseSampleData();
513        }
514    
515        /**
516         * Returns a list with all instruments currently in use, that are part of
517         * the given file.
518         *
519         * @param pFile - search criteria
520         * @param bLock - whether we should lock (mutex) the instrument manager
521         *                during this call and unlock at the end of this call
522         */
523        std::vector< ::gig::Instrument*> InstrumentResourceManager::GetInstrumentsCurrentlyUsedOf(::gig::File* pFile, bool bLock) {
524            if (bLock) Lock();
525            std::vector< ::gig::Instrument*> result;
526            std::vector< ::gig::Instrument*> allInstruments = Resources(false/*don't lock again*/);
527            for (int i = 0; i < allInstruments.size(); i++)
528                if (
529                    (::gig::File*) allInstruments[i]->GetParent()
530                    == pFile
531                ) result.push_back(allInstruments[i]);
532            if (bLock) Unlock();
533            return result;
534        }
535    
536        /**
537         * Returns a list with all gig Engines that are currently using the given
538         * instrument.
539         *
540         * @param pInstrument - search criteria
541         * @param bLock - whether we should lock (mutex) the instrument manager
542         *                during this call and unlock at the end of this call
543         */
544        std::set<gig::Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::Instrument* pInstrument, bool bLock) {
545            if (bLock) Lock();
546            std::set<gig::Engine*> result;
547            std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(pInstrument);
548            std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
549            std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();
550            for (; iter != end; ++iter) {
551                gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(*iter);
552                if (!pEngineChannel) continue;
553                gig::Engine* pEngine = dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine());
554                if (!pEngine) continue;
555                result.insert(pEngine);
556            }
557            if (bLock) Unlock();
558            return result;
559        }
560    
561        /**
562         * Returns a list with all gig Engines that are currently using an
563         * instrument that is part of the given instrument file.
564         *
565         * @param pFile - search criteria
566         * @param bLock - whether we should lock (mutex) the instrument manager
567         *                during this call and unlock at the end of this call
568         */
569        std::set<gig::Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::File* pFile, bool bLock) {
570            if (bLock) Lock();
571            // get all instruments (currently in usage) that use that same gig::File
572            std::vector< ::gig::Instrument*> instrumentsOfInterest =
573                GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
574    
575            // get all engines that use that same gig::File
576            std::set<gig::Engine*> result;
577            {
578                for (int i = 0; i < instrumentsOfInterest.size(); i++) {
579                    std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(instrumentsOfInterest[i]);
580                    std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
581                    std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();
582                    for (; iter != end; ++iter) {
583                        gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(*iter);
584                        if (!pEngineChannel) continue;
585                        gig::Engine* pEngine = dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine());
586                        if (!pEngine) continue;
587                        // the unique, sorted container std::set makes
588                        // sure we won't have duplicates
589                        result.insert(pEngine);
590                    }
591                }
592            }
593            if (bLock) Unlock();
594            return result;
595        }
596    
597        /**
598         * Returns @c true in case the given sample is referenced somewhere by the
599         * given instrument, @c false otherwise.
600         *
601         * @param pSample - sample reference
602         * @param pInstrument - instrument that might use that sample
603         */
604        bool InstrumentResourceManager::SampleReferencedByInstrument(::gig::Sample* pSample, ::gig::Instrument* pInstrument) {
605            for (
606                ::gig::Region* pRegion = pInstrument->GetFirstRegion();
607                pRegion; pRegion = pInstrument->GetNextRegion()
608            ) {
609                for (
610                    int i = 0; i < pRegion->DimensionRegions &&
611                    pRegion->pDimensionRegions[i]; i++
612                ) {
613                    if (pRegion->pDimensionRegions[i]->pSample == pSample)
614                        return true;
615                }
616            }
617            return false;
618        }
619    
620        /**
621         * Suspend all gig engines that use the given instrument. This means
622         * completely stopping playback on those engines and killing all their
623         * voices and disk streams. This method will block until all voices AND
624         * their disk streams are finally deleted and the engine turned into a
625         * complete idle loop.
626         *
627         * All @c SuspendEnginesUsing() methods only serve one thread by one and
628         * block all other threads until the current active thread called
629         * @c ResumeAllEngines() .
630         *
631         * @param pInstrument - search criteria
632         */
633        void InstrumentResourceManager::SuspendEnginesUsing(::gig::Instrument* pInstrument) {
634            // make sure no other thread suspends whole engines at the same time
635            suspendedEnginesMutex.Lock();
636            // get all engines that use that same gig::Instrument
637            suspendedEngines = GetEnginesUsing(pInstrument, true/*lock*/);
638            // finally, completely suspend all engines that use that same gig::Instrument
639            std::set<gig::Engine*>::iterator iter = suspendedEngines.begin();
640            std::set<gig::Engine*>::iterator end  = suspendedEngines.end();
641            for (; iter != end; ++iter) (*iter)->SuspendAll();
642        }
643    
644        /**
645         * Suspend all gig engines that use the given instrument file. This means
646         * completely stopping playback on those engines and killing all their
647         * voices and disk streams. This method will block until all voices AND
648         * their disk streams are finally deleted and the engine turned into a
649         * complete idle loop.
650         *
651         * All @c SuspendEnginesUsing() methods only serve one thread by one and
652         * block all other threads until the current active thread called
653         * @c ResumeAllEngines() .
654         *
655         * @param pFile - search criteria
656         */
657        void InstrumentResourceManager::SuspendEnginesUsing(::gig::File* pFile) {
658            // make sure no other thread suspends whole engines at the same time
659            suspendedEnginesMutex.Lock();
660            // get all engines that use that same gig::File
661            suspendedEngines = GetEnginesUsing(pFile, true/*lock*/);
662            // finally, completely suspend all engines that use that same gig::File
663            std::set<gig::Engine*>::iterator iter = suspendedEngines.begin();
664            std::set<gig::Engine*>::iterator end  = suspendedEngines.end();
665            for (; iter != end; ++iter) (*iter)->SuspendAll();
666        }
667    
668        /**
669         * MUST be called after one called one of the @c SuspendEnginesUsing()
670         * methods, to resume normal playback on all previously suspended engines.
671         * As it's only possible for one thread to suspend whole engines at the
672         * same time, this method doesn't take any arguments.
673         */
674        void InstrumentResourceManager::ResumeAllEngines() {
675            // resume all previously completely suspended engines
676            std::set<Engine*>::iterator iter = suspendedEngines.begin();
677            std::set<Engine*>::iterator end  = suspendedEngines.end();
678            for (; iter != end; ++iter) (*iter)->ResumeAll();
679            // no more suspended engines ...
680            suspendedEngines.clear();
681            // allow another thread to suspend whole engines
682            suspendedEnginesMutex.Unlock();
683        }
684    
685    
686    
687      // internal gig file manager      // internal gig file manager

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

  ViewVC Help
Powered by ViewVC