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

Legend:
Removed from v.420  
changed lines
  Added in v.3719

  ViewVC Help
Powered by ViewVC