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

Legend:
Removed from v.56  
changed lines
  Added in v.1659

  ViewVC Help
Powered by ViewVC