/[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 1321 by schoenebeck, Tue Sep 4 01:12:49 2007 UTC revision 1771 by iliev, Wed Sep 10 15:02:24 2008 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 - 2007 Christian Schoenebeck                       *   *   Copyright (C) 2005 - 2008 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"  #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 66  namespace LinuxSampler { namespace gig { Line 67  namespace LinuxSampler { namespace gig {
67    
68          // the instrument we borrowed on behalf of the editor          // the instrument we borrowed on behalf of the editor
69          ::gig::Instrument* pInstrument;          ::gig::Instrument* pInstrument;
70            // the instrument editor we work on behalf
71            InstrumentEditor* pEditor;
72      };      };
73    
74      /**      /**
# Line 114  namespace LinuxSampler { namespace gig { Line 117  namespace LinuxSampler { namespace gig {
117          return ::gig::libraryVersion();          return ::gig::libraryVersion();
118      }      }
119    
120        std::vector<InstrumentResourceManager::instrument_id_t> InstrumentResourceManager::GetInstrumentFileContent(String File) throw (InstrumentManagerException) {
121            ::RIFF::File* riff = NULL;
122            ::gig::File*  gig  = NULL;
123            try {
124                std::vector<instrument_id_t> result;
125                riff = new ::RIFF::File(File);
126                gig  = new ::gig::File(riff);
127                gig->SetAutoLoad(false); // avoid time consuming samples scanning
128                for (int i = 0; gig->GetInstrument(i); i++) {
129                    instrument_id_t id;
130                    id.FileName = File;
131                    id.Index    = i;
132                    result.push_back(id);
133                }
134                if (gig)  delete gig;
135                if (riff) delete riff;
136                return result;
137            } catch (::RIFF::Exception e) {
138                if (gig)  delete gig;
139                if (riff) delete riff;
140                throw InstrumentManagerException(e.Message);
141            } catch (...) {
142                if (gig)  delete gig;
143                if (riff) delete riff;
144                throw InstrumentManagerException("Unknown exception while trying to parse '" + File + "'");
145            }
146        }
147    
148        InstrumentResourceManager::instrument_info_t InstrumentResourceManager::GetInstrumentInfo(instrument_id_t ID) throw (InstrumentManagerException) {
149            Lock();
150            ::gig::Instrument* pInstrument = Resource(ID, false);
151            bool loaded = (pInstrument != NULL);
152            if (!loaded) Unlock();
153    
154            ::RIFF::File* riff = NULL;
155            ::gig::File*  gig  = NULL;
156            try {
157                if(!loaded) {
158                    riff = new ::RIFF::File(ID.FileName);
159                    gig  = new ::gig::File(riff);
160                    gig->SetAutoLoad(false); // avoid time consuming samples scanning
161                    pInstrument = gig->GetInstrument(ID.Index);
162                }
163                
164                if (!pInstrument) throw InstrumentManagerException("There is no instrument " + ToString(ID.Index) + " in " + ID.FileName);
165    
166                instrument_info_t info;
167                for (int i = 0; i < 128; i++) { info.KeyBindings[i] = info.KeySwitchBindings[i] = 0; }
168    
169                ::gig::File* pFile = (::gig::File*) pInstrument->GetParent();
170    
171                if (pFile->pVersion) {
172                    info.FormatVersion = ToString(pFile->pVersion->major);
173                    info.Product = pFile->pInfo->Product;
174                    info.Artists = pFile->pInfo->Artists;
175                }
176    
177                info.InstrumentName = pInstrument->pInfo->Name;
178    
179                ::gig::Region* pRegion = pInstrument->GetFirstRegion();
180                while (pRegion) {
181                    int low = pRegion->KeyRange.low;
182                    int high = pRegion->KeyRange.high;
183                    if (low < 0 || low > 127 || high < 0 || high > 127 || low > high) {
184                        std::cerr << "Invalid key range: " << low << " - " << high << std::endl;
185                    } else {
186                        for (int i = low; i <= high; i++) info.KeyBindings[i] = 1;
187                    }
188                    pRegion = pInstrument->GetNextRegion();
189                }
190                
191                int low = pInstrument->DimensionKeyRange.low;
192                int high = pInstrument->DimensionKeyRange.high;
193                if (low < 0 || low > 127 || high < 0 || high > 127 || low > high) {
194                    std::cerr << "Invalid keyswitch range: " << low << " - " << high << std::endl;
195                } else {
196                    for (int i = low; i <= high; i++) info.KeySwitchBindings[i] = 1;
197                }
198    
199                if (loaded) Unlock();
200    
201                if (gig)  delete gig;
202                if (riff) delete riff;
203                return info;
204            } catch (::RIFF::Exception e) {
205                if (loaded) Unlock();
206                if (gig)  delete gig;
207                if (riff) delete riff;
208                throw InstrumentManagerException(e.Message);
209            } catch (...) {
210                if (loaded) Unlock();
211                if (gig)  delete gig;
212                if (riff) delete riff;
213                throw InstrumentManagerException("Unknown exception while trying to parse '" + ID.FileName + "'");
214            }
215        }
216    
217      void InstrumentResourceManager::LaunchInstrumentEditor(instrument_id_t ID) throw (InstrumentManagerException) {      void InstrumentResourceManager::LaunchInstrumentEditor(instrument_id_t ID) throw (InstrumentManagerException) {
218          const String sDataType    = GetInstrumentDataStructureName(ID);          const String sDataType    = GetInstrumentDataStructureName(ID);
219          const String sDataVersion = GetInstrumentDataStructureVersion(ID);          const String sDataVersion = GetInstrumentDataStructureVersion(ID);
# Line 136  namespace LinuxSampler { namespace gig { Line 236  namespace LinuxSampler { namespace gig {
236          ::gig::Instrument* pInstrument = Borrow(ID, pProxy);          ::gig::Instrument* pInstrument = Borrow(ID, pProxy);
237          // remember the proxy and instrument for this instrument editor          // remember the proxy and instrument for this instrument editor
238          pProxy->pInstrument = pInstrument;          pProxy->pInstrument = pInstrument;
239            pProxy->pEditor     = pEditor;
240          InstrumentEditorProxiesMutex.Lock();          InstrumentEditorProxiesMutex.Lock();
241          InstrumentEditorProxies[pEditor] = pProxy;          InstrumentEditorProxies.add(pProxy);
242          InstrumentEditorProxiesMutex.Unlock();          InstrumentEditorProxiesMutex.Unlock();
243          // launch the instrument editor for the given instrument          // launch the instrument editor for the given instrument
244          pEditor->Launch(pInstrument, sDataType, sDataVersion);          pEditor->Launch(pInstrument, sDataType, sDataVersion);
245    
246            // register the instrument editor as virtual MIDI device as well ...
247            VirtualMidiDevice* pVirtualMidiDevice =
248                dynamic_cast<VirtualMidiDevice*>(pEditor);
249            if (!pVirtualMidiDevice) {
250                std::cerr << "Instrument editor not a virtual MIDI device\n" << std::flush;
251                return;
252            }
253            // NOTE: for now connect the virtual MIDI keyboard of the instrument editor (if any) with all engine channels that have the same instrument as the editor was opened for ( other ideas ? )
254            Lock();
255            std::set<gig::EngineChannel*> engineChannels =
256                GetEngineChannelsUsing(pInstrument, false/*don't lock again*/);
257            std::set<gig::EngineChannel*>::iterator iter = engineChannels.begin();
258            std::set<gig::EngineChannel*>::iterator end  = engineChannels.end();
259            for (; iter != end; ++iter) (*iter)->Connect(pVirtualMidiDevice);
260            Unlock();
261      }      }
262    
263      /**      /**
# Line 152  namespace LinuxSampler { namespace gig { Line 269  namespace LinuxSampler { namespace gig {
269       */       */
270      void InstrumentResourceManager::OnInstrumentEditorQuit(InstrumentEditor* pSender) {      void InstrumentResourceManager::OnInstrumentEditorQuit(InstrumentEditor* pSender) {
271          dmsg(1,("InstrumentResourceManager: instrument editor quit, doing cleanup\n"));          dmsg(1,("InstrumentResourceManager: instrument editor quit, doing cleanup\n"));
272          // hand back instrument and free proxy  
273            ::gig::Instrument* pInstrument = NULL;
274            InstrumentEditorProxy* pProxy  = NULL;
275            int iProxyIndex                = -1;
276    
277            // first find the editor proxy entry for this editor
278          InstrumentEditorProxiesMutex.Lock();          InstrumentEditorProxiesMutex.Lock();
279          if (InstrumentEditorProxies.count(pSender)) {          for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
280              InstrumentEditorProxy* pProxy =              InstrumentEditorProxy* pCurProxy =
281                  dynamic_cast<InstrumentEditorProxy*>(                  dynamic_cast<InstrumentEditorProxy*>(
282                      InstrumentEditorProxies[pSender]                      InstrumentEditorProxies[i]
283                  );                  );
284              InstrumentEditorProxies.erase(pSender);              if (pCurProxy->pEditor == pSender) {
285              InstrumentEditorProxiesMutex.Unlock();                  pProxy      = pCurProxy;
286              HandBack(pProxy->pInstrument, pProxy);                  iProxyIndex = i;
287              if (pProxy) delete pProxy;                  pInstrument = pCurProxy->pInstrument;
288                }
289            }
290            InstrumentEditorProxiesMutex.Unlock();
291    
292            if (!pProxy) {
293                std::cerr << "Eeeek, could not find instrument editor proxy, "
294                             "this is a bug!\n" << std::flush;
295                return;
296            }
297    
298            // now unregister editor as not being available as a virtual MIDI device anymore
299            VirtualMidiDevice* pVirtualMidiDevice =
300                dynamic_cast<VirtualMidiDevice*>(pSender);
301            if (pVirtualMidiDevice) {
302                Lock();
303                // NOTE: see note in LaunchInstrumentEditor()
304                std::set<gig::EngineChannel*> engineChannels =
305                    GetEngineChannelsUsing(pInstrument, false/*don't lock again*/);
306                std::set<gig::EngineChannel*>::iterator iter = engineChannels.begin();
307                std::set<gig::EngineChannel*>::iterator end  = engineChannels.end();
308                for (; iter != end; ++iter) (*iter)->Disconnect(pVirtualMidiDevice);
309                Unlock();
310          } else {          } else {
311                std::cerr << "Could not unregister editor as not longer acting as "
312                             "virtual MIDI device. Wasn't it registered?\n"
313                          << std::flush;
314            }
315    
316            // finally delete proxy entry and hand back instrument
317            if (pInstrument) {
318                InstrumentEditorProxiesMutex.Lock();
319                InstrumentEditorProxies.remove(iProxyIndex);
320              InstrumentEditorProxiesMutex.Unlock();              InstrumentEditorProxiesMutex.Unlock();
321              std::cerr << "Eeeek, could not find instrument editor proxy, this is a bug!\n" << std::flush;  
322                HandBack(pInstrument, pProxy);
323                delete pProxy;
324            }
325    
326            // Note that we don't need to free the editor here. As it
327            // derives from Thread, it will delete itself when the thread
328            // dies.
329        }
330    
331    #if 0 // currently unused :
332        /**
333         * Try to inform the respective instrument editor(s), that a note on
334         * event just occured. This method is called by the MIDI thread. If any
335         * obstacles are in the way (e.g. if a wait for an unlock would be
336         * required) we give up immediately, since the RT safeness of the MIDI
337         * thread has absolute priority.
338         */
339        void InstrumentResourceManager::TrySendNoteOnToEditors(uint8_t Key, uint8_t Velocity, ::gig::Instrument* pInstrument) {
340            const bool bGotLock = InstrumentEditorProxiesMutex.Trylock(); // naively assumes RT safe implementation
341            if (!bGotLock) return; // hell, forget it, not worth the hassle
342            for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
343                InstrumentEditorProxy* pProxy =
344                    dynamic_cast<InstrumentEditorProxy*>(
345                        InstrumentEditorProxies[i]
346                    );
347                if (pProxy->pInstrument == pInstrument)
348                    pProxy->pEditor->SendNoteOnToDevice(Key, Velocity);
349            }
350            InstrumentEditorProxiesMutex.Unlock(); // naively assumes RT safe implementation
351        }
352    
353        /**
354         * Try to inform the respective instrument editor(s), that a note off
355         * event just occured. This method is called by the MIDI thread. If any
356         * obstacles are in the way (e.g. if a wait for an unlock would be
357         * required) we give up immediately, since the RT safeness of the MIDI
358         * thread has absolute priority.
359         */
360        void InstrumentResourceManager::TrySendNoteOffToEditors(uint8_t Key, uint8_t Velocity, ::gig::Instrument* pInstrument) {
361            const bool bGotLock = InstrumentEditorProxiesMutex.Trylock(); // naively assumes RT safe implementation
362            if (!bGotLock) return; // hell, forget it, not worth the hassle
363            for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
364                InstrumentEditorProxy* pProxy =
365                    dynamic_cast<InstrumentEditorProxy*>(
366                        InstrumentEditorProxies[i]
367                    );
368                if (pProxy->pInstrument == pInstrument)
369                    pProxy->pEditor->SendNoteOffToDevice(Key, Velocity);
370          }          }
371          // free the editor          InstrumentEditorProxiesMutex.Unlock(); // naively assumes RT safe implementation
         InstrumentEditorFactory::Destroy(pSender);  
372      }      }
373    #endif // unused
374    
375      void InstrumentResourceManager::OnSamplesToBeRemoved(std::set<void*> Samples, InstrumentEditor* pSender) {      void InstrumentResourceManager::OnSamplesToBeRemoved(std::set<void*> Samples, InstrumentEditor* pSender) {
376          if (Samples.empty()) {          if (Samples.empty()) {
# Line 401  namespace LinuxSampler { namespace gig { Line 602  namespace LinuxSampler { namespace gig {
602       * Give back an instrument. This should be used instead of       * Give back an instrument. This should be used instead of
603       * HandBack if there are some dimension regions that are still in       * HandBack if there are some dimension regions that are still in
604       * use. (When an instrument is changed, the voices currently       * use. (When an instrument is changed, the voices currently
605       * playing is allowed to keep playing with the old instrument       * playing are allowed to keep playing with the old instrument
606       * until note off arrives. New notes will use the new instrument.)       * until note off arrives. New notes will use the new instrument.)
607       */       */
608      void InstrumentResourceManager::HandBackInstrument(::gig::Instrument* pResource, InstrumentConsumer* pConsumer,      void InstrumentResourceManager::HandBackInstrument(::gig::Instrument* pResource, InstrumentConsumer* pConsumer,
609                                                         ::gig::DimensionRegion** dimRegionsInUse) {                                                         RTList< ::gig::DimensionRegion*>* pDimRegionsInUse) {
610          DimRegInfoMutex.Lock();          DimRegInfoMutex.Lock();
611          for (int i = 0 ; dimRegionsInUse[i] ; i++) {          for (RTList< ::gig::DimensionRegion*>::Iterator i = pDimRegionsInUse->first() ; i != pDimRegionsInUse->end() ; i++) {
612              DimRegInfo[dimRegionsInUse[i]].refCount++;              DimRegInfo[*i].refCount++;
613              SampleRefCount[dimRegionsInUse[i]->pSample]++;              SampleRefCount[(*i)->pSample]++;
614          }          }
615          HandBack(pResource, pConsumer, true);          HandBack(pResource, pConsumer, true);
616          DimRegInfoMutex.Unlock();          DimRegInfoMutex.Unlock();
# Line 529  namespace LinuxSampler { namespace gig { Line 730  namespace LinuxSampler { namespace gig {
730          if (bLock) Unlock();          if (bLock) Unlock();
731          return result;          return result;
732      }      }
733    
734        /**
735         * Returns a list with all gig engine channels that are currently using
736         * the given instrument.
737         *
738         * @param pInstrument - search criteria
739         * @param bLock - whether we should lock (mutex) the instrument manager
740         *                during this call and unlock at the end of this call
741         */
742        std::set<gig::EngineChannel*> InstrumentResourceManager::GetEngineChannelsUsing(::gig::Instrument* pInstrument, bool bLock) {
743            if (bLock) Lock();
744            std::set<gig::EngineChannel*> result;
745            std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(pInstrument);
746            std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
747            std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();
748            for (; iter != end; ++iter) {
749                gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(*iter);
750                if (!pEngineChannel) continue;
751                result.insert(pEngineChannel);
752            }
753            if (bLock) Unlock();
754            return result;
755        }
756    
757      /**      /**
758       * Returns a list with all gig Engines that are currently using the given       * Returns a list with all gig Engines that are currently using the given

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

  ViewVC Help
Powered by ViewVC