/[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 970 by schoenebeck, Wed Dec 6 22:28:17 2006 UTC revision 2327 by persson, Sat Mar 10 16:16:14 2012 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 - 2012 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 24  Line 24 
24  #include <sstream>  #include <sstream>
25    
26  #include "InstrumentResourceManager.h"  #include "InstrumentResourceManager.h"
27    #include "EngineChannel.h"
28    #include "Engine.h"
29    
30  // We need to know the maximum number of sample points which are going to  #include "../../common/global_private.h"
31  // be processed for each render cycle of the audio output driver, to know  #include "../../plugins/InstrumentEditorFactory.h"
 // how much initial sample points we need to cache into RAM. If the given  
 // sampler channel does not have an audio output device assigned yet  
 // though, we simply use this default value.  
 #define GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE     128  
32    
33  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
34    
     // data stored as long as an instrument resource exists  
     struct instr_entry_t {  
         InstrumentManager::instrument_id_t ID;  
         ::gig::File*                       pGig;  
         uint                               MaxSamplesPerCycle; ///< if some engine requests an already allocated instrument with a higher value, we have to reallocate the instrument  
     };  
   
35      // some data needed for the libgig callback function      // some data needed for the libgig callback function
36      struct progress_callback_arg_t {      struct progress_callback_arg_t {
37          InstrumentResourceManager*          pManager;          InstrumentResourceManager*          pManager;
38          InstrumentManager::instrument_id_t* pInstrumentKey;          InstrumentManager::instrument_id_t* pInstrumentKey;
39      };      };
40    
41        // we use this to react on events concerning an instrument on behalf of an instrument editor
42        class InstrumentEditorProxy : public InstrumentConsumer {
43        public:
44            virtual void ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {
45                //TODO: inform the instrument editor about the pending update
46            }
47    
48            virtual void ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {
49                //TODO:: inform the instrument editor about finished update
50            }
51    
52            virtual void OnResourceProgress(float fProgress) {
53                //TODO: inform the instrument editor about the progress of an update
54            }
55    
56            // the instrument we borrowed on behalf of the editor
57            ::gig::Instrument* pInstrument;
58            // the instrument editor we work on behalf
59            InstrumentEditor* pEditor;
60        };
61    
62      /**      /**
63       * Callback function which will be called by libgig during loading of       * Callback function which will be called by libgig during loading of
64       * instruments to inform about the current progress. Or to be more       * instruments to inform about the current progress. Or to be more
# Line 64  namespace LinuxSampler { namespace gig { Line 76  namespace LinuxSampler { namespace gig {
76          pArg->pManager->DispatchResourceProgressEvent(*pArg->pInstrumentKey, localProgress);          pArg->pManager->DispatchResourceProgressEvent(*pArg->pInstrumentKey, localProgress);
77      }      }
78    
79      std::vector<InstrumentResourceManager::instrument_id_t> InstrumentResourceManager::Instruments() {      String InstrumentResourceManager::GetInstrumentName(instrument_id_t ID) {
80          return Entries();          Lock();
81            ::gig::Instrument* pInstrument = Resource(ID, false);
82            String res = (pInstrument) ? pInstrument->pInfo->Name : "";
83            Unlock();
84            return res;
85      }      }
86    
87      InstrumentManager::mode_t InstrumentResourceManager::GetMode(const instrument_id_t& ID) {      String InstrumentResourceManager::GetInstrumentDataStructureName(instrument_id_t ID) {
88          return static_cast<InstrumentManager::mode_t>(AvailabilityMode(ID));          return ::gig::libraryName();
89      }      }
90    
91      void InstrumentResourceManager::SetMode(const instrument_id_t& ID, InstrumentManager::mode_t Mode) {      String InstrumentResourceManager::GetInstrumentDataStructureVersion(instrument_id_t ID) {
92          dmsg(2,("gig::InstrumentResourceManager: setting mode for %s (Index=%d) to %d\n",ID.FileName.c_str(),ID.Index,Mode));          return ::gig::libraryVersion();
         SetAvailabilityMode(ID, static_cast<ResourceManager<InstrumentManager::instrument_id_t, ::gig::Instrument>::mode_t>(Mode));  
93      }      }
94    
95      String InstrumentResourceManager::GetInstrumentName(instrument_id_t ID) {      std::vector<InstrumentResourceManager::instrument_id_t> InstrumentResourceManager::GetInstrumentFileContent(String File) throw (InstrumentManagerException) {
96            ::RIFF::File* riff = NULL;
97            ::gig::File*  gig  = NULL;
98            try {
99                std::vector<instrument_id_t> result;
100                riff = new ::RIFF::File(File);
101                gig  = new ::gig::File(riff);
102                gig->SetAutoLoad(false); // avoid time consuming samples scanning
103                for (int i = 0; gig->GetInstrument(i); i++) {
104                    instrument_id_t id;
105                    id.FileName = File;
106                    id.Index    = i;
107                    result.push_back(id);
108                }
109                if (gig)  delete gig;
110                if (riff) delete riff;
111                return result;
112            } catch (::RIFF::Exception e) {
113                if (gig)  delete gig;
114                if (riff) delete riff;
115                throw InstrumentManagerException(e.Message);
116            } catch (...) {
117                if (gig)  delete gig;
118                if (riff) delete riff;
119                throw InstrumentManagerException("Unknown exception while trying to parse '" + File + "'");
120            }
121        }
122    
123        InstrumentResourceManager::instrument_info_t InstrumentResourceManager::GetInstrumentInfo(instrument_id_t ID) throw (InstrumentManagerException) {
124          Lock();          Lock();
125          ::gig::Instrument* pInstrument = Resource(ID, false);          ::gig::Instrument* pInstrument = Resource(ID, false);
126          String res = (pInstrument) ? pInstrument->pInfo->Name : "";          bool loaded = (pInstrument != NULL);
127            if (!loaded) Unlock();
128    
129            ::RIFF::File* riff = NULL;
130            ::gig::File*  gig  = NULL;
131            try {
132                if (!loaded) {
133                    riff = new ::RIFF::File(ID.FileName);
134                    gig  = new ::gig::File(riff);
135                    gig->SetAutoLoad(false); // avoid time consuming samples scanning
136                    pInstrument = gig->GetInstrument(ID.Index);
137                }
138    
139                if (!pInstrument) throw InstrumentManagerException("There is no instrument " + ToString(ID.Index) + " in " + ID.FileName);
140    
141                instrument_info_t info;
142                for (int i = 0; i < 128; i++) { info.KeyBindings[i] = info.KeySwitchBindings[i] = 0; }
143    
144                ::gig::File* pFile = (::gig::File*) pInstrument->GetParent();
145    
146                if (pFile->pVersion) {
147                    info.FormatVersion = ToString(pFile->pVersion->major);
148                    info.Product = pFile->pInfo->Product;
149                    info.Artists = pFile->pInfo->Artists;
150                }
151    
152                info.InstrumentName = pInstrument->pInfo->Name;
153    
154                ::gig::Region* pRegion = pInstrument->GetFirstRegion();
155                while (pRegion) {
156                    int low = pRegion->KeyRange.low;
157                    int high = pRegion->KeyRange.high;
158                    if (low < 0 || low > 127 || high < 0 || high > 127 || low > high) {
159                        std::cerr << "Invalid key range: " << low << " - " << high << std::endl;
160                    } else {
161                        for (int i = low; i <= high; i++) info.KeyBindings[i] = 1;
162                    }
163    
164                    pRegion = pInstrument->GetNextRegion();
165                }
166    
167                if (loaded) { // retrieve keyswitching only if the instrument is fully loaded.
168    
169                    // only return keyswitch range if keyswitching is used
170                    bool hasKeyswitches = false;
171                    for (::gig::Region* pRegion = pInstrument->GetFirstRegion() ;
172                         pRegion && !hasKeyswitches ;
173                         pRegion = pInstrument->GetNextRegion()) {
174                        for (int i = 0 ; i < pRegion->Dimensions ; i++) {
175                            if (pRegion->pDimensionDefinitions[i].dimension == ::gig::dimension_keyboard) {
176                                hasKeyswitches = true;
177                                break;
178                            }
179                        }
180                    }
181    
182                    if (hasKeyswitches) {
183                        int low = pInstrument->DimensionKeyRange.low;
184                        int high = pInstrument->DimensionKeyRange.high;
185                        if (low < 0 || low > 127 || high < 0 || high > 127 || low > high) {
186                            std::cerr << "Invalid keyswitch range: " << low << " - " << high << std::endl;
187                        } else {
188                            for (int i = low; i <= high; i++) info.KeySwitchBindings[i] = 1;
189                        }
190                    }
191                }
192    
193                if (loaded) Unlock();
194    
195                if (gig)  delete gig;
196                if (riff) delete riff;
197                return info;
198            } catch (::RIFF::Exception e) {
199                if (loaded) Unlock();
200                if (gig)  delete gig;
201                if (riff) delete riff;
202                throw InstrumentManagerException(e.Message);
203            } catch (...) {
204                if (loaded) Unlock();
205                if (gig)  delete gig;
206                if (riff) delete riff;
207                throw InstrumentManagerException("Unknown exception while trying to parse '" + ID.FileName + "'");
208            }
209        }
210    
211        InstrumentEditor* InstrumentResourceManager::LaunchInstrumentEditor(instrument_id_t ID, void* pUserData) throw (InstrumentManagerException) {
212            const String sDataType    = GetInstrumentDataStructureName(ID);
213            const String sDataVersion = GetInstrumentDataStructureVersion(ID);
214            // find instrument editors capable to handle given instrument
215            std::vector<String> vEditors =
216                InstrumentEditorFactory::MatchingEditors(sDataType, sDataVersion);
217            if (!vEditors.size())
218                throw InstrumentManagerException(
219                    "There is no instrument editor capable to handle this instrument"
220                );
221            // simply use the first editor in the result set
222            dmsg(1,("Found matching editor '%s' for instrument ('%s', %d) having data structure ('%s','%s')\n",
223                vEditors[0].c_str(), ID.FileName.c_str(), ID.Index, sDataType.c_str(), sDataVersion.c_str()));
224            InstrumentEditor* pEditor = InstrumentEditorFactory::Create(vEditors[0]);
225            // register for receiving notifications from the instrument editor
226            pEditor->AddListener(this);
227            // create a proxy that reacts on notification on behalf of the editor
228            InstrumentEditorProxy* pProxy = new InstrumentEditorProxy;
229            // borrow the instrument on behalf of the instrument editor
230            ::gig::Instrument* pInstrument = Borrow(ID, pProxy);
231            // remember the proxy and instrument for this instrument editor
232            pProxy->pInstrument = pInstrument;
233            pProxy->pEditor     = pEditor;
234            InstrumentEditorProxiesMutex.Lock();
235            InstrumentEditorProxies.add(pProxy);
236            InstrumentEditorProxiesMutex.Unlock();
237            // launch the instrument editor for the given instrument
238            pEditor->Launch(pInstrument, sDataType, sDataVersion, pUserData);
239    
240            // register the instrument editor as virtual MIDI device as well ...
241            VirtualMidiDevice* pVirtualMidiDevice =
242                dynamic_cast<VirtualMidiDevice*>(pEditor);
243            if (!pVirtualMidiDevice) {
244                std::cerr << "Instrument editor not a virtual MIDI device\n" << std::flush;
245                return pEditor;
246            }
247            // 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 ? )
248            Lock();
249            std::set<EngineChannel*> engineChannels =
250                GetEngineChannelsUsing(pInstrument, false/*don't lock again*/);
251            std::set<EngineChannel*>::iterator iter = engineChannels.begin();
252            std::set<EngineChannel*>::iterator end  = engineChannels.end();
253            for (; iter != end; ++iter) (static_cast<AbstractEngineChannel*>(*iter))->Connect(pVirtualMidiDevice);
254          Unlock();          Unlock();
255          return res;  
256            return pEditor;
257        }
258    
259        /**
260         * Will be called by the respective instrument editor once it left its
261         * Main() loop. That way we can handle cleanup before its thread finally
262         * dies.
263         *
264         * @param pSender - instrument editor that stops execution
265         */
266        void InstrumentResourceManager::OnInstrumentEditorQuit(InstrumentEditor* pSender) {
267            dmsg(1,("InstrumentResourceManager: instrument editor quit, doing cleanup\n"));
268    
269            ::gig::Instrument* pInstrument = NULL;
270            InstrumentEditorProxy* pProxy  = NULL;
271            int iProxyIndex                = -1;
272    
273            // first find the editor proxy entry for this editor
274            InstrumentEditorProxiesMutex.Lock();
275            for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
276                InstrumentEditorProxy* pCurProxy =
277                    dynamic_cast<InstrumentEditorProxy*>(
278                        InstrumentEditorProxies[i]
279                    );
280                if (pCurProxy->pEditor == pSender) {
281                    pProxy      = pCurProxy;
282                    iProxyIndex = i;
283                    pInstrument = pCurProxy->pInstrument;
284                }
285            }
286            InstrumentEditorProxiesMutex.Unlock();
287    
288            if (!pProxy) {
289                std::cerr << "Eeeek, could not find instrument editor proxy, "
290                             "this is a bug!\n" << std::flush;
291                return;
292            }
293    
294            // now unregister editor as not being available as a virtual MIDI device anymore
295            VirtualMidiDevice* pVirtualMidiDevice =
296                dynamic_cast<VirtualMidiDevice*>(pSender);
297            if (pVirtualMidiDevice) {
298                Lock();
299                // NOTE: see note in LaunchInstrumentEditor()
300                std::set<EngineChannel*> engineChannels =
301                    GetEngineChannelsUsing(pInstrument, false/*don't lock again*/);
302                std::set<EngineChannel*>::iterator iter = engineChannels.begin();
303                std::set<EngineChannel*>::iterator end  = engineChannels.end();
304                for (; iter != end; ++iter) (*iter)->Disconnect(pVirtualMidiDevice);
305                Unlock();
306            } else {
307                std::cerr << "Could not unregister editor as not longer acting as "
308                             "virtual MIDI device. Wasn't it registered?\n"
309                          << std::flush;
310            }
311    
312            // finally delete proxy entry and hand back instrument
313            if (pInstrument) {
314                InstrumentEditorProxiesMutex.Lock();
315                InstrumentEditorProxies.remove(iProxyIndex);
316                InstrumentEditorProxiesMutex.Unlock();
317    
318                HandBack(pInstrument, pProxy);
319                delete pProxy;
320            }
321    
322            // Note that we don't need to free the editor here. As it
323            // derives from Thread, it will delete itself when the thread
324            // dies.
325        }
326    
327    #if 0 // currently unused :
328        /**
329         * Try to inform the respective instrument editor(s), that a note on
330         * event just occured. This method is called by the MIDI thread. If any
331         * obstacles are in the way (e.g. if a wait for an unlock would be
332         * required) we give up immediately, since the RT safeness of the MIDI
333         * thread has absolute priority.
334         */
335        void InstrumentResourceManager::TrySendNoteOnToEditors(uint8_t Key, uint8_t Velocity, ::gig::Instrument* pInstrument) {
336            const bool bGotLock = InstrumentEditorProxiesMutex.Trylock(); // naively assumes RT safe implementation
337            if (!bGotLock) return; // hell, forget it, not worth the hassle
338            for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
339                InstrumentEditorProxy* pProxy =
340                    dynamic_cast<InstrumentEditorProxy*>(
341                        InstrumentEditorProxies[i]
342                    );
343                if (pProxy->pInstrument == pInstrument)
344                    pProxy->pEditor->SendNoteOnToDevice(Key, Velocity);
345            }
346            InstrumentEditorProxiesMutex.Unlock(); // naively assumes RT safe implementation
347        }
348    
349        /**
350         * Try to inform the respective instrument editor(s), that a note off
351         * event just occured. This method is called by the MIDI thread. If any
352         * obstacles are in the way (e.g. if a wait for an unlock would be
353         * required) we give up immediately, since the RT safeness of the MIDI
354         * thread has absolute priority.
355         */
356        void InstrumentResourceManager::TrySendNoteOffToEditors(uint8_t Key, uint8_t Velocity, ::gig::Instrument* pInstrument) {
357            const bool bGotLock = InstrumentEditorProxiesMutex.Trylock(); // naively assumes RT safe implementation
358            if (!bGotLock) return; // hell, forget it, not worth the hassle
359            for (int i = 0; i < InstrumentEditorProxies.size(); i++) {
360                InstrumentEditorProxy* pProxy =
361                    dynamic_cast<InstrumentEditorProxy*>(
362                        InstrumentEditorProxies[i]
363                    );
364                if (pProxy->pInstrument == pInstrument)
365                    pProxy->pEditor->SendNoteOffToDevice(Key, Velocity);
366            }
367            InstrumentEditorProxiesMutex.Unlock(); // naively assumes RT safe implementation
368        }
369    #endif // unused
370    
371        void InstrumentResourceManager::OnSamplesToBeRemoved(std::set<void*> Samples, InstrumentEditor* pSender) {
372            if (Samples.empty()) {
373                std::cerr << "gig::InstrumentResourceManager: WARNING, "
374                             "OnSamplesToBeRemoved() called with empty list, this "
375                             "is a bug!\n" << std::flush;
376                return;
377            }
378            // TODO: ATM we assume here that all samples are from the same file
379            ::gig::Sample* pFirstSample = (::gig::Sample*) *Samples.begin();
380            ::gig::File* pCriticalFile = dynamic_cast< ::gig::File*>(pFirstSample->GetParent());
381            // completely suspend all engines that use that same file
382            SuspendEnginesUsing(pCriticalFile);
383        }
384    
385        void InstrumentResourceManager::OnSamplesRemoved(InstrumentEditor* pSender) {
386            // resume all previously, completely suspended engines
387            // (we don't have to un-cache the removed samples here, since that is
388            // automatically done by the gig::Sample destructor)
389            ResumeAllEngines();
390        }
391    
392        void InstrumentResourceManager::OnDataStructureToBeChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {
393            //TODO: remove code duplication
394            if (sStructType == "gig::File") {
395                // completely suspend all engines that use that file
396                ::gig::File* pFile = (::gig::File*) pStruct;
397                SuspendEnginesUsing(pFile);
398            } else if (sStructType == "gig::Instrument") {
399                // completely suspend all engines that use that instrument
400                ::gig::Instrument* pInstrument = (::gig::Instrument*) pStruct;
401                SuspendEnginesUsing(pInstrument);
402            } else if (sStructType == "gig::Region") {
403                // only advice the engines to suspend the given region, so they'll
404                // only ignore that region (and probably already other suspended
405                // ones), but beside that continue normal playback
406                ::gig::Region* pRegion = (::gig::Region*) pStruct;
407                ::gig::Instrument* pInstrument =
408                    (::gig::Instrument*) pRegion->GetParent();
409                Lock();
410                std::set<Engine*> engines =
411                    GetEnginesUsing(pInstrument, false/*don't lock again*/);
412                std::set<Engine*>::iterator iter = engines.begin();
413                std::set<Engine*>::iterator end  = engines.end();
414                for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
415                Unlock();
416            } else if (sStructType == "gig::DimensionRegion") {
417                // only advice the engines to suspend the given DimensionRegions's
418                // parent region, so they'll only ignore that region (and probably
419                // already other suspended ones), but beside that continue normal
420                // playback
421                ::gig::DimensionRegion* pDimReg =
422                    (::gig::DimensionRegion*) pStruct;
423                ::gig::Region* pRegion = pDimReg->GetParent();
424                ::gig::Instrument* pInstrument =
425                    (::gig::Instrument*) pRegion->GetParent();
426                Lock();
427                std::set<Engine*> engines =
428                    GetEnginesUsing(pInstrument, false/*don't lock again*/);
429                std::set<Engine*>::iterator iter = engines.begin();
430                std::set<Engine*>::iterator end  = engines.end();
431                for (; iter != end; ++iter) (*iter)->Suspend(pRegion);
432                Unlock();
433            } else {
434                std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
435                             "structure '" << sStructType << "' requested to be "
436                             "suspended by instrument editor. This is a bug!\n"
437                          << std::flush;
438                //TODO: we should inform the instrument editor that something seriously went wrong
439            }
440        }
441    
442        void InstrumentResourceManager::OnDataStructureChanged(void* pStruct, String sStructType, InstrumentEditor* pSender) {
443            //TODO: remove code duplication
444            if (sStructType == "gig::File") {
445                // resume all previously suspended engines
446                ResumeAllEngines();
447            } else if (sStructType == "gig::Instrument") {
448                // resume all previously suspended engines
449                ResumeAllEngines();
450            } else if (sStructType == "gig::Sample") {
451                // we're assuming here, that OnDataStructureToBeChanged() with
452                // "gig::File" was called previously, so we won't resume anything
453                // here, but just re-cache the given sample
454                Lock();
455                ::gig::Sample* pSample = (::gig::Sample*) pStruct;
456                ::gig::File* pFile = (::gig::File*) pSample->GetParent();
457                UncacheInitialSamples(pSample);
458                // now re-cache ...
459                std::vector< ::gig::Instrument*> instruments =
460                    GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
461                for (int i = 0; i < instruments.size(); i++) {
462                    if (SampleReferencedByInstrument(pSample, instruments[i])) {
463                        std::set<EngineChannel*> engineChannels =
464                            GetEngineChannelsUsing(instruments[i], false/*don't lock again*/);
465                        std::set<EngineChannel*>::iterator iter = engineChannels.begin();
466                        std::set<EngineChannel*>::iterator end  = engineChannels.end();
467                        for (; iter != end; ++iter)
468                            CacheInitialSamples(pSample, *iter);
469                    }
470                }
471                Unlock();
472            } else if (sStructType == "gig::Region") {
473                // advice the engines to resume the given region, that is to
474                // using it for playback again
475                ::gig::Region* pRegion = (::gig::Region*) pStruct;
476                ::gig::Instrument* pInstrument =
477                    (::gig::Instrument*) pRegion->GetParent();
478                Lock();
479                std::set<Engine*> engines =
480                    GetEnginesUsing(pInstrument, false/*don't lock again*/);
481                std::set<Engine*>::iterator iter = engines.begin();
482                std::set<Engine*>::iterator end  = engines.end();
483                for (; iter != end; ++iter) (*iter)->Resume(pRegion);
484                Unlock();
485            } else if (sStructType == "gig::DimensionRegion") {
486                // advice the engines to resume the given DimensionRegion's parent
487                // region, that is to using it for playback again
488                ::gig::DimensionRegion* pDimReg =
489                    (::gig::DimensionRegion*) pStruct;
490                ::gig::Region* pRegion = pDimReg->GetParent();
491                ::gig::Instrument* pInstrument =
492                    (::gig::Instrument*) pRegion->GetParent();
493                Lock();
494                std::set<Engine*> engines =
495                    GetEnginesUsing(pInstrument, false/*don't lock again*/);
496                std::set<Engine*>::iterator iter = engines.begin();
497                std::set<Engine*>::iterator end  = engines.end();
498                for (; iter != end; ++iter) (*iter)->Resume(pRegion);
499                Unlock();
500            } else {
501                std::cerr << "gig::InstrumentResourceManager: ERROR, unknown data "
502                             "structure '" << sStructType << "' requested to be "
503                             "resumed by instrument editor. This is a bug!\n"
504                          << std::flush;
505                //TODO: we should inform the instrument editor that something seriously went wrong
506            }
507        }
508    
509        void InstrumentResourceManager::OnSampleReferenceChanged(void* pOldSample, void* pNewSample, InstrumentEditor* pSender) {
510            // uncache old sample in case it's not used by anybody anymore
511            if (pOldSample) {
512                Lock();
513                ::gig::Sample* pSample = (::gig::Sample*) pOldSample;
514                ::gig::File* pFile = (::gig::File*) pSample->GetParent();
515                bool bSampleStillInUse = false;
516                std::vector< ::gig::Instrument*> instruments =
517                    GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
518                for (int i = 0; i < instruments.size(); i++) {
519                    if (SampleReferencedByInstrument(pSample, instruments[i])) {
520                        bSampleStillInUse = true;
521                        break;
522                    }
523                }
524                if (!bSampleStillInUse) UncacheInitialSamples(pSample);
525                Unlock();
526            }
527            // make sure new sample reference is cached
528            if (pNewSample) {
529                Lock();
530                ::gig::Sample* pSample = (::gig::Sample*) pNewSample;
531                ::gig::File* pFile = (::gig::File*) pSample->GetParent();
532                // get all engines that use that same gig::File
533                std::set<Engine*> engines = GetEnginesUsing(pFile, false/*don't lock again*/);
534                std::set<Engine*>::iterator iter = engines.begin();
535                std::set<Engine*>::iterator end  = engines.end();
536                for (; iter != end; ++iter)
537                    CacheInitialSamples(pSample, *iter);
538                Unlock();
539            }
540      }      }
541    
542      ::gig::Instrument* InstrumentResourceManager::Create(instrument_id_t Key, InstrumentConsumer* pConsumer, void*& pArg) {      ::gig::Instrument* InstrumentResourceManager::Create(instrument_id_t Key, InstrumentConsumer* pConsumer, void*& pArg) {
543          // get gig file from inernal gig file manager          // get gig file from internal gig file manager
544          ::gig::File* pGig = Gigs.Borrow(Key.FileName, (GigConsumer*) Key.Index); // conversion kinda hackish :/          ::gig::File* pGig = Gigs.Borrow(Key.FileName, reinterpret_cast<GigConsumer*>(Key.Index)); // conversion kinda hackish :/
545    
546          // we pass this to the progress callback mechanism of libgig          // we pass this to the progress callback mechanism of libgig
547          progress_callback_arg_t callbackArg;          progress_callback_arg_t callbackArg;
# Line 103  namespace LinuxSampler { namespace gig { Line 557  namespace LinuxSampler { namespace gig {
557          if (!pInstrument) {          if (!pInstrument) {
558              std::stringstream msg;              std::stringstream msg;
559              msg << "There's no instrument with index " << Key.Index << ".";              msg << "There's no instrument with index " << Key.Index << ".";
560              throw InstrumentResourceManagerException(msg.str());              throw InstrumentManagerException(msg.str());
561          }          }
562          pGig->GetFirstSample(); // just to force complete instrument loading          pGig->GetFirstSample(); // just to force complete instrument loading
563          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
564    
565            uint maxSamplesPerCycle = GetMaxSamplesPerCycle(pConsumer);
566    
567          // cache initial samples points (for actually needed samples)          // cache initial samples points (for actually needed samples)
568          dmsg(1,("Caching initial samples..."));          dmsg(1,("Caching initial samples..."));
569          uint iRegion = 0; // just for progress calculation          uint iRegion = 0; // just for progress calculation
# Line 119  namespace LinuxSampler { namespace gig { Line 575  namespace LinuxSampler { namespace gig {
575    
576              if (pRgn->GetSample() && !pRgn->GetSample()->GetCache().Size) {              if (pRgn->GetSample() && !pRgn->GetSample()->GetCache().Size) {
577                  dmsg(2,("C"));                  dmsg(2,("C"));
578                  CacheInitialSamples(pRgn->GetSample(), (gig::EngineChannel*) pConsumer);                  CacheInitialSamples(pRgn->GetSample(), maxSamplesPerCycle);
579              }              }
580              for (uint i = 0; i < pRgn->DimensionRegions; i++) {              for (uint i = 0; i < pRgn->DimensionRegions; i++) {
581                  CacheInitialSamples(pRgn->pDimensionRegions[i]->pSample, (gig::EngineChannel*) pConsumer);                  CacheInitialSamples(pRgn->pDimensionRegions[i]->pSample, maxSamplesPerCycle);
582              }              }
583    
584              pRgn = pInstrument->GetNextRegion();              pRgn = pInstrument->GetNextRegion();
# Line 135  namespace LinuxSampler { namespace gig { Line 591  namespace LinuxSampler { namespace gig {
591          instr_entry_t* pEntry = new instr_entry_t;          instr_entry_t* pEntry = new instr_entry_t;
592          pEntry->ID.FileName   = Key.FileName;          pEntry->ID.FileName   = Key.FileName;
593          pEntry->ID.Index      = Key.Index;          pEntry->ID.Index      = Key.Index;
594          pEntry->pGig          = pGig;          pEntry->pFile         = pGig;
595    
596          gig::EngineChannel* pEngineChannel = (gig::EngineChannel*) pConsumer;          // and we save this to check if we need to reallocate for an engine with higher value of 'MaxSamplesPerSecond'
597          // and we save this to check if we need to reallocate for a engine with higher value of 'MaxSamplesPerSecond'          pEntry->MaxSamplesPerCycle = maxSamplesPerCycle;
598          pEntry->MaxSamplesPerCycle =          
             (pEngineChannel && pEngineChannel->GetEngine()) ? dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()  
                                           : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;  
599          pArg = pEntry;          pArg = pEntry;
600    
601          return pInstrument;          return pInstrument;
602      }      }
603    
604      void InstrumentResourceManager::Destroy( ::gig::Instrument* pResource, void* pArg) {      void InstrumentResourceManager::Destroy(::gig::Instrument* pResource, void* pArg) {
605          instr_entry_t* pEntry = (instr_entry_t*) pArg;          instr_entry_t* pEntry = (instr_entry_t*) pArg;
606          // we don't need the .gig file here anymore          // we don't need the .gig file here anymore
607          Gigs.HandBack(pEntry->pGig, (GigConsumer*) pEntry->ID.Index); // conversion kinda hackish :/          Gigs.HandBack(pEntry->pFile, reinterpret_cast<GigConsumer*>(pEntry->ID.Index)); // conversion kinda hackish :/
608          delete pEntry;          delete pEntry;
609      }      }
610    
611      void InstrumentResourceManager::OnBorrow(::gig::Instrument* pResource, InstrumentConsumer* pConsumer, void*& pArg) {      void InstrumentResourceManager::DeleteRegionIfNotUsed(::gig::DimensionRegion* pRegion, region_info_t* pRegInfo) {
612          instr_entry_t* pEntry = (instr_entry_t*) pArg;          // TODO: we could delete Region and Instrument here if they have become unused
613          gig::EngineChannel* pEngineChannel = dynamic_cast<gig::EngineChannel*>(pConsumer);      }
614          uint maxSamplesPerCycle =  
615              (pEngineChannel->GetEngine()) ? dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()      void InstrumentResourceManager::DeleteSampleIfNotUsed(::gig::Sample* pSample, region_info_t* pRegInfo) {
616                                            : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;          ::gig::File* gig = pRegInfo->file;
617          if (pEntry->MaxSamplesPerCycle < maxSamplesPerCycle) {          ::RIFF::File* riff = static_cast< ::RIFF::File*>(pRegInfo->pArg);
618              Update(pResource, pConsumer);          if (gig) {
619                gig->DeleteSample(pSample);
620                if (!gig->GetFirstSample()) {
621                    dmsg(2,("No more samples in use - freeing gig\n"));
622                    delete gig;
623                    delete riff;
624                }
625          }          }
626      }      }
627    
628      /**      /**
629         * Just a wrapper around the other @c CacheInitialSamples() method.
630         *
631         *  @param pSample - points to the sample to be cached
632         *  @param pEngine - pointer to Gig Engine Channel which caused this call
633         *                   (may be NULL, in this case default amount of samples
634         *                   will be cached)
635         */
636        void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, EngineChannel* pEngineChannel) {
637            Engine* pEngine =
638                (pEngineChannel && pEngineChannel->GetEngine()) ?
639                    dynamic_cast<Engine*>(pEngineChannel->GetEngine()) : NULL;
640            CacheInitialSamples(pSample, pEngine);
641        }
642    
643        /**
644       *  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
645       *  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
646       *  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
647       *  samples is needed to compensate disk reading latency.       *  samples is needed to compensate disk reading latency.
648       *       *
649       *  @param pSample - points to the sample to be cached       *  @param pSample - points to the sample to be cached
650       *  @param pEngineChannel - pointer to Gig Engine Channel which caused this call       *  @param pEngine - pointer to Gig Engine which caused this call
651         *                   (may be NULL, in this case default amount of samples
652         *                   will be cached)
653       */       */
654      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, gig::EngineChannel* pEngineChannel) {      void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, AbstractEngine* pEngine) {
655            uint maxSamplesPerCycle =
656                (pEngine) ? pEngine->pAudioOutputDevice->MaxSamplesPerCycle() :
657                DefaultMaxSamplesPerCycle();
658            CacheInitialSamples(pSample, maxSamplesPerCycle);
659        }
660    
661        void InstrumentResourceManager::CacheInitialSamples(::gig::Sample* pSample, uint maxSamplesPerCycle) {
662          if (!pSample) {          if (!pSample) {
663              dmsg(4,("gig::InstrumentResourceManager: Skipping sample (pSample == NULL)\n"));              dmsg(4,("gig::InstrumentResourceManager: Skipping sample (pSample == NULL)\n"));
664              return;              return;
# Line 187  namespace LinuxSampler { namespace gig { Line 671  namespace LinuxSampler { namespace gig {
671              // number of '0' samples (silence samples) behind the official buffer              // number of '0' samples (silence samples) behind the official buffer
672              // 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
673              // the sample.              // the sample.
             const uint maxSamplesPerCycle =  
                 (pEngineChannel && pEngineChannel->GetEngine()) ? dynamic_cast<gig::Engine*>(pEngineChannel->GetEngine())->pAudioOutputDevice->MaxSamplesPerCycle()  
                                               : GIG_RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;  
674              const uint neededSilenceSamples = (maxSamplesPerCycle << CONFIG_MAX_PITCH) + 3;              const uint neededSilenceSamples = (maxSamplesPerCycle << CONFIG_MAX_PITCH) + 3;
675              const uint currentlyCachedSilenceSamples = pSample->GetCache().NullExtensionSize / pSample->FrameSize;              const uint currentlyCachedSilenceSamples = pSample->GetCache().NullExtensionSize / pSample->FrameSize;
676              if (currentlyCachedSilenceSamples < neededSilenceSamples) {              if (currentlyCachedSilenceSamples < neededSilenceSamples) {
# Line 205  namespace LinuxSampler { namespace gig { Line 686  namespace LinuxSampler { namespace gig {
686          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;
687      }      }
688    
689        void InstrumentResourceManager::UncacheInitialSamples(::gig::Sample* pSample) {
690            dmsg(1,("Uncaching sample %x\n",pSample));
691            if (pSample->GetCache().Size) pSample->ReleaseSampleData();
692        }
693    
694        /**
695         * Returns a list with all instruments currently in use, that are part of
696         * the given file.
697         *
698         * @param pFile - search criteria
699         * @param bLock - whether we should lock (mutex) the instrument manager
700         *                during this call and unlock at the end of this call
701         */
702        std::vector< ::gig::Instrument*> InstrumentResourceManager::GetInstrumentsCurrentlyUsedOf(::gig::File* pFile, bool bLock) {
703            if (bLock) Lock();
704            std::vector< ::gig::Instrument*> result;
705            std::vector< ::gig::Instrument*> allInstruments = Resources(false/*don't lock again*/);
706            for (int i = 0; i < allInstruments.size(); i++)
707                if (
708                    (::gig::File*) allInstruments[i]->GetParent()
709                    == pFile
710                ) result.push_back(allInstruments[i]);
711            if (bLock) Unlock();
712            return result;
713        }
714    
715        /**
716         * Returns a list with all gig engine channels that are currently using
717         * the given instrument.
718         *
719         * @param pInstrument - search criteria
720         * @param bLock - whether we should lock (mutex) the instrument manager
721         *                during this call and unlock at the end of this call
722         */
723        std::set<EngineChannel*> InstrumentResourceManager::GetEngineChannelsUsing(::gig::Instrument* pInstrument, bool bLock) {
724            if (bLock) Lock();
725            std::set<EngineChannel*> result;
726            std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(pInstrument);
727            std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
728            std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();
729            for (; iter != end; ++iter) {
730                EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
731                if (!pEngineChannel) continue;
732                result.insert(pEngineChannel);
733            }
734            if (bLock) Unlock();
735            return result;
736        }
737    
738        /**
739         * Returns a list with all gig Engines that are currently using the given
740         * instrument.
741         *
742         * @param pInstrument - search criteria
743         * @param bLock - whether we should lock (mutex) the instrument manager
744         *                during this call and unlock at the end of this call
745         */
746        std::set<Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::Instrument* pInstrument, bool bLock) {
747            if (bLock) Lock();
748            std::set<Engine*> result;
749            std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(pInstrument);
750            std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
751            std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();
752            for (; iter != end; ++iter) {
753                EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
754                if (!pEngineChannel) continue;
755                Engine* pEngine = dynamic_cast<Engine*>(pEngineChannel->GetEngine());
756                if (!pEngine) continue;
757                result.insert(pEngine);
758            }
759            if (bLock) Unlock();
760            return result;
761        }
762    
763        /**
764         * Returns a list with all gig Engines that are currently using an
765         * instrument that is part of the given instrument file.
766         *
767         * @param pFile - search criteria
768         * @param bLock - whether we should lock (mutex) the instrument manager
769         *                during this call and unlock at the end of this call
770         */
771        std::set<Engine*> InstrumentResourceManager::GetEnginesUsing(::gig::File* pFile, bool bLock) {
772            if (bLock) Lock();
773            // get all instruments (currently in usage) that use that same gig::File
774            std::vector< ::gig::Instrument*> instrumentsOfInterest =
775                GetInstrumentsCurrentlyUsedOf(pFile, false/*don't lock again*/);
776    
777            // get all engines that use that same gig::File
778            std::set<Engine*> result;
779            {
780                for (int i = 0; i < instrumentsOfInterest.size(); i++) {
781                    std::set<ResourceConsumer< ::gig::Instrument>*> consumers = ConsumersOf(instrumentsOfInterest[i]);
782                    std::set<ResourceConsumer< ::gig::Instrument>*>::iterator iter = consumers.begin();
783                    std::set<ResourceConsumer< ::gig::Instrument>*>::iterator end  = consumers.end();
784                    for (; iter != end; ++iter) {
785                        EngineChannel* pEngineChannel = dynamic_cast<EngineChannel*>(*iter);
786                        if (!pEngineChannel) continue;
787                        Engine* pEngine = dynamic_cast<Engine*>(pEngineChannel->GetEngine());
788                        if (!pEngine) continue;
789                        // the unique, sorted container std::set makes
790                        // sure we won't have duplicates
791                        result.insert(pEngine);
792                    }
793                }
794            }
795            if (bLock) Unlock();
796            return result;
797        }
798    
799        /**
800         * Returns @c true in case the given sample is referenced somewhere by the
801         * given instrument, @c false otherwise.
802         *
803         * @param pSample - sample reference
804         * @param pInstrument - instrument that might use that sample
805         */
806        bool InstrumentResourceManager::SampleReferencedByInstrument(::gig::Sample* pSample, ::gig::Instrument* pInstrument) {
807            for (
808                ::gig::Region* pRegion = pInstrument->GetFirstRegion();
809                pRegion; pRegion = pInstrument->GetNextRegion()
810            ) {
811                for (
812                    int i = 0; i < pRegion->DimensionRegions &&
813                    pRegion->pDimensionRegions[i]; i++
814                ) {
815                    if (pRegion->pDimensionRegions[i]->pSample == pSample)
816                        return true;
817                }
818            }
819            return false;
820        }
821    
822        /**
823         * Suspend all gig engines that use the given instrument. This means
824         * completely stopping playback on those engines and killing all their
825         * voices and disk streams. This method will block until all voices AND
826         * their disk streams are finally deleted and the engine turned into a
827         * complete idle loop.
828         *
829         * All @c SuspendEnginesUsing() methods only serve one thread by one and
830         * block all other threads until the current active thread called
831         * @c ResumeAllEngines() .
832         *
833         * @param pInstrument - search criteria
834         */
835        void InstrumentResourceManager::SuspendEnginesUsing(::gig::Instrument* pInstrument) {
836            // make sure no other thread suspends whole engines at the same time
837            suspendedEnginesMutex.Lock();
838            // get all engines that use that same gig::Instrument
839            suspendedEngines = GetEnginesUsing(pInstrument, true/*lock*/);
840            // finally, completely suspend all engines that use that same gig::Instrument
841            std::set<Engine*>::iterator iter = suspendedEngines.begin();
842            std::set<Engine*>::iterator end  = suspendedEngines.end();
843            for (; iter != end; ++iter) (*iter)->SuspendAll();
844        }
845    
846        /**
847         * Suspend all gig engines that use the given instrument file. This means
848         * completely stopping playback on those engines and killing all their
849         * voices and disk streams. This method will block until all voices AND
850         * their disk streams are finally deleted and the engine turned into a
851         * complete idle loop.
852         *
853         * All @c SuspendEnginesUsing() methods only serve one thread by one and
854         * block all other threads until the current active thread called
855         * @c ResumeAllEngines() .
856         *
857         * @param pFile - search criteria
858         */
859        void InstrumentResourceManager::SuspendEnginesUsing(::gig::File* pFile) {
860            // make sure no other thread suspends whole engines at the same time
861            suspendedEnginesMutex.Lock();
862            // get all engines that use that same gig::File
863            suspendedEngines = GetEnginesUsing(pFile, true/*lock*/);
864            // finally, completely suspend all engines that use that same gig::File
865            std::set<Engine*>::iterator iter = suspendedEngines.begin();
866            std::set<Engine*>::iterator end  = suspendedEngines.end();
867            for (; iter != end; ++iter) (*iter)->SuspendAll();
868        }
869    
870        /**
871         * MUST be called after one called one of the @c SuspendEnginesUsing()
872         * methods, to resume normal playback on all previously suspended engines.
873         * As it's only possible for one thread to suspend whole engines at the
874         * same time, this method doesn't take any arguments.
875         */
876        void InstrumentResourceManager::ResumeAllEngines() {
877            // resume all previously completely suspended engines
878            std::set<Engine*>::iterator iter = suspendedEngines.begin();
879            std::set<Engine*>::iterator end  = suspendedEngines.end();
880            for (; iter != end; ++iter) (*iter)->ResumeAll();
881            // no more suspended engines ...
882            suspendedEngines.clear();
883            // allow another thread to suspend whole engines
884            suspendedEnginesMutex.Unlock();
885        }
886    
887    
888    
889      // internal gig file manager      // internal gig file manager
# Line 219  namespace LinuxSampler { namespace gig { Line 898  namespace LinuxSampler { namespace gig {
898      }      }
899    
900      void InstrumentResourceManager::GigResourceManager::Destroy(::gig::File* pResource, void* pArg) {      void InstrumentResourceManager::GigResourceManager::Destroy(::gig::File* pResource, void* pArg) {
901          dmsg(1,("Freeing gig file from memory..."));          dmsg(1,("Freeing gig file '%s' from memory ...", pResource->GetFileName().c_str()));
902          delete pResource;  
903          delete (::RIFF::File*) pArg;          // Delete as much as possible of the gig file. Some of the
904            // dimension regions and samples may still be in use - these
905            // will be deleted later by the HandBackDimReg function.
906            bool deleteFile = true;
907            ::gig::Instrument* nextInstrument;
908            for (::gig::Instrument* instrument = pResource->GetFirstInstrument() ;
909                 instrument ;
910                 instrument = nextInstrument) {
911                nextInstrument = pResource->GetNextInstrument();
912                bool deleteInstrument = true;
913                ::gig::Region* nextRegion;
914                for (::gig::Region *region = instrument->GetFirstRegion() ;
915                     region ;
916                     region = nextRegion) {
917                    nextRegion = instrument->GetNextRegion();
918                    bool deleteRegion = true;
919                    for (int i = 0 ; i < region->DimensionRegions ; i++)
920                    {
921                        ::gig::DimensionRegion *d = region->pDimensionRegions[i];
922                        std::map< ::gig::DimensionRegion*, region_info_t>::iterator iter = parent->RegionInfo.find(d);
923                        if (iter != parent->RegionInfo.end()) {
924                            region_info_t& dimRegInfo = (*iter).second;
925                            dimRegInfo.file = pResource;
926                            dimRegInfo.pArg = (::RIFF::File*)pArg;
927                            deleteFile = deleteInstrument = deleteRegion = false;
928                        }
929                    }
930                    if (deleteRegion) instrument->DeleteRegion(region);
931                }
932                if (deleteInstrument) pResource->DeleteInstrument(instrument);
933            }
934            if (deleteFile) {
935                delete pResource;
936                delete (::RIFF::File*) pArg;
937            } else {
938                dmsg(2,("keeping some samples that are in use..."));
939                ::gig::Sample* nextSample;
940                for (::gig::Sample* sample = pResource->GetFirstSample() ;
941                     sample ;
942                     sample = nextSample) {
943                    nextSample = pResource->GetNextSample();
944                    if (parent->SampleRefCount.find(sample) == parent->SampleRefCount.end()) {
945                        pResource->DeleteSample(sample);
946                    }
947                }
948            }
949          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
950      }      }
951    

Legend:
Removed from v.970  
changed lines
  Added in v.2327

  ViewVC Help
Powered by ViewVC