/[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 947 by schoenebeck, Mon Nov 27 21:34:55 2006 UTC revision 1212 by schoenebeck, Tue May 29 23:59:36 2007 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, 2006 Christian Schoenebeck                        *   *   Copyright (C) 2005 - 2007 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 25  Line 25 
25    
26  #include "InstrumentResourceManager.h"  #include "InstrumentResourceManager.h"
27    
28    #include "../InstrumentEditorFactory.h"
29    
30  // 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
31  // 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
32  // how much initial sample points we need to cache into RAM. If the given  // how much initial sample points we need to cache into RAM. If the given
# Line 47  namespace LinuxSampler { namespace gig { Line 49  namespace LinuxSampler { namespace gig {
49          InstrumentManager::instrument_id_t* pInstrumentKey;          InstrumentManager::instrument_id_t* pInstrumentKey;
50      };      };
51    
52        // we use this to react on events concerning an instrument on behalf of an instrument editor
53        class InstrumentEditorProxy : public InstrumentConsumer {
54        public:
55            virtual void ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {
56                //TODO: inform the instrument editor about the pending update
57            }
58    
59            virtual void ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {
60                //TODO:: inform the instrument editor about finished update
61            }
62    
63            virtual void OnResourceProgress(float fProgress) {
64                //TODO: inform the instrument editor about the progress of an update
65            }
66    
67            // the instrument we borrowed on behalf of the editor
68            ::gig::Instrument* pInstrument;
69        };
70    
71      /**      /**
72       * Callback function which will be called by libgig during loading of       * Callback function which will be called by libgig during loading of
73       * instruments to inform about the current progress. Or to be more       * instruments to inform about the current progress. Or to be more
# Line 77  namespace LinuxSampler { namespace gig { Line 98  namespace LinuxSampler { namespace gig {
98          SetAvailabilityMode(ID, static_cast<ResourceManager<InstrumentManager::instrument_id_t, ::gig::Instrument>::mode_t>(Mode));          SetAvailabilityMode(ID, static_cast<ResourceManager<InstrumentManager::instrument_id_t, ::gig::Instrument>::mode_t>(Mode));
99      }      }
100    
101      float InstrumentResourceManager::GetVolume(const instrument_id_t& ID) {      String InstrumentResourceManager::GetInstrumentName(instrument_id_t ID) {
102          void* pCustomData = CustomData(ID);          Lock();
103          const float fVolume = (pCustomData) ? *((float*)pCustomData) /* stored value */ : 1.0f /* default value */;          ::gig::Instrument* pInstrument = Resource(ID, false);
104          return fVolume;          String res = (pInstrument) ? pInstrument->pInfo->Name : "";
105      }          Unlock();
106            return res;
107      void InstrumentResourceManager::SetVolume(const instrument_id_t& ID, float Volume) {      }
108          void* pCustomData = CustomData(ID);  
109          if (Volume == 1.0f) { // if default volume ...      String InstrumentResourceManager::GetInstrumentTypeName(instrument_id_t ID) {
110              if (pCustomData) { // ... delete volume entry if necessary          return ::gig::libraryName();
111                  delete (float*)pCustomData;      }
112                  SetCustomData(ID, NULL);  
113              }      String InstrumentResourceManager::GetInstrumentTypeVersion(instrument_id_t ID) {
114          } else { // if not default volume          return ::gig::libraryVersion();
115              if (!pCustomData) { // create volume entry if necessary      }
116                  pCustomData = new float;  
117                  SetCustomData(ID, pCustomData);      void InstrumentResourceManager::LaunchInstrumentEditor(instrument_id_t ID) throw (InstrumentManagerException) {
118              }          const String sDataType    = GetInstrumentTypeName(ID);
119              *((float*)pCustomData) = Volume;          const String sDataVersion = GetInstrumentTypeVersion(ID);
120          }          // find instrument editors capable to handle given instrument
121            std::vector<String> vEditors =
122                InstrumentEditorFactory::MatchingEditors(sDataType, sDataVersion);
123            if (!vEditors.size())
124                throw InstrumentManagerException(
125                    "There is no instrument editor capable to handle this instrument"
126                );
127            // simply use the first editor in the result set
128            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()));
130            InstrumentEditor* pEditor = InstrumentEditorFactory::Create(vEditors[0]);
131            // we want to know when you'll die X| (see OnInstrumentEditorQuit())
132            pEditor->AddListener(this);
133            // create a proxy that reacts on notification on behalf of the editor
134            InstrumentEditorProxy* pProxy = new InstrumentEditorProxy;
135            // borrow the instrument on behalf of the instrument editor
136            ::gig::Instrument* pInstrument = Borrow(ID, pProxy);
137            // remember the proxy and instrument for this instrument editor
138            pProxy->pInstrument = pInstrument;
139            InstrumentEditorProxiesMutex.Lock();
140            InstrumentEditorProxies[pEditor] = pProxy;
141            InstrumentEditorProxiesMutex.Unlock();
142            // launch the instrument editor for the given instrument
143            pEditor->Launch(pInstrument, sDataType, sDataVersion);
144      }      }
145    
146      String InstrumentResourceManager::GetInstrumentName(instrument_id_t ID) {      /**
147          return ""; // TODO: ...       * Will be called by the respective instrument editor once it left its
148         * Main() loop. That way we can handle cleanup before its thread finally
149         * dies.
150         *
151         * @param pSender - instrument editor that stops execution
152         */
153        void InstrumentResourceManager::OnInstrumentEditorQuit(InstrumentEditor* pSender) {
154            dmsg(1,("InstrumentResourceManager: instrument editor quit, doing cleanup\n"));
155            // hand back instrument and free proxy
156            InstrumentEditorProxiesMutex.Lock();
157            if (InstrumentEditorProxies.count(pSender)) {
158                InstrumentEditorProxy* pProxy =
159                    dynamic_cast<InstrumentEditorProxy*>(
160                        InstrumentEditorProxies[pSender]
161                    );
162                InstrumentEditorProxies.erase(pSender);
163                InstrumentEditorProxiesMutex.Unlock();
164                HandBack(pProxy->pInstrument, pProxy);
165                if (pProxy) delete pProxy;
166            } else {
167                InstrumentEditorProxiesMutex.Unlock();
168                std::cerr << "Eeeek, could not find instrument editor proxy, this is a bug!\n" << std::flush;
169            }
170            // free the editor
171            InstrumentEditorFactory::Destroy(pSender);
172      }      }
173    
174      ::gig::Instrument* InstrumentResourceManager::Create(instrument_id_t Key, InstrumentConsumer* pConsumer, void*& pArg) {      ::gig::Instrument* InstrumentResourceManager::Create(instrument_id_t Key, InstrumentConsumer* pConsumer, void*& pArg) {
# Line 121  namespace LinuxSampler { namespace gig { Line 189  namespace LinuxSampler { namespace gig {
189          if (!pInstrument) {          if (!pInstrument) {
190              std::stringstream msg;              std::stringstream msg;
191              msg << "There's no instrument with index " << Key.Index << ".";              msg << "There's no instrument with index " << Key.Index << ".";
192              throw InstrumentResourceManagerException(msg.str());              throw InstrumentManagerException(msg.str());
193          }          }
194          pGig->GetFirstSample(); // just to force complete instrument loading          pGig->GetFirstSample(); // just to force complete instrument loading
195          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
# Line 155  namespace LinuxSampler { namespace gig { Line 223  namespace LinuxSampler { namespace gig {
223          pEntry->ID.Index      = Key.Index;          pEntry->ID.Index      = Key.Index;
224          pEntry->pGig          = pGig;          pEntry->pGig          = pGig;
225    
226          gig::EngineChannel* pEngineChannel = (gig::EngineChannel*) pConsumer;          gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(pConsumer);
227          // 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'
228          pEntry->MaxSamplesPerCycle =          pEntry->MaxSamplesPerCycle =
229              (pEngineChannel && pEngineChannel->GetEngine()) ? dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()              (!pEngineChannel) ? 0 /* don't care for instrument editors */ :
230                                            : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;                  (pEngineChannel->GetEngine()) ?
231                        dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()
232                        : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;
233          pArg = pEntry;          pArg = pEntry;
234    
235          return pInstrument;          return pInstrument;
# Line 167  namespace LinuxSampler { namespace gig { Line 237  namespace LinuxSampler { namespace gig {
237    
238      void InstrumentResourceManager::Destroy( ::gig::Instrument* pResource, void* pArg) {      void InstrumentResourceManager::Destroy( ::gig::Instrument* pResource, void* pArg) {
239          instr_entry_t* pEntry = (instr_entry_t*) pArg;          instr_entry_t* pEntry = (instr_entry_t*) pArg;
         // remove volume entry if necessary  
         void* pCustomData = CustomData(pEntry->ID);  
         if (pCustomData) {  
             delete (float*)pCustomData;  
             SetCustomData(pEntry->ID, NULL);  
         }  
240          // we don't need the .gig file here anymore          // we don't need the .gig file here anymore
241          Gigs.HandBack(pEntry->pGig, (GigConsumer*) pEntry->ID.Index); // conversion kinda hackish :/          Gigs.HandBack(pEntry->pGig, (GigConsumer*) pEntry->ID.Index); // conversion kinda hackish :/
242          delete pEntry;          delete pEntry;
# Line 182  namespace LinuxSampler { namespace gig { Line 246  namespace LinuxSampler { namespace gig {
246          instr_entry_t* pEntry = (instr_entry_t*) pArg;          instr_entry_t* pEntry = (instr_entry_t*) pArg;
247          gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(pConsumer);          gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(pConsumer);
248          uint maxSamplesPerCycle =          uint maxSamplesPerCycle =
249              (pEngineChannel->GetEngine()) ? dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()              (pEngineChannel && pEngineChannel->GetEngine()) ? dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()
250                                            : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;                                            : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;
251          if (pEntry->MaxSamplesPerCycle < maxSamplesPerCycle) {          if (pEntry->MaxSamplesPerCycle < maxSamplesPerCycle) {
252              Update(pResource, pConsumer);              Update(pResource, pConsumer);
# Line 190  namespace LinuxSampler { namespace gig { Line 254  namespace LinuxSampler { namespace gig {
254      }      }
255    
256      /**      /**
257         * Give back an instrument. This should be used instead of
258         * HandBack if there are some dimension regions that are still in
259         * use. (When an instrument is changed, the voices currently
260         * playing is allowed to keep playing with the old instrument
261         * until note off arrives. New notes will use the new instrument.)
262         */
263        void InstrumentResourceManager::HandBackInstrument(::gig::Instrument* pResource, InstrumentConsumer* pConsumer,
264                                                           ::gig::DimensionRegion** dimRegionsInUse) {
265            DimRegInfoMutex.Lock();
266            for (int i = 0 ; dimRegionsInUse[i] ; i++) {
267                DimRegInfo[dimRegionsInUse[i]].refCount++;
268                SampleRefCount[dimRegionsInUse[i]->pSample]++;
269            }
270            HandBack(pResource, pConsumer, true);
271            DimRegInfoMutex.Unlock();
272        }
273    
274        /**
275         * Give back a dimension region that belongs to an instrument that
276         * was previously handed back.
277         */
278        void InstrumentResourceManager::HandBackDimReg(::gig::DimensionRegion* pDimReg) {
279            DimRegInfoMutex.Lock();
280            dimreg_info_t& dimRegInfo = DimRegInfo[pDimReg];
281            int dimRegRefCount = --dimRegInfo.refCount;
282            int sampleRefCount = --SampleRefCount[pDimReg->pSample];
283            if (dimRegRefCount == 0) {
284                ::gig::File* gig = dimRegInfo.file;
285                ::RIFF::File* riff = dimRegInfo.riff;
286                DimRegInfo.erase(pDimReg);
287                // TODO: we could delete Region and Instrument here if
288                // they have become unused
289    
290                if (sampleRefCount == 0) {
291                    SampleRefCount.erase(pDimReg->pSample);
292    
293                    if (gig) {
294                        gig->DeleteSample(pDimReg->pSample);
295                        if (!gig->GetFirstSample()) {
296                            dmsg(2,("No more samples in use - freeing gig\n"));
297                            delete gig;
298                            delete riff;
299                        }
300                    }
301                }
302            }
303            DimRegInfoMutex.Unlock();
304        }
305    
306        /**
307       *  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
308       *  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
309       *  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
# Line 244  namespace LinuxSampler { namespace gig { Line 358  namespace LinuxSampler { namespace gig {
358    
359      void InstrumentResourceManager::GigResourceManager::Destroy(::gig::File* pResource, void* pArg) {      void InstrumentResourceManager::GigResourceManager::Destroy(::gig::File* pResource, void* pArg) {
360          dmsg(1,("Freeing gig file from memory..."));          dmsg(1,("Freeing gig file from memory..."));
361          delete pResource;  
362          delete (::RIFF::File*) pArg;          // Delete as much as possible of the gig file. Some of the
363            // dimension regions and samples may still be in use - these
364            // will be deleted later by the HandBackDimReg function.
365            bool deleteFile = true;
366            ::gig::Instrument* nextInstrument;
367            for (::gig::Instrument* instrument = pResource->GetFirstInstrument() ;
368                 instrument ;
369                 instrument = nextInstrument) {
370                nextInstrument = pResource->GetNextInstrument();
371                bool deleteInstrument = true;
372                ::gig::Region* nextRegion;
373                for (::gig::Region *region = instrument->GetFirstRegion() ;
374                     region ;
375                     region = nextRegion) {
376                    nextRegion = instrument->GetNextRegion();
377                    bool deleteRegion = true;
378                    for (int i = 0 ; i < region->DimensionRegions ; i++)
379                    {
380                        ::gig::DimensionRegion *d = region->pDimensionRegions[i];
381                        std::map< ::gig::DimensionRegion*, dimreg_info_t>::iterator iter = parent->DimRegInfo.find(d);
382                        if (iter != parent->DimRegInfo.end()) {
383                            dimreg_info_t& dimRegInfo = (*iter).second;
384                            dimRegInfo.file = pResource;
385                            dimRegInfo.riff = (::RIFF::File*)pArg;
386                            deleteFile = deleteInstrument = deleteRegion = false;
387                        }
388                    }
389                    if (deleteRegion) instrument->DeleteRegion(region);
390                }
391                if (deleteInstrument) pResource->DeleteInstrument(instrument);
392            }
393            if (deleteFile) {
394                delete pResource;
395                delete (::RIFF::File*) pArg;
396            } else {
397                dmsg(2,("keeping some samples that are in use..."));
398                ::gig::Sample* nextSample;
399                for (::gig::Sample* sample = pResource->GetFirstSample() ;
400                     sample ;
401                     sample = nextSample) {
402                    nextSample = pResource->GetNextSample();
403                    if (parent->SampleRefCount.find(sample) == parent->SampleRefCount.end()) {
404                        pResource->DeleteSample(sample);
405                    }
406                }
407            }
408          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
409      }      }
410    

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

  ViewVC Help
Powered by ViewVC