/[svn]/linuxsampler/trunk/src/engines/InstrumentManagerBase.h
ViewVC logotype

Annotation of /linuxsampler/trunk/src/engines/InstrumentManagerBase.h

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2434 - (hide annotations) (download) (as text)
Thu Mar 7 19:23:24 2013 UTC (11 years, 1 month ago) by schoenebeck
File MIME type: text/x-c++hdr
File size: 13537 byte(s)
* Started to spread new C++ keyword "override" over the code base
  (keyword introduced with C++11 standard).

1 iliev 2012 /***************************************************************************
2     * *
3     * LinuxSampler - modular, streaming capable sampler *
4     * *
5     * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck *
6 persson 2326 * Copyright (C) 2005 - 2008 Christian Schoenebeck *
7 persson 2427 * Copyright (C) 2009 - 2013 Christian Schoenebeck and Grigor Iliev *
8 iliev 2012 * *
9     * This library is free software; you can redistribute it and/or modify *
10     * it under the terms of the GNU General Public License as published by *
11     * the Free Software Foundation; either version 2 of the License, or *
12     * (at your option) any later version. *
13     * *
14     * This library is distributed in the hope that it will be useful, *
15     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
16     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
17     * GNU General Public License for more details. *
18     * *
19     * You should have received a copy of the GNU General Public License *
20     * along with this library; if not, write to the Free Software *
21     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
22     * MA 02111-1307 USA *
23     ***************************************************************************/
24    
25     #ifndef __LS_INSTRUMENTMANAGERBASE_H__
26     #define __LS_INSTRUMENTMANAGERBASE_H__
27    
28     #include "InstrumentManager.h"
29     #include "AbstractEngine.h"
30     #include "AbstractEngineChannel.h"
31     #include "../common/ResourceManager.h"
32     #include "../common/global_private.h"
33 schoenebeck 2275 #include "../drivers/audio/AudioOutputDeviceFactory.h"
34 iliev 2012
35     // We need to know the maximum number of sample points which are going to
36     // be processed for each render cycle of the audio output driver, to know
37     // how much initial sample points we need to cache into RAM. If the given
38     // sampler channel does not have an audio output device assigned yet
39     // though, we simply use this default value.
40 persson 2326 #define RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE 128
41 iliev 2012
42     namespace LinuxSampler {
43    
44     template <class F /* Instrument File */, class I /* Instrument */, class R /* Regions */, class S /*Sample */>
45 persson 2326 class InstrumentManagerBase : public InstrumentManager, public ResourceManager<InstrumentManager::instrument_id_t, I> {
46 iliev 2012 public:
47     struct region_info_t {
48     int refCount;
49     F* file;
50     void* pArg;
51    
52     region_info_t() {
53     refCount = 0; file = NULL; pArg = NULL;
54     }
55     };
56    
57     typedef ResourceConsumer<I> InstrumentConsumer;
58    
59     InstrumentManagerBase() { }
60     virtual ~InstrumentManagerBase() { }
61    
62 schoenebeck 2434 virtual InstrumentEditor* LaunchInstrumentEditor(instrument_id_t ID, void* pUserData = NULL) throw (InstrumentManagerException) OVERRIDE {
63 iliev 2012 throw InstrumentManagerException(
64     "Instrument editing is not supported for this instrument format"
65     );
66     }
67    
68 schoenebeck 2434 virtual String GetInstrumentDataStructureName(instrument_id_t ID) OVERRIDE {
69 iliev 2012 throw InstrumentManagerException("Not implemented");
70     }
71    
72 schoenebeck 2434 virtual String GetInstrumentDataStructureVersion(instrument_id_t ID) OVERRIDE {
73 iliev 2012 throw InstrumentManagerException("Not implemented");
74     }
75    
76     /**
77     * Give back an instrument. This should be used instead of
78     * HandBack if there are some regions that are still in
79     * use. (When an instrument is changed, the voices currently
80     * playing are allowed to keep playing with the old instrument
81     * until note off arrives. New notes will use the new instrument.)
82     */
83     void HandBackInstrument (
84     I* pResource,
85     InstrumentConsumer* pConsumer,
86     RTList<R*>* pRegionsInUse
87     ) {
88 persson 2427 LockGuard lock(RegionInfoMutex);
89 iliev 2012 for (typename RTList<R*>::Iterator i = pRegionsInUse->first() ; i != pRegionsInUse->end() ; i++) {
90     RegionInfo[*i].refCount++;
91     SampleRefCount[(*i)->pSample]++;
92     }
93 persson 2335 this->HandBack(pResource, pConsumer, true);
94 iliev 2012 }
95    
96     /**
97     * Give back a region that belongs to an instrument that
98     * was previously handed back.
99     */
100 schoenebeck 2434 virtual void HandBackRegion(R* pRegion) OVERRIDE {
101 persson 2427 LockGuard lock(RegionInfoMutex);
102 iliev 2012 if (RegionInfo.find(pRegion) == RegionInfo.end()) {
103     std::cerr << "Handing back unknown region. This is a BUG!!!" << std::endl;
104     }
105     region_info_t& regInfo = RegionInfo[pRegion];
106     int regionRefCount = --regInfo.refCount;
107     int sampleRefCount = --SampleRefCount[pRegion->pSample];
108     if (regionRefCount == 0) {
109 persson 2058 S* pSample = pRegion->pSample;
110    
111 iliev 2012 DeleteRegionIfNotUsed(pRegion, &regInfo);
112    
113     if (sampleRefCount == 0) {
114 persson 2058 SampleRefCount.erase(pSample);
115     DeleteSampleIfNotUsed(pSample, &regInfo);
116 iliev 2012 }
117 persson 2058 RegionInfo.erase(pRegion);
118 iliev 2012 }
119     }
120    
121 schoenebeck 2434 virtual InstrumentManager::mode_t GetMode(const InstrumentManager::instrument_id_t& ID) OVERRIDE {
122 iliev 2012 return static_cast<InstrumentManager::mode_t>(ResourceManager<instrument_id_t, I>::AvailabilityMode(ID));
123     }
124    
125 schoenebeck 2434 virtual void SetMode(const InstrumentManager::instrument_id_t& ID, InstrumentManager::mode_t Mode) OVERRIDE {
126 iliev 2012 dmsg(2,("InstrumentManagerBase: setting mode for %s (Index=%d) to %d\n",ID.FileName.c_str(),ID.Index,Mode));
127 persson 2335 this->SetAvailabilityMode(ID, static_cast<typename ResourceManager<instrument_id_t, I>::mode_t>(Mode));
128 iliev 2012 }
129 persson 2326
130     protected:
131     // data stored as long as an instrument resource exists
132     struct instr_entry_t {
133     InstrumentManager::instrument_id_t ID;
134     F* pFile;
135     uint MaxSamplesPerCycle; ///< if some engine requests an already allocated instrument with a higher value, we have to reallocate the instrument
136     };
137    
138    
139 schoenebeck 2275 /**
140     * Used by the implementing instrument manager descendents in case
141     * they don't have a reference to a sampler channel, which in turn
142     * provides a reference to an audio device which would actually
143     * define the maximum amount of sample points per audio render
144     * cycle. So in those missing cases (e.g. when MIDI instrument maps
145     * are created), this method will iterate through all already
146     * existing audio devices and return the biggest max. samples per
147     * cycle value of those audio devices.
148     *
149     * In case no audio device is currently created, this method will
150     * return a hard coded constant default value.
151     *
152     * Background: We need to know the maximum number of sample points
153     * which are going to be processed for each render cycle of the
154     * audio output driver, to know how many initial sample points we
155     * need to cache into RAM by the implementing instrument manager.
156     */
157     virtual uint DefaultMaxSamplesPerCycle() {
158     uint samples = 0;
159     std::map<uint, AudioOutputDevice*> devices = AudioOutputDeviceFactory::Devices();
160     for (std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin(); iter != devices.end(); ++iter) {
161     AudioOutputDevice* pDevice = iter->second;
162     if (pDevice->MaxSamplesPerCycle() > samples)
163     samples = pDevice->MaxSamplesPerCycle();
164     }
165 persson 2326 return (samples != 0) ? samples : RESOURCE_MANAGER_DEFAULT_MAX_SAMPLES_PER_CYCLE;
166 schoenebeck 2275 }
167 iliev 2012
168 persson 2326 uint GetMaxSamplesPerCycle(InstrumentConsumer* pConsumer) {
169     // try to resolve the audio device context
170     AbstractEngineChannel* pEngineChannel = dynamic_cast<AbstractEngineChannel*>(pConsumer);
171     AudioOutputDevice* pDevice = pEngineChannel ? pEngineChannel->GetAudioOutputDeviceSafe() : 0;
172     return pDevice ? pDevice->MaxSamplesPerCycle() : DefaultMaxSamplesPerCycle();
173     }
174    
175 iliev 2012 Mutex RegionInfoMutex; ///< protects the RegionInfo and SampleRefCount maps from concurrent access by the instrument loader and disk threads
176     std::map< R*, region_info_t> RegionInfo; ///< contains dimension regions that are still in use but belong to released instrument
177     std::map< S*, int> SampleRefCount; ///< contains samples that are still in use but belong to a released instrument
178    
179     virtual void DeleteRegionIfNotUsed(R* pRegion, region_info_t* pRegInfo) = 0;
180     virtual void DeleteSampleIfNotUsed(S* pSample, region_info_t* pRegInfo) = 0;
181    
182 iliev 2027 void SetKeyBindings(uint8_t* bindingsArray, int low, int high, int undefined = -1) {
183     if (low == undefined || high == undefined) return;
184     if (low < 0 || low > 127 || high < 0 || high > 127 || low > high) {
185     std::cerr << "Invalid key range: " << low << " - " << high << std::endl;
186     return;
187     }
188    
189     for (int i = low; i <= high; i++) bindingsArray[i] = 1;
190     }
191    
192 persson 2326 /**
193     * Caches a certain size at the beginning of the given sample in RAM. If the
194     * sample is very short, the whole sample will be loaded into RAM and thus
195     * no disk streaming is needed for this sample. Caching an initial part of
196     * samples is needed to compensate disk reading latency.
197     *
198     * @param pSample - points to the sample to be cached
199     * @param maxSamplesPerCycle - max samples per cycle
200     */
201     void CacheInitialSamples(S* pSample, uint maxSamplesPerCycle) {
202 iliev 2012 if (!pSample) {
203     dmsg(4,("InstrumentManagerBase: Skipping sample (pSample == NULL)\n"));
204     return;
205     }
206     if (!pSample->GetTotalFrameCount()) return; // skip zero size samples
207    
208     if (pSample->GetTotalFrameCount() <= CONFIG_PRELOAD_SAMPLES) {
209     // Sample is too short for disk streaming, so we load the whole
210     // sample into RAM and place 'pAudioIO->FragmentSize << CONFIG_MAX_PITCH'
211     // number of '0' samples (silence samples) behind the official buffer
212     // border, to allow the interpolator do it's work even at the end of
213     // the sample.
214     const uint neededSilenceSamples = (maxSamplesPerCycle << CONFIG_MAX_PITCH) + 3;
215     const uint currentlyCachedSilenceSamples = pSample->GetCache().NullExtensionSize / pSample->GetFrameSize();
216     if (currentlyCachedSilenceSamples < neededSilenceSamples) {
217     dmsg(3,("Caching whole sample (sample name: \"%s\", sample size: %d)\n", pSample->GetName().c_str(), pSample->GetTotalFrameCount()));
218     typename S::buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(neededSilenceSamples);
219     dmsg(4,("Cached %d Bytes, %d silence bytes.\n", buf.Size, buf.NullExtensionSize));
220     }
221     }
222     else { // we only cache CONFIG_PRELOAD_SAMPLES and stream the other sample points from disk
223     if (!pSample->GetCache().Size) pSample->LoadSampleData(CONFIG_PRELOAD_SAMPLES);
224     }
225    
226     if (!pSample->GetCache().Size) std::cerr << "Unable to cache sample - maybe memory full!" << std::endl << std::flush;
227     }
228    
229 persson 2326 // implementation of derived abstract methods from 'InstrumentManager'
230     std::vector<instrument_id_t> Instruments() {
231     return ResourceManager<InstrumentManager::instrument_id_t, I>::Entries();
232 iliev 2012 }
233 persson 2326
234     // implementation of derived abstract methods from 'ResourceManager'
235     void OnBorrow(I* pResource, InstrumentConsumer* pConsumer, void*& pArg) {
236     instr_entry_t* pEntry = static_cast<instr_entry_t*>(pArg);
237    
238     uint maxSamplesPerCycle = GetMaxSamplesPerCycle(pConsumer);
239    
240     if (pEntry->MaxSamplesPerCycle < maxSamplesPerCycle) {
241     dmsg(1,("Completely reloading instrument due to insufficient precached samples ...\n"));
242 persson 2335 this->Update(pResource, pConsumer);
243 persson 2326 }
244     }
245 iliev 2012 };
246    
247     } // namespace LinuxSampler
248    
249 persson 2045 #endif // __LS_INSTRUMENTMANAGERBASE_H__

  ViewVC Help
Powered by ViewVC