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

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

  ViewVC Help
Powered by ViewVC