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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2594 - (hide annotations) (download) (as text)
Thu Jun 5 00:16:25 2014 UTC (9 years, 9 months ago) by schoenebeck
File MIME type: text/x-c++hdr
File size: 87100 byte(s)
* ScriptVM (WIP): started to integrate real-time instrument script
  support into the sampler engine implementations. The code is
  shared among all sampler engines, however currently only the gig
  file format supports storing instrument scripts (as LinuxSampler
  extension to the original GigaStudio 4 file format).
* gig engine: Added support for loading instrument scripts from .gig
  files.
* ScriptVM (WIP): Implemented built-in script variables %CC, $CC_NUM,
  $EVENT_NOTE, $EVENT_VELOCITY, $VCC_MONO_AT, $VCC_PITCH_BEND.
* ScriptVM (WIP): Implemented execution of script event handler "init".
* ScriptVM (WIP): Implemented execution of script event handler
  "controller".
* Bumped version (1.0.0.svn42).

1 iliev 2012 /***************************************************************************
2     * *
3     * LinuxSampler - modular, streaming capable sampler *
4     * *
5     * Copyright (C) 2003,2004 by Benno Senoner and Christian Schoenebeck *
6 persson 2055 * Copyright (C) 2005-2008 Christian Schoenebeck *
7 persson 2427 * Copyright (C) 2009-2013 Christian Schoenebeck and Grigor Iliev *
8 iliev 2012 * *
9     * 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 *
11     * the Free Software Foundation; either version 2 of the License, or *
12     * (at your option) any later version. *
13     * *
14     * This program 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 program; 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_ENGINEBASE_H__
26     #define __LS_ENGINEBASE_H__
27    
28     #include "AbstractEngine.h"
29     #include "EngineChannelBase.h"
30     #include "common/DiskThreadBase.h"
31     #include "common/MidiKeyboardManager.h"
32     #include "InstrumentManager.h"
33     #include "../common/global_private.h"
34    
35    
36     namespace LinuxSampler {
37    
38     class AbstractEngineChannel;
39    
40     template <
41     class V /* Voice */,
42     class RR /* Root Region */,
43     class R /* Region */,
44     class D /* Disk Thread */,
45     class IM /* Instrument Manager */,
46     class I /* Instrument */
47     >
48     class EngineBase: public AbstractEngine, public RegionPools<R>, public VoicePool<V> {
49    
50     public:
51     typedef typename RTList<V>::Iterator VoiceIterator;
52     typedef typename Pool<V>::Iterator PoolVoiceIterator;
53     typedef typename RTList<RR*>::Iterator RootRegionIterator;
54     typedef typename MidiKeyboardManager<V>::MidiKey MidiKey;
55    
56     EngineBase() : SuspendedRegions(128) {
57     pDiskThread = NULL;
58     pVoicePool = new Pool<V>(GLOBAL_MAX_VOICES);
59     pRegionPool[0] = new Pool<R*>(GLOBAL_MAX_VOICES);
60     pRegionPool[1] = new Pool<R*>(GLOBAL_MAX_VOICES);
61     pVoiceStealingQueue = new RTList<Event>(pEventPool);
62     iMaxDiskStreams = GLOBAL_MAX_STREAMS;
63    
64     for (VoiceIterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
65     iterVoice->SetEngine(this);
66     }
67     pVoicePool->clear();
68    
69     ResetInternal();
70     ResetScaleTuning();
71     ResetSuspendedRegions();
72     }
73    
74     virtual ~EngineBase() {
75     if (pDiskThread) {
76     dmsg(1,("Stopping disk thread..."));
77     pDiskThread->StopThread();
78     delete pDiskThread;
79     dmsg(1,("OK\n"));
80     }
81    
82     if (pVoicePool) {
83     pVoicePool->clear();
84     delete pVoicePool;
85     }
86    
87     if (pVoiceStealingQueue) delete pVoiceStealingQueue;
88    
89     if (pRegionPool[0]) delete pRegionPool[0];
90     if (pRegionPool[1]) delete pRegionPool[1];
91     ResetSuspendedRegions();
92     }
93    
94     // implementation of abstract methods derived from class 'LinuxSampler::Engine'
95    
96     /**
97     * Let this engine proceed to render the given amount of sample points.
98     * The engine will iterate through all engine channels and render audio
99     * for each engine channel independently. The calculated audio data of
100     * all voices of each engine channel will be placed into the audio sum
101     * buffers of the respective audio output device, connected to the
102     * respective engine channel.
103     *
104     * @param Samples - number of sample points to be rendered
105     * @returns 0 on success
106     */
107 schoenebeck 2434 virtual int RenderAudio(uint Samples) OVERRIDE {
108 iliev 2012 dmsg(8,("RenderAudio(Samples=%d)\n", Samples));
109    
110     // return if engine disabled
111     if (EngineDisabled.Pop()) {
112     dmsg(5,("EngineBase: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));
113     EngineDisabled.RttDone();
114     return 0;
115     }
116    
117     // process requests for suspending / resuming regions (i.e. to avoid
118     // crashes while these regions are modified by an instrument editor)
119     ProcessSuspensionsChanges();
120    
121     // update time of start and end of this audio fragment (as events' time stamps relate to this)
122     pEventGenerator->UpdateFragmentTime(Samples);
123    
124     // We only allow the given maximum number of voices to be spawned
125     // in each audio fragment. All subsequent request for spawning new
126     // voices in the same audio fragment will be ignored.
127     VoiceSpawnsLeft = MaxVoices();
128    
129     // get all events from the engine's global input event queue which belong to the current fragment
130     // (these are usually just SysEx messages)
131     ImportEvents(Samples);
132    
133     // process engine global events (these are currently only MIDI System Exclusive messages)
134     {
135     RTList<Event>::Iterator itEvent = pGlobalEvents->first();
136     RTList<Event>::Iterator end = pGlobalEvents->end();
137     for (; itEvent != end; ++itEvent) {
138     switch (itEvent->Type) {
139     case Event::type_sysex:
140     dmsg(5,("Engine: Sysex received\n"));
141     ProcessSysex(itEvent);
142     break;
143     }
144     }
145     }
146 schoenebeck 2448
147     // In case scale tuning has been changed, recalculate pitch for
148     // all active voices.
149     ProcessScaleTuningChange();
150 iliev 2012
151     // reset internal voice counter (just for statistic of active voices)
152     ActiveVoiceCountTemp = 0;
153    
154     HandleInstrumentChanges();
155    
156     // handle events on all engine channels
157     for (int i = 0; i < engineChannels.size(); i++) {
158     ProcessEvents(engineChannels[i], Samples);
159     }
160    
161     // render all 'normal', active voices on all engine channels
162     for (int i = 0; i < engineChannels.size(); i++) {
163     RenderActiveVoices(engineChannels[i], Samples);
164     }
165    
166     // now that all ordinary voices on ALL engine channels are rendered, render new stolen voices
167     RenderStolenVoices(Samples);
168    
169     // handle audio routing for engine channels with FX sends
170     for (int i = 0; i < engineChannels.size(); i++) {
171     AbstractEngineChannel* pChannel = static_cast<AbstractEngineChannel*>(engineChannels[i]);
172     if (pChannel->fxSends.empty()) continue; // ignore if no FX sends
173     RouteAudio(engineChannels[i], Samples);
174     }
175    
176     // handle cleanup on all engine channels for the next audio fragment
177     for (int i = 0; i < engineChannels.size(); i++) {
178     PostProcess(engineChannels[i]);
179     }
180    
181    
182     // empty the engine's event list for the next audio fragment
183     ClearEventLists();
184    
185     // reset voice stealing for the next audio fragment
186     pVoiceStealingQueue->clear();
187    
188     // just some statistics about this engine instance
189     SetVoiceCount(ActiveVoiceCountTemp);
190     if (VoiceCount() > ActiveVoiceCountMax) ActiveVoiceCountMax = VoiceCount();
191    
192     // in case regions were previously suspended and we killed voices
193     // with disk streams due to that, check if those streams have finally
194     // been deleted by the disk thread
195     if (iPendingStreamDeletions) ProcessPendingStreamDeletions();
196    
197 persson 2162 // Release the instrument change command. (This has to
198     // be done after all voices have been rendered and not
199     // in HandleInstrumentChanges, as the RegionsInUse
200     // list has been built up by the voice renderers.)
201     for (int i = 0; i < engineChannels.size(); i++) {
202     EngineChannelBase<V, R, I>* channel =
203     static_cast<EngineChannelBase<V, R, I>*>(engineChannels[i]);
204     channel->InstrumentChangeCommandReader.Unlock();
205     }
206 iliev 2012 FrameTime += Samples;
207    
208     EngineDisabled.RttDone();
209     return 0;
210     }
211    
212 schoenebeck 2434 virtual int MaxVoices() OVERRIDE { return pVoicePool->poolSize(); }
213 iliev 2012
214 schoenebeck 2434 virtual void SetMaxVoices(int iVoices) throw (Exception) OVERRIDE {
215 iliev 2012 if (iVoices < 1)
216     throw Exception("Maximum voices for an engine cannot be set lower than 1");
217    
218     SuspendAll();
219    
220     // NOTE: we need to clear pRegionsInUse before deleting pDimRegionPool,
221     // otherwise memory corruption will occur if there are active voices (see bug #118)
222     for (int iChannel = 0; iChannel < engineChannels.size(); iChannel++) {
223     EngineChannelBase<V, R, I>* pChannel = static_cast<EngineChannelBase<V, R, I>*>(engineChannels[iChannel]);
224     pChannel->ClearRegionsInUse();
225     }
226    
227     if (pRegionPool[0]) delete pRegionPool[0];
228     if (pRegionPool[1]) delete pRegionPool[1];
229    
230     pRegionPool[0] = new Pool<R*>(iVoices);
231     pRegionPool[1] = new Pool<R*>(iVoices);
232    
233     for (int iChannel = 0; iChannel < engineChannels.size(); iChannel++) {
234     EngineChannelBase<V, R, I>* pChannel = static_cast<EngineChannelBase<V, R, I>*>(engineChannels[iChannel]);
235     pChannel->ResetRegionsInUse(pRegionPool);
236     }
237    
238     try {
239     pVoicePool->resizePool(iVoices);
240     } catch (...) {
241     throw Exception("FATAL: Could not resize voice pool!");
242     }
243    
244     for (VoiceIterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
245     iterVoice->SetEngine(this);
246     iterVoice->pDiskThread = this->pDiskThread;
247     }
248     pVoicePool->clear();
249    
250 iliev 2244 PostSetMaxVoices(iVoices);
251 iliev 2012 ResumeAll();
252     }
253 iliev 2244
254     /** Called after the new max number of voices is set and before resuming the engine. */
255     virtual void PostSetMaxVoices(int iVoices) { }
256 iliev 2012
257 schoenebeck 2434 virtual uint DiskStreamCount() OVERRIDE { return (pDiskThread) ? pDiskThread->GetActiveStreamCount() : 0; }
258     virtual uint DiskStreamCountMax() OVERRIDE { return (pDiskThread) ? pDiskThread->ActiveStreamCountMax : 0; }
259     virtual int MaxDiskStreams() OVERRIDE { return iMaxDiskStreams; }
260 iliev 2012
261 schoenebeck 2434 virtual void SetMaxDiskStreams(int iStreams) throw (Exception) OVERRIDE {
262 iliev 2012 if (iStreams < 0)
263     throw Exception("Maximum disk streams for an engine cannot be set lower than 0");
264    
265     SuspendAll();
266    
267     iMaxDiskStreams = iStreams;
268    
269     // reconnect to audio output device, because that will automatically
270     // recreate the disk thread with the required amount of streams
271     if (pAudioOutputDevice) Connect(pAudioOutputDevice);
272    
273     ResumeAll();
274     }
275    
276 schoenebeck 2434 virtual String DiskStreamBufferFillBytes() OVERRIDE { return (pDiskThread) ? pDiskThread->GetBufferFillBytes() : ""; }
277     virtual String DiskStreamBufferFillPercentage() OVERRIDE { return (pDiskThread) ? pDiskThread->GetBufferFillPercentage() : ""; }
278     virtual InstrumentManager* GetInstrumentManager() OVERRIDE { return &instruments; }
279 iliev 2012
280     /**
281     * Connect this engine instance with the given audio output device.
282     * This method will be called when an Engine instance is created.
283     * All of the engine's data structures which are dependant to the used
284     * audio output device / driver will be (re)allocated and / or
285     * adjusted appropriately.
286     *
287     * @param pAudioOut - audio output device to connect to
288     */
289 schoenebeck 2434 virtual void Connect(AudioOutputDevice* pAudioOut) OVERRIDE {
290 iliev 2012 // caution: don't ignore if connecting to the same device here,
291     // because otherwise SetMaxDiskStreams() implementation won't work anymore!
292    
293     pAudioOutputDevice = pAudioOut;
294    
295     ResetInternal();
296    
297     // inform audio driver for the need of two channels
298     try {
299     pAudioOutputDevice->AcquireChannels(2); // default stereo
300     }
301     catch (AudioOutputException e) {
302     String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();
303     throw Exception(msg);
304     }
305    
306     this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle();
307     this->SampleRate = pAudioOutputDevice->SampleRate();
308    
309     MinFadeOutSamples = int(double(SampleRate) * CONFIG_EG_MIN_RELEASE_TIME) - 1;
310     if (MaxSamplesPerCycle < MinFadeOutSamples) {
311     std::cerr << "EngineBase: WARNING, CONFIG_EG_MIN_RELEASE_TIME "
312     << "too big for current audio fragment size & sampling rate! "
313     << "May lead to click sounds if voice stealing chimes in!\n" << std::flush;
314     // force volume ramp downs at the beginning of each fragment
315     MinFadeOutSamples = MaxSamplesPerCycle;
316     // lower minimum release time
317     const float minReleaseTime = (float) MaxSamplesPerCycle / (float) SampleRate;
318     for (VoiceIterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
319 persson 2327 iterVoice->CalculateFadeOutCoeff(minReleaseTime, SampleRate);
320 iliev 2012 }
321     pVoicePool->clear();
322     }
323    
324     // (re)create disk thread
325     if (this->pDiskThread) {
326     dmsg(1,("Stopping disk thread..."));
327     this->pDiskThread->StopThread();
328     delete this->pDiskThread;
329     dmsg(1,("OK\n"));
330     }
331     this->pDiskThread = CreateDiskThread();
332    
333     if (!pDiskThread) {
334     dmsg(0,("EngineBase new diskthread = NULL\n"));
335     exit(EXIT_FAILURE);
336     }
337    
338     for (VoiceIterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
339     iterVoice->pDiskThread = this->pDiskThread;
340     dmsg(3,("d"));
341     }
342     pVoicePool->clear();
343    
344     // (re)create event generator
345     if (pEventGenerator) delete pEventGenerator;
346     pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
347    
348     dmsg(1,("Starting disk thread..."));
349     pDiskThread->StartThread();
350     dmsg(1,("OK\n"));
351    
352 iliev 2298 bool printEqInfo = true;
353 iliev 2012 for (VoiceIterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
354     if (!iterVoice->pDiskThread) {
355     dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));
356     exit(EXIT_FAILURE);
357     }
358 iliev 2298
359     iterVoice->CreateEq();
360    
361     if(printEqInfo) {
362     iterVoice->PrintEqInfo();
363     printEqInfo = false;
364     }
365 iliev 2012 }
366     pVoicePool->clear();
367 schoenebeck 2121
368     // (re)create dedicated voice audio buffers
369     //TODO: we could optimize resource usage a bit by just allocating these dedicated voice buffers when there is at least one engine channel with FX sends, because only in this case those special buffers are used actually, but since it would usually only save couple bytes in total, its probably not worth it
370     if (pDedicatedVoiceChannelLeft) delete pDedicatedVoiceChannelLeft;
371     if (pDedicatedVoiceChannelRight) delete pDedicatedVoiceChannelRight;
372     pDedicatedVoiceChannelLeft = new AudioChannel(0, MaxSamplesPerCycle);
373     pDedicatedVoiceChannelRight = new AudioChannel(1, MaxSamplesPerCycle);
374 iliev 2012 }
375 schoenebeck 2410
376     // Implementattion for abstract method derived from Engine.
377 schoenebeck 2434 virtual void ReconnectAudioOutputDevice() OVERRIDE {
378 schoenebeck 2410 SuspendAll();
379     if (pAudioOutputDevice) Connect(pAudioOutputDevice);
380     ResumeAll();
381     }
382 iliev 2012
383     /**
384     * Similar to @c Disable() but this method additionally kills all voices
385     * and disk streams and blocks until all voices and disk streams are actually
386     * killed / deleted.
387     *
388     * @e Note: only the original calling thread is able to re-enable the
389     * engine afterwards by calling @c ResumeAll() later on!
390     */
391     virtual void SuspendAll() {
392     dmsg(2,("Engine: Suspending all ...\n"));
393     // stop the engine, so we can safely modify the engine's
394     // data structures from this foreign thread
395     DisableAndLock();
396     // we could also use the respective class member variable here,
397     // but this is probably safer and cleaner
398     int iPendingStreamDeletions = 0;
399     // kill all voices on all engine channels the *die hard* way
400     for (int iChannel = 0; iChannel < engineChannels.size(); iChannel++) {
401     EngineChannelBase<V, R, I>* pEngineChannel =
402     static_cast<EngineChannelBase<V, R, I>*>(engineChannels[iChannel]);
403    
404     iPendingStreamDeletions += pEngineChannel->KillAllVoicesImmediately();
405     }
406     // wait until all streams were actually deleted by the disk thread
407     while (iPendingStreamDeletions) {
408     while (
409     iPendingStreamDeletions &&
410     pDiskThread->AskForDeletedStream() != Stream::INVALID_HANDLE
411     ) iPendingStreamDeletions--;
412     if (!iPendingStreamDeletions) break;
413     usleep(10000); // sleep for 10ms
414     }
415     dmsg(2,("EngineBase: Everything suspended.\n"));
416     }
417    
418     /**
419     * At the moment same as calling @c Enable() directly, but this might
420     * change in future, so better call this method as counterpart to
421     * @c SuspendAll() instead of @c Enable() !
422     */
423     virtual void ResumeAll() { Enable(); }
424    
425     /**
426     * Order the engine to stop rendering audio for the given region.
427     * Additionally this method will block until all voices and their disk
428     * streams associated with that region are actually killed / deleted, so
429     * one can i.e. safely modify the region with an instrument editor after
430     * returning from this method.
431     *
432     * @param pRegion - region the engine shall stop using
433     */
434     virtual void Suspend(RR* pRegion) {
435     dmsg(2,("EngineBase: Suspending Region %x ...\n",pRegion));
436 persson 2427 {
437     LockGuard lock(SuspendedRegionsMutex);
438     SuspensionChangeOngoing.Set(true);
439     pPendingRegionSuspension = pRegion;
440     SuspensionChangeOngoing.WaitAndUnlockIf(true);
441     }
442 iliev 2012 dmsg(2,("EngineBase: Region %x suspended.",pRegion));
443     }
444    
445     /**
446     * Orders the engine to resume playing back the given region, previously
447     * suspended with @c Suspend() .
448     *
449     * @param pRegion - region the engine shall be allowed to use again
450     */
451     virtual void Resume(RR* pRegion) {
452     dmsg(2,("EngineBase: Resuming Region %x ...\n",pRegion));
453 persson 2427 {
454     LockGuard lock(SuspendedRegionsMutex);
455     SuspensionChangeOngoing.Set(true);
456     pPendingRegionResumption = pRegion;
457     SuspensionChangeOngoing.WaitAndUnlockIf(true);
458     }
459 iliev 2012 dmsg(2,("EngineBase: Region %x resumed.\n",pRegion));
460     }
461    
462     virtual void ResetSuspendedRegions() {
463     SuspendedRegions.clear();
464     iPendingStreamDeletions = 0;
465     pPendingRegionSuspension = pPendingRegionResumption = NULL;
466     SuspensionChangeOngoing.Set(false);
467     }
468    
469     /**
470     * Called by the engine's (audio) thread once per cycle to process requests
471     * from the outer world to suspend or resume a given @c gig::Region .
472     */
473     virtual void ProcessSuspensionsChanges() {
474     // process request for suspending one region
475     if (pPendingRegionSuspension) {
476     // kill all voices on all engine channels that use this region
477     for (int iChannel = 0; iChannel < engineChannels.size(); iChannel++) {
478     EngineChannelBase<V, R, I>* pEngineChannel =
479     static_cast<EngineChannelBase<V, R, I>*>(engineChannels[iChannel]);
480     SuspensionVoiceHandler handler(pPendingRegionSuspension);
481     pEngineChannel->ProcessActiveVoices(&handler);
482     iPendingStreamDeletions += handler.PendingStreamDeletions;
483     }
484     // make sure the region is not yet on the list
485     bool bAlreadySuspended = false;
486     RootRegionIterator iter = SuspendedRegions.first();
487     RootRegionIterator end = SuspendedRegions.end();
488     for (; iter != end; ++iter) { // iterate through all suspended regions
489     if (*iter == pPendingRegionSuspension) { // found
490     bAlreadySuspended = true;
491     dmsg(1,("EngineBase: attempt to suspend an already suspended region !!!\n"));
492     break;
493     }
494     }
495     if (!bAlreadySuspended) {
496     // put the region on the list of suspended regions
497     RootRegionIterator iter = SuspendedRegions.allocAppend();
498     if (iter) {
499     *iter = pPendingRegionSuspension;
500     } else std::cerr << "EngineBase: Could not suspend Region, list is full. This is a bug!!!\n" << std::flush;
501     }
502     // free request slot for next caller (and to make sure that
503     // we're not going to process the same request in the next cycle)
504     pPendingRegionSuspension = NULL;
505     // if no disk stream deletions are pending, awaken other side, as
506     // we're done in this case
507     if (!iPendingStreamDeletions) SuspensionChangeOngoing.Set(false);
508     }
509    
510     // process request for resuming one region
511     if (pPendingRegionResumption) {
512     // remove region from the list of suspended regions
513     RootRegionIterator iter = SuspendedRegions.first();
514     RootRegionIterator end = SuspendedRegions.end();
515     for (; iter != end; ++iter) { // iterate through all suspended regions
516     if (*iter == pPendingRegionResumption) { // found
517     SuspendedRegions.free(iter);
518     break; // done
519     }
520     }
521     // free request slot for next caller
522     pPendingRegionResumption = NULL;
523     // awake other side as we're done
524     SuspensionChangeOngoing.Set(false);
525     }
526     }
527    
528     /**
529     * Called by the engine's (audio) thread once per cycle to check if
530     * streams of voices that were killed due to suspension request have
531     * finally really been deleted by the disk thread.
532     */
533     virtual void ProcessPendingStreamDeletions() {
534     if (!iPendingStreamDeletions) return;
535     //TODO: or shall we better store a list with stream handles instead of a scalar amount of streams to be deleted? might be safer
536     while (
537     iPendingStreamDeletions &&
538     pDiskThread->AskForDeletedStream() != Stream::INVALID_HANDLE
539     ) iPendingStreamDeletions--;
540     // just for safety ...
541     while (pDiskThread->AskForDeletedStream() != Stream::INVALID_HANDLE);
542     // now that all disk streams are deleted, awake other side as
543     // we're finally done with suspending the requested region
544     if (!iPendingStreamDeletions) SuspensionChangeOngoing.Set(false);
545     }
546    
547     /**
548     * Returns @c true if the given region is currently set to be suspended
549     * from being used, @c false otherwise.
550     */
551     virtual bool RegionSuspended(RR* pRegion) {
552     if (SuspendedRegions.isEmpty()) return false;
553     //TODO: or shall we use a sorted container instead of the RTList? might be faster ... or trivial ;-)
554     RootRegionIterator iter = SuspendedRegions.first();
555     RootRegionIterator end = SuspendedRegions.end();
556     for (; iter != end; ++iter) // iterate through all suspended regions
557     if (*iter == pRegion) return true;
558     return false;
559     }
560    
561     // implementation of abstract method derived from class 'LinuxSampler::RegionPools'
562     virtual Pool<R*>* GetRegionPool(int index) {
563     if (index < 0 || index > 1) throw Exception("Index out of bounds");
564     return pRegionPool[index];
565     }
566    
567     // implementation of abstract method derived from class 'LinuxSampler::VoicePool'
568     virtual Pool<V>* GetVoicePool() { return pVoicePool; }
569    
570     D* GetDiskThread() { return pDiskThread; }
571    
572     //friend class EngineChannelBase<V, R, I>;
573    
574 persson 2127 static IM instruments;
575    
576 iliev 2012 protected:
577     class SuspensionVoiceHandler : public MidiKeyboardManager<V>::VoiceHandler {
578     public:
579     int PendingStreamDeletions;
580     RR* pPendingRegionSuspension;
581 schoenebeck 2434
582 iliev 2012 SuspensionVoiceHandler(RR* pPendingRegionSuspension) {
583     PendingStreamDeletions = 0;
584     this->pPendingRegionSuspension = pPendingRegionSuspension;
585     }
586    
587 schoenebeck 2434 virtual bool Process(MidiKey* pMidiKey) OVERRIDE {
588 iliev 2012 VoiceIterator itVoice = pMidiKey->pActiveVoices->first();
589     // if current key is not associated with this region, skip this key
590     if (itVoice->GetRegion()->GetParent() != pPendingRegionSuspension) return false;
591    
592     return true;
593     }
594    
595 schoenebeck 2434 virtual void Process(VoiceIterator& itVoice) OVERRIDE {
596 iliev 2012 // request a notification from disk thread side for stream deletion
597     const Stream::Handle hStream = itVoice->KillImmediately(true);
598     if (hStream != Stream::INVALID_HANDLE) { // voice actually used a stream
599     PendingStreamDeletions++;
600     }
601     //NOTE: maybe we should call FreeVoice() here, shouldn't cause a harm though I think, since the voices should be freed by RenderActiveVoices() in the render loop, they are probably just freed a bit later than they could/should be
602     }
603     };
604    
605     Pool<R*>* pRegionPool[2]; ///< Double buffered pool, used by the engine channels to keep track of regions in use.
606     int MinFadeOutSamples; ///< The number of samples needed to make an instant fade out (e.g. for voice stealing) without leading to clicks.
607     D* pDiskThread;
608    
609     int ActiveVoiceCountTemp; ///< number of currently active voices (for internal usage, will be used for incrementation)
610     VoiceIterator itLastStolenVoice; ///< Only for voice stealing: points to the last voice which was theft in current audio fragment, NULL otherwise.
611     RTList<uint>::Iterator iuiLastStolenKey; ///< Only for voice stealing: key number of last key on which the last voice was theft in current audio fragment, NULL otherwise.
612     EngineChannelBase<V, R, I>* pLastStolenChannel; ///< Only for voice stealing: points to the engine channel on which the previous voice was stolen in this audio fragment.
613     VoiceIterator itLastStolenVoiceGlobally; ///< Same as itLastStolenVoice, but engine globally
614     RTList<uint>::Iterator iuiLastStolenKeyGlobally; ///< Same as iuiLastStolenKey, but engine globally
615     RTList<Event>* pVoiceStealingQueue; ///< All voice-launching events which had to be postponed due to free voice shortage.
616     Mutex ResetInternalMutex; ///< Mutex to protect the ResetInternal function for concurrent usage (e.g. by the lscp and instrument loader threads).
617     int iMaxDiskStreams;
618    
619     /**
620     * Dispatch and handle all events in this audio fragment for the given
621     * engine channel.
622     *
623     * @param pEngineChannel - engine channel on which events should be
624     * processed
625     * @param Samples - amount of sample points to be processed in
626     * this audio fragment cycle
627     */
628     void ProcessEvents(EngineChannel* pEngineChannel, uint Samples) {
629     // get all events from the engine channels's input event queue which belong to the current fragment
630     // (these are the common events like NoteOn, NoteOff, ControlChange, etc.)
631     AbstractEngineChannel* pChannel = static_cast<AbstractEngineChannel*>(pEngineChannel);
632     pChannel->ImportEvents(Samples);
633    
634 schoenebeck 2594 // if a valid real-time instrument script is loaded, pre-process
635     // the event list by running the script now, since the script
636     // might filter events or add new ones for this cycle
637     if (pChannel->script.bHasValidScript) {
638     // resume any suspended script executions still hanging
639     // around of previous audio fragment cycles
640     for (RTList<ScriptEvent>::Iterator itEvent = pChannel->pScriptEvents->first(),
641     end = pChannel->pScriptEvents->end(); itEvent != end; ++itEvent)
642     {
643     ResumeScriptEvent(pChannel, itEvent);
644     }
645    
646     // spawn new script executions for the new MIDI events of
647     // this audio fragment cycle
648     for (RTList<Event>::Iterator itEvent = pChannel->pEvents->first(),
649     end = pChannel->pEvents->end(); itEvent != end; ++itEvent)
650     {
651     switch (itEvent->Type) {
652     case Event::type_note_on:
653     if (pChannel->script.handlerNote)
654     ProcessEventByScript(pChannel, itEvent, pChannel->script.handlerNote);
655     break;
656     case Event::type_note_off:
657     //TODO: ...
658     break;
659     case Event::type_control_change:
660     case Event::type_channel_pressure:
661     case Event::type_pitchbend:
662     if (pChannel->script.handlerController)
663     ProcessEventByScript(pChannel, itEvent, pChannel->script.handlerController);
664     break;
665     case Event::type_note_pressure:
666     //TODO: ...
667     break;
668     }
669     }
670     }
671    
672     // now process all events regularly
673 iliev 2012 {
674     RTList<Event>::Iterator itEvent = pChannel->pEvents->first();
675     RTList<Event>::Iterator end = pChannel->pEvents->end();
676     for (; itEvent != end; ++itEvent) {
677     switch (itEvent->Type) {
678     case Event::type_note_on:
679     dmsg(5,("Engine: Note on received\n"));
680     ProcessNoteOn((EngineChannel*)itEvent->pEngineChannel, itEvent);
681     break;
682     case Event::type_note_off:
683     dmsg(5,("Engine: Note off received\n"));
684     ProcessNoteOff((EngineChannel*)itEvent->pEngineChannel, itEvent);
685     break;
686     case Event::type_control_change:
687     dmsg(5,("Engine: MIDI CC received\n"));
688     ProcessControlChange((EngineChannel*)itEvent->pEngineChannel, itEvent);
689     break;
690 schoenebeck 2559 case Event::type_channel_pressure:
691     dmsg(5,("Engine: MIDI Chan. Pressure received\n"));
692     ProcessChannelPressure((EngineChannel*)itEvent->pEngineChannel, itEvent);
693     break;
694     case Event::type_note_pressure:
695     dmsg(5,("Engine: MIDI Note Pressure received\n"));
696     ProcessPolyphonicKeyPressure((EngineChannel*)itEvent->pEngineChannel, itEvent);
697     break;
698 iliev 2012 case Event::type_pitchbend:
699     dmsg(5,("Engine: Pitchbend received\n"));
700     ProcessPitchbend(static_cast<AbstractEngineChannel*>(itEvent->pEngineChannel), itEvent);
701     break;
702     }
703     }
704     }
705    
706     // reset voice stealing for the next engine channel (or next audio fragment)
707     itLastStolenVoice = VoiceIterator();
708     itLastStolenVoiceGlobally = VoiceIterator();
709     iuiLastStolenKey = RTList<uint>::Iterator();
710     iuiLastStolenKeyGlobally = RTList<uint>::Iterator();
711     pLastStolenChannel = NULL;
712     }
713    
714 schoenebeck 2594 /** @brief Call instrument script's event handler for this event.
715     *
716     * Causes a new execution instance of the currently loaded real-time
717     * instrument script's event handler (callback) to be spawned for
718     * the given MIDI event.
719     *
720     * @param pChannel - engine channel on which the MIDI event occured
721     * @param itEvent - MIDI event that causes this new script execution
722     * @param pEventHandler - script's event handler to be executed
723     */
724     void ProcessEventByScript(AbstractEngineChannel* pChannel, RTList<Event>::Iterator& itEvent, VMEventHandler* pEventHandler) {
725     RTList<ScriptEvent>::Iterator itScriptEvent =
726     pChannel->pScriptEvents->allocAppend();
727    
728     if (!itScriptEvent) return; // no free script event left for execution
729    
730     // fill the list of script handlers to be executed by this event
731     int i = 0;
732     if (pChannel->script.handlerInit)
733     itScriptEvent->handlers[i++] = pChannel->script.handlerInit;
734     itScriptEvent->handlers[i++] = pEventHandler; // actual event handler (i.e. note, controller)
735     itScriptEvent->handlers[i] = NULL; // NULL termination of list
736    
737     // initialize/reset other members
738     itScriptEvent->cause = *itEvent;
739     itScriptEvent->currentHandler = 0;
740     itScriptEvent->executionSlices = 0;
741    
742     // run script handler(s)
743     VMExecStatus_t res = pScriptVM->exec(
744     pChannel->script.parserContext, &*itScriptEvent
745     );
746    
747     // in case the script was suspended, keep it on the allocated
748     // ScriptEvent list to be continued on the next audio cycle,
749     // otherwise if execution has been finished, free it for a new
750     // future script event to be triggered from start
751     if (!(res & VM_EXEC_SUSPENDED))
752     pChannel->pScriptEvents->free(itScriptEvent);
753     }
754    
755     /** @brief Resume execution of instrument script.
756     *
757     * Will be called to resume execution of a real-time instrument
758     * script event which has been suspended in a previous audio
759     * fragment cycle.
760     *
761     * Script execution might be suspended for various reasons. Usually
762     * a script will be suspended if the script called the built-in
763     * "wait()" function, but it might also be suspended automatically
764     * if the script took too much execution time in an audio fragment
765     * cycle. So in the latter case automatic suspension is performed in
766     * order to avoid harm for the sampler's overall real-time
767     * requirements.
768     *
769     * @param pChannel - engine channel this script is running for
770     * @param itScriptEvent - script execution that shall be resumed
771     */
772     void ResumeScriptEvent(AbstractEngineChannel* pChannel, RTList<ScriptEvent>::Iterator& itScriptEvent) {
773     // run script
774     VMExecStatus_t res = pScriptVM->exec(
775     pChannel->script.parserContext, &*itScriptEvent
776     );
777     // in case the script was again suspended, keep it on the allocated
778     // ScriptEvent list to be continued on the next audio cycle,
779     // otherwise if execution has been finished, free it for a new
780     // future script event to be triggered from start
781     if (!(res & VM_EXEC_SUSPENDED))
782     pChannel->pScriptEvents->free(itScriptEvent);
783     }
784    
785 iliev 2012 /**
786     * Will be called by LaunchVoice() method in case there are no free
787     * voices left. This method will select and kill one old voice for
788     * voice stealing and postpone the note-on event until the selected
789     * voice actually died.
790     *
791     * @param pEngineChannel - engine channel on which this event occured on
792     * @param itNoteOnEvent - key, velocity and time stamp of the event
793     * @returns 0 on success, a value < 0 if no active voice could be picked for voice stealing
794     */
795     int StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
796     if (VoiceSpawnsLeft <= 0) {
797     dmsg(1,("Max. voice thefts per audio fragment reached (you may raise CONFIG_MAX_VOICES).\n"));
798     return -1;
799     }
800    
801     EngineChannelBase<V, R, I>* pEngineChn = static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
802    
803     if (!pEventPool->poolIsEmpty()) {
804    
805     if(!pEngineChn->StealVoice(itNoteOnEvent, &itLastStolenVoice, &iuiLastStolenKey)) {
806     --VoiceSpawnsLeft;
807     return 0;
808     }
809    
810     // if we couldn't steal a voice from the same engine channel then
811     // steal oldest voice on the oldest key from any other engine channel
812     // (the smaller engine channel number, the higher priority)
813     EngineChannelBase<V, R, I>* pSelectedChannel;
814     int iChannelIndex;
815     VoiceIterator itSelectedVoice;
816    
817     // select engine channel
818     if (pLastStolenChannel) {
819     pSelectedChannel = pLastStolenChannel;
820     iChannelIndex = pSelectedChannel->iEngineIndexSelf;
821     } else { // pick the engine channel followed by this engine channel
822     iChannelIndex = (pEngineChn->iEngineIndexSelf + 1) % engineChannels.size();
823     pSelectedChannel = static_cast<EngineChannelBase<V, R, I>*>(engineChannels[iChannelIndex]);
824     }
825    
826     // if we already stole in this fragment, try to proceed on same key
827     if (this->itLastStolenVoiceGlobally) {
828     itSelectedVoice = this->itLastStolenVoiceGlobally;
829     do {
830     ++itSelectedVoice;
831     } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
832     }
833    
834     #if CONFIG_DEVMODE
835     EngineChannel* pBegin = pSelectedChannel; // to detect endless loop
836     #endif // CONFIG_DEVMODE
837    
838     // did we find a 'stealable' voice?
839     if (itSelectedVoice && itSelectedVoice->IsStealable()) {
840     // remember which voice we stole, so we can simply proceed on next voice stealing
841     this->itLastStolenVoiceGlobally = itSelectedVoice;
842     } else while (true) { // iterate through engine channels
843     // get (next) oldest key
844     RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKeyGlobally) ? ++this->iuiLastStolenKeyGlobally : pSelectedChannel->pActiveKeys->first();
845     this->iuiLastStolenKeyGlobally = RTList<uint>::Iterator(); // to prevent endless loop (see line above)
846     while (iuiSelectedKey) {
847     MidiKey* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];
848     itSelectedVoice = pSelectedKey->pActiveVoices->first();
849     // proceed iterating if voice was created in this fragment cycle
850     while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
851     // found a "stealable" voice ?
852     if (itSelectedVoice && itSelectedVoice->IsStealable()) {
853     // remember which voice on which key on which engine channel we stole, so we can simply proceed on next voice stealing
854     this->iuiLastStolenKeyGlobally = iuiSelectedKey;
855     this->itLastStolenVoiceGlobally = itSelectedVoice;
856     this->pLastStolenChannel = pSelectedChannel;
857     goto stealable_voice_found; // selection succeeded
858     }
859     ++iuiSelectedKey; // get next key on current engine channel
860     }
861     // get next engine channel
862     iChannelIndex = (iChannelIndex + 1) % engineChannels.size();
863     pSelectedChannel = static_cast<EngineChannelBase<V, R, I>*>(engineChannels[iChannelIndex]);
864    
865     #if CONFIG_DEVMODE
866     if (pSelectedChannel == pBegin) {
867     dmsg(1,("FATAL ERROR: voice stealing endless loop!\n"));
868     dmsg(1,("VoiceSpawnsLeft=%d.\n", VoiceSpawnsLeft));
869     dmsg(1,("Exiting.\n"));
870     exit(-1);
871     }
872     #endif // CONFIG_DEVMODE
873     }
874    
875     // jump point if a 'stealable' voice was found
876     stealable_voice_found:
877    
878     #if CONFIG_DEVMODE
879     if (!itSelectedVoice->IsActive()) {
880     dmsg(1,("EngineBase: ERROR, tried to steal a voice which was not active !!!\n"));
881     return -1;
882     }
883     #endif // CONFIG_DEVMODE
884    
885     // now kill the selected voice
886     itSelectedVoice->Kill(itNoteOnEvent);
887    
888     --VoiceSpawnsLeft;
889    
890     return 0; // success
891     }
892     else {
893     dmsg(1,("Event pool emtpy!\n"));
894     return -1;
895     }
896     }
897    
898     void HandleInstrumentChanges() {
899     bool instrumentChanged = false;
900     for (int i = 0; i < engineChannels.size(); i++) {
901     EngineChannelBase<V, R, I>* pEngineChannel =
902     static_cast<EngineChannelBase<V, R, I>*>(engineChannels[i]);
903    
904     // as we're going to (carefully) write some status to the
905     // synchronized struct, we cast away the const
906     InstrumentChangeCmd<R, I>& cmd =
907     const_cast<InstrumentChangeCmd<R, I>&>(pEngineChannel->InstrumentChangeCommandReader.Lock());
908    
909     pEngineChannel->pRegionsInUse = cmd.pRegionsInUse;
910     pEngineChannel->pRegionsInUse->clear();
911    
912     if (cmd.bChangeInstrument) {
913     // change instrument
914     dmsg(5,("Engine: instrument change command received\n"));
915     cmd.bChangeInstrument = false;
916     pEngineChannel->pInstrument = cmd.pInstrument;
917     instrumentChanged = true;
918    
919     pEngineChannel->MarkAllActiveVoicesAsOrphans();
920     }
921     }
922    
923     if (instrumentChanged) {
924     //TODO: this is a lazy solution ATM and not safe in case somebody is currently editing the instrument we're currently switching to (we should store all suspended regions on instrument manager side and when switching to another instrument copy that list to the engine's local list of suspensions
925     ResetSuspendedRegions();
926     }
927     }
928    
929     /**
930     * Render all 'normal' voices (that is voices which were not stolen in
931     * this fragment) on the given engine channel.
932     *
933     * @param pEngineChannel - engine channel on which audio should be
934     * rendered
935     * @param Samples - amount of sample points to be rendered in
936     * this audio fragment cycle
937     */
938     void RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {
939     #if !CONFIG_PROCESS_MUTED_CHANNELS
940     if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
941     #endif
942    
943     EngineChannelBase<V, R, I>* pChannel =
944     static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
945     pChannel->RenderActiveVoices(Samples);
946    
947     ActiveVoiceCountTemp += pEngineChannel->GetVoiceCount();
948     }
949    
950     /**
951     * Render all stolen voices (only voices which were stolen in this
952     * fragment) on the given engine channel. Stolen voices are rendered
953     * after all normal voices have been rendered; this is needed to render
954     * audio of those voices which were selected for voice stealing until
955     * the point were the stealing (that is the take over of the voice)
956     * actually happened.
957     *
958     * @param pEngineChannel - engine channel on which audio should be
959     * rendered
960     * @param Samples - amount of sample points to be rendered in
961     * this audio fragment cycle
962     */
963     void RenderStolenVoices(uint Samples) {
964     RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();
965     RTList<Event>::Iterator end = pVoiceStealingQueue->end();
966     for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
967     EngineChannelBase<V, R, I>* pEngineChannel =
968     static_cast<EngineChannelBase<V, R, I>*>(itVoiceStealEvent->pEngineChannel);;
969     if (!pEngineChannel->pInstrument) continue; // ignore if no instrument loaded
970     PoolVoiceIterator itNewVoice =
971     LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false, false);
972     if (itNewVoice) {
973     itNewVoice->Render(Samples);
974     if (itNewVoice->IsActive()) { // still active
975     *(pEngineChannel->pRegionsInUse->allocAppend()) = itNewVoice->GetRegion();
976     ActiveVoiceCountTemp++;
977     pEngineChannel->SetVoiceCount(pEngineChannel->GetVoiceCount() + 1);
978    
979     if (itNewVoice->PlaybackState == Voice::playback_state_disk) {
980     if (itNewVoice->DiskStreamRef.State != Stream::state_unused) {
981     pEngineChannel->SetDiskStreamCount(pEngineChannel->GetDiskStreamCount() + 1);
982     }
983     }
984     } else { // voice reached end, is now inactive
985     pEngineChannel->FreeVoice(itNewVoice); // remove voice from the list of active voices
986     }
987     }
988     else dmsg(1,("EngineBase: ERROR, voice stealing didn't work out!\n"));
989    
990     // we need to clear the key's event list explicitly here in case key was never active
991     MidiKey* pKey = &pEngineChannel->pMIDIKeyInfo[itVoiceStealEvent->Param.Note.Key];
992     pKey->VoiceTheftsQueued--;
993     if (!pKey->Active && !pKey->VoiceTheftsQueued) pKey->pEvents->clear();
994     }
995     }
996    
997     /**
998     * Free all keys which have turned inactive in this audio fragment, from
999     * the list of active keys and clear all event lists on that engine
1000     * channel.
1001     *
1002     * @param pEngineChannel - engine channel to cleanup
1003     */
1004     void PostProcess(EngineChannel* pEngineChannel) {
1005     EngineChannelBase<V, R, I>* pChannel =
1006     static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
1007     pChannel->FreeAllInactiveKyes();
1008    
1009     // empty the engine channel's own event lists
1010     pChannel->ClearEventLists();
1011     }
1012    
1013 schoenebeck 2121 /**
1014     * Process MIDI control change events with hard coded behavior,
1015     * that is controllers whose behavior is defined independently
1016     * of the actual sampler engine type and instrument.
1017     *
1018     * @param pEngineChannel - engine channel on which the MIDI CC event was received
1019     * @param itControlChangeEvent - the actual MIDI CC event
1020     */
1021 iliev 2012 void ProcessHardcodedControllers (
1022     EngineChannel* pEngineChannel,
1023     Pool<Event>::Iterator& itControlChangeEvent
1024     ) {
1025     EngineChannelBase<V, R, I>* pChannel =
1026     static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
1027    
1028     switch (itControlChangeEvent->Param.CC.Controller) {
1029     case 5: { // portamento time
1030     pChannel->PortamentoTime = (float) itControlChangeEvent->Param.CC.Value / 127.0f * (float) CONFIG_PORTAMENTO_TIME_MAX + (float) CONFIG_PORTAMENTO_TIME_MIN;
1031     break;
1032     }
1033 schoenebeck 2121 case 6: { // data entry (currently only used for RPN and NRPN controllers)
1034     //dmsg(1,("DATA ENTRY %d\n", itControlChangeEvent->Param.CC.Value));
1035     if (pChannel->GetMidiRpnController() >= 0) { // RPN controller number was sent previously ...
1036     dmsg(4,("Guess it's an RPN ...\n"));
1037     if (pChannel->GetMidiRpnController() == 2) { // coarse tuning in half tones
1038     int transpose = (int) itControlChangeEvent->Param.CC.Value - 64;
1039     // limit to +- two octaves for now
1040     transpose = RTMath::Min(transpose, 24);
1041     transpose = RTMath::Max(transpose, -24);
1042     pChannel->GlobalTranspose = transpose;
1043     // workaround, so we won't have hanging notes
1044     pChannel->ReleaseAllVoices(itControlChangeEvent);
1045     }
1046     // to prevent other MIDI CC #6 messages to be misenterpreted as RPN controller data
1047     pChannel->ResetMidiRpnController();
1048     } else if (pChannel->GetMidiNrpnController() >= 0) { // NRPN controller number was sent previously ...
1049     dmsg(4,("Guess it's an NRPN ...\n"));
1050     const int NrpnCtrlMSB = pChannel->GetMidiNrpnController() >> 8;
1051     const int NrpnCtrlLSB = pChannel->GetMidiNrpnController() & 0xff;
1052     dmsg(4,("NRPN MSB=%d LSB=%d Data=%d\n", NrpnCtrlMSB, NrpnCtrlLSB, itControlChangeEvent->Param.CC.Value));
1053     switch (NrpnCtrlMSB) {
1054     case 0x1a: { // volume level of note (Roland GS NRPN)
1055     const uint note = NrpnCtrlLSB;
1056     const uint vol = itControlChangeEvent->Param.CC.Value;
1057     dmsg(4,("Note Volume NRPN received (note=%d,vol=%d).\n", note, vol));
1058     if (note < 128 && vol < 128)
1059     pChannel->pMIDIKeyInfo[note].Volume = VolumeCurve[vol];
1060     break;
1061     }
1062     case 0x1c: { // panpot of note (Roland GS NRPN)
1063     const uint note = NrpnCtrlLSB;
1064     const uint pan = itControlChangeEvent->Param.CC.Value;
1065     dmsg(4,("Note Pan NRPN received (note=%d,pan=%d).\n", note, pan));
1066     if (note < 128 && pan < 128) {
1067     pChannel->pMIDIKeyInfo[note].PanLeft = PanCurve[128 - pan];
1068     pChannel->pMIDIKeyInfo[note].PanRight = PanCurve[pan];
1069     }
1070     break;
1071     }
1072     case 0x1d: { // reverb send of note (Roland GS NRPN)
1073     const uint note = NrpnCtrlLSB;
1074     const float reverb = float(itControlChangeEvent->Param.CC.Value) / 127.0f;
1075     dmsg(4,("Note Reverb Send NRPN received (note=%d,send=%d).\n", note, reverb));
1076     if (note < 128)
1077     pChannel->pMIDIKeyInfo[note].ReverbSend = reverb;
1078     break;
1079     }
1080     case 0x1e: { // chorus send of note (Roland GS NRPN)
1081     const uint note = NrpnCtrlLSB;
1082     const float chorus = float(itControlChangeEvent->Param.CC.Value) / 127.0f;
1083     dmsg(4,("Note Chorus Send NRPN received (note=%d,send=%d).\n", note, chorus));
1084     if (note < 128)
1085     pChannel->pMIDIKeyInfo[note].ChorusSend = chorus;
1086     break;
1087     }
1088     }
1089     // to prevent other MIDI CC #6 messages to be misenterpreted as NRPN controller data
1090     pChannel->ResetMidiNrpnController();
1091 iliev 2012 }
1092     break;
1093     }
1094     case 7: { // volume
1095     //TODO: not sample accurate yet
1096     pChannel->MidiVolume = VolumeCurve[itControlChangeEvent->Param.CC.Value];
1097     pChannel->bStatusChanged = true; // engine channel status has changed, so set notify flag
1098     break;
1099     }
1100     case 10: { // panpot
1101     //TODO: not sample accurate yet
1102     pChannel->iLastPanRequest = itControlChangeEvent->Param.CC.Value;
1103     break;
1104     }
1105     case 64: { // sustain
1106     if (itControlChangeEvent->Param.CC.Value >= 64 && !pChannel->SustainPedal) {
1107     dmsg(4,("DAMPER (RIGHT) PEDAL DOWN\n"));
1108     pChannel->SustainPedal = true;
1109     pChannel->listeners.PreProcessSustainPedalDown();
1110    
1111     #if !CONFIG_PROCESS_MUTED_CHANNELS
1112     if (pEngineChannel->GetMute()) { // skip if sampler channel is muted
1113     pChannel->listeners.PostProcessSustainPedalDown();
1114     return;
1115     }
1116     #endif
1117    
1118     pChannel->ProcessSustainPedalDown(itControlChangeEvent);
1119     pChannel->listeners.PostProcessSustainPedalDown();
1120     }
1121     if (itControlChangeEvent->Param.CC.Value < 64 && pChannel->SustainPedal) {
1122     dmsg(4,("DAMPER (RIGHT) PEDAL UP\n"));
1123     pChannel->SustainPedal = false;
1124     pChannel->listeners.PreProcessSustainPedalUp();
1125    
1126     #if !CONFIG_PROCESS_MUTED_CHANNELS
1127     if (pChannel->GetMute()) { // skip if sampler channel is muted
1128     pChannel->listeners.PostProcessSustainPedalUp();
1129     return;
1130     }
1131     #endif
1132    
1133     pChannel->ProcessSustainPedalUp(itControlChangeEvent);
1134     pChannel->listeners.PostProcessSustainPedalUp();
1135     }
1136     break;
1137     }
1138     case 65: { // portamento on / off
1139     const bool bPortamento = itControlChangeEvent->Param.CC.Value >= 64;
1140     if (bPortamento != pChannel->PortamentoMode)
1141     KillAllVoices(pChannel, itControlChangeEvent);
1142     pChannel->PortamentoMode = bPortamento;
1143     break;
1144     }
1145     case 66: { // sostenuto
1146     if (itControlChangeEvent->Param.CC.Value >= 64 && !pChannel->SostenutoPedal) {
1147     dmsg(4,("SOSTENUTO (CENTER) PEDAL DOWN\n"));
1148     pChannel->SostenutoPedal = true;
1149     pChannel->listeners.PreProcessSostenutoPedalDown();
1150    
1151     #if !CONFIG_PROCESS_MUTED_CHANNELS
1152     if (pEngineChannel->GetMute()) { // skip if sampler channel is muted
1153     pChannel->listeners.PostProcessSostenutoPedalDown();
1154     return;
1155     }
1156     #endif
1157    
1158     pChannel->ProcessSostenutoPedalDown();
1159     pChannel->listeners.PostProcessSostenutoPedalDown();
1160     }
1161     if (itControlChangeEvent->Param.CC.Value < 64 && pChannel->SostenutoPedal) {
1162     dmsg(4,("SOSTENUTO (CENTER) PEDAL UP\n"));
1163     pChannel->SostenutoPedal = false;
1164     pChannel->listeners.PreProcessSostenutoPedalUp();
1165    
1166     #if !CONFIG_PROCESS_MUTED_CHANNELS
1167     if (pEngineChannel->GetMute()) { // skip if sampler channel is muted
1168     pChannel->listeners.PostProcessSostenutoPedalUp();
1169     return;
1170     }
1171     #endif
1172    
1173     pChannel->ProcessSostenutoPedalUp(itControlChangeEvent);
1174     pChannel->listeners.PostProcessSostenutoPedalUp();
1175     }
1176     break;
1177     }
1178 schoenebeck 2121 case 98: { // NRPN controller LSB
1179     dmsg(4,("NRPN LSB %d\n", itControlChangeEvent->Param.CC.Value));
1180     pEngineChannel->SetMidiNrpnControllerLsb(itControlChangeEvent->Param.CC.Value);
1181     break;
1182     }
1183     case 99: { // NRPN controller MSB
1184     dmsg(4,("NRPN MSB %d\n", itControlChangeEvent->Param.CC.Value));
1185     pEngineChannel->SetMidiNrpnControllerMsb(itControlChangeEvent->Param.CC.Value);
1186     break;
1187     }
1188 iliev 2012 case 100: { // RPN controller LSB
1189 schoenebeck 2121 dmsg(4,("RPN LSB %d\n", itControlChangeEvent->Param.CC.Value));
1190 iliev 2012 pEngineChannel->SetMidiRpnControllerLsb(itControlChangeEvent->Param.CC.Value);
1191     break;
1192     }
1193     case 101: { // RPN controller MSB
1194 schoenebeck 2121 dmsg(4,("RPN MSB %d\n", itControlChangeEvent->Param.CC.Value));
1195 iliev 2012 pEngineChannel->SetMidiRpnControllerMsb(itControlChangeEvent->Param.CC.Value);
1196     break;
1197     }
1198    
1199    
1200     // Channel Mode Messages
1201    
1202     case 120: { // all sound off
1203     KillAllVoices(pEngineChannel, itControlChangeEvent);
1204     break;
1205     }
1206     case 121: { // reset all controllers
1207     pChannel->ResetControllers();
1208     break;
1209     }
1210     case 123: { // all notes off
1211     #if CONFIG_PROCESS_ALL_NOTES_OFF
1212     pChannel->ReleaseAllVoices(itControlChangeEvent);
1213     #endif // CONFIG_PROCESS_ALL_NOTES_OFF
1214     break;
1215     }
1216     case 126: { // mono mode on
1217     if (!pChannel->SoloMode)
1218     KillAllVoices(pEngineChannel, itControlChangeEvent);
1219     pChannel->SoloMode = true;
1220     break;
1221     }
1222     case 127: { // poly mode on
1223     if (pChannel->SoloMode)
1224     KillAllVoices(pEngineChannel, itControlChangeEvent);
1225     pChannel->SoloMode = false;
1226     break;
1227     }
1228     }
1229     }
1230    
1231     virtual D* CreateDiskThread() = 0;
1232    
1233     /**
1234     * Assigns and triggers a new voice for the respective MIDI key.
1235     *
1236     * @param pEngineChannel - engine channel on which this event occured on
1237     * @param itNoteOnEvent - key, velocity and time stamp of the event
1238     */
1239     virtual void ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
1240     EngineChannelBase<V, R, I>* pChannel =
1241     static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
1242    
1243     //HACK: we should better add the transpose value only to the most mandatory places (like for retrieving the region and calculating the tuning), because otherwise voices will unintendedly survive when changing transpose while playing
1244     int k = itNoteOnEvent->Param.Note.Key + pChannel->GlobalTranspose;
1245     if (k < 0 || k > 127) return; //ignore keys outside the key range
1246    
1247     itNoteOnEvent->Param.Note.Key += pChannel->GlobalTranspose;
1248     int vel = itNoteOnEvent->Param.Note.Velocity;
1249    
1250     const int key = itNoteOnEvent->Param.Note.Key;
1251     MidiKey* pKey = &pChannel->pMIDIKeyInfo[key];
1252    
1253     pChannel->listeners.PreProcessNoteOn(key, vel);
1254     #if !CONFIG_PROCESS_MUTED_CHANNELS
1255     if (pEngineChannel->GetMute()) { // skip if sampler channel is muted
1256     pChannel->listeners.PostProcessNoteOn(key, vel);
1257     return;
1258     }
1259     #endif
1260    
1261     if (!pChannel->pInstrument) {
1262     pChannel->listeners.PostProcessNoteOn(key, vel);
1263     return; // ignore if no instrument loaded
1264     }
1265    
1266     // move note on event to the key's own event list
1267     RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
1268    
1269     // if Solo Mode then kill all already active voices
1270     if (pChannel->SoloMode) {
1271     Pool<uint>::Iterator itYoungestKey = pChannel->pActiveKeys->last();
1272     if (itYoungestKey) {
1273     const int iYoungestKey = *itYoungestKey;
1274     const MidiKey* pOtherKey = &pChannel->pMIDIKeyInfo[iYoungestKey];
1275     if (pOtherKey->Active) {
1276     // get final portamento position of currently active voice
1277     if (pChannel->PortamentoMode) {
1278     VoiceIterator itVoice = pOtherKey->pActiveVoices->last();
1279     if (itVoice) itVoice->UpdatePortamentoPos(itNoteOnEventOnKeyList);
1280     }
1281     // kill all voices on the (other) key
1282     VoiceIterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
1283     VoiceIterator end = pOtherKey->pActiveVoices->end();
1284     for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
1285 persson 2115 if (!(itVoiceToBeKilled->Type & Voice::type_release_trigger))
1286 iliev 2012 itVoiceToBeKilled->Kill(itNoteOnEventOnKeyList);
1287     }
1288     }
1289     }
1290     // set this key as 'currently active solo key'
1291     pChannel->SoloKey = key;
1292     }
1293    
1294     pChannel->ProcessKeySwitchChange(key);
1295    
1296     pKey->KeyPressed = true; // the MIDI key was now pressed down
1297     pKey->Velocity = itNoteOnEventOnKeyList->Param.Note.Velocity;
1298     pKey->NoteOnTime = FrameTime + itNoteOnEventOnKeyList->FragmentPos(); // will be used to calculate note length
1299    
1300     // cancel release process of voices on this key if needed
1301     if (pKey->Active && !pChannel->SustainPedal) {
1302     RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
1303     if (itCancelReleaseEvent) {
1304     *itCancelReleaseEvent = *itNoteOnEventOnKeyList; // copy event
1305     itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type
1306     }
1307     else dmsg(1,("Event pool emtpy!\n"));
1308     }
1309    
1310     TriggerNewVoices(pEngineChannel, itNoteOnEventOnKeyList);
1311    
1312     // if neither a voice was spawned or postponed then remove note on event from key again
1313     if (!pKey->Active && !pKey->VoiceTheftsQueued)
1314     pKey->pEvents->free(itNoteOnEventOnKeyList);
1315    
1316     if (!pChannel->SoloMode || pChannel->PortamentoPos < 0.0f) pChannel->PortamentoPos = (float) key;
1317 persson 2043 if (pKey->pRoundRobinIndex) {
1318     (*pKey->pRoundRobinIndex)++; // counter specific for the key or region
1319     pChannel->RoundRobinIndex++; // common counter for the channel
1320     }
1321 iliev 2012 pChannel->listeners.PostProcessNoteOn(key, vel);
1322     }
1323    
1324     /**
1325     * Allocate and trigger new voice(s) for the key.
1326     */
1327     virtual void TriggerNewVoices (
1328     EngineChannel* pEngineChannel,
1329     RTList<Event>::Iterator& itNoteOnEvent,
1330     bool HandleKeyGroupConflicts = true
1331     ) = 0;
1332    
1333     /**
1334     * Allocate and trigger release voice(s) for the key.
1335     */
1336     virtual void TriggerReleaseVoices (
1337     EngineChannel* pEngineChannel,
1338     RTList<Event>::Iterator& itNoteOffEvent
1339     ) = 0;
1340    
1341     /**
1342     * Releases the voices on the given key if sustain pedal is not pressed.
1343     * If sustain is pressed, the release of the note will be postponed until
1344     * sustain pedal will be released or voice turned inactive by itself (e.g.
1345     * due to completion of sample playback).
1346     *
1347     * @param pEngineChannel - engine channel on which this event occured on
1348     * @param itNoteOffEvent - key, velocity and time stamp of the event
1349     */
1350     virtual void ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {
1351     EngineChannelBase<V, R, I>* pChannel = static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
1352    
1353     int k = itNoteOffEvent->Param.Note.Key + pChannel->GlobalTranspose;
1354     if (k < 0 || k > 127) return; //ignore keys outside the key range
1355    
1356     //HACK: we should better add the transpose value only to the most mandatory places (like for retrieving the region and calculating the tuning), because otherwise voices will unintendedly survive when changing transpose while playing
1357     itNoteOffEvent->Param.Note.Key += pChannel->GlobalTranspose;
1358     int vel = itNoteOffEvent->Param.Note.Velocity;
1359    
1360     const int iKey = itNoteOffEvent->Param.Note.Key;
1361     MidiKey* pKey = &pChannel->pMIDIKeyInfo[iKey];
1362    
1363     pChannel->listeners.PreProcessNoteOff(iKey, vel);
1364    
1365     #if !CONFIG_PROCESS_MUTED_CHANNELS
1366     if (pEngineChannel->GetMute()) { // skip if sampler channel is muted
1367     pChannel->listeners.PostProcessNoteOff(iKey, vel);
1368     return;
1369     }
1370     #endif
1371    
1372     pKey->KeyPressed = false; // the MIDI key was now released
1373    
1374     // move event to the key's own event list
1375     RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
1376    
1377     bool bShouldRelease = pKey->Active && pChannel->ShouldReleaseVoice(itNoteOffEventOnKeyList->Param.Note.Key);
1378    
1379     // in case Solo Mode is enabled, kill all voices on this key and respawn a voice on the highest pressed key (if any)
1380     if (pChannel->SoloMode && pChannel->pInstrument) { //TODO: this feels like too much code just for handling solo mode :P
1381     bool bOtherKeysPressed = false;
1382     if (iKey == pChannel->SoloKey) {
1383     pChannel->SoloKey = -1;
1384     // if there's still a key pressed down, respawn a voice (group) on the highest key
1385     for (int i = 127; i > 0; i--) {
1386     MidiKey* pOtherKey = &pChannel->pMIDIKeyInfo[i];
1387     if (pOtherKey->KeyPressed) {
1388     bOtherKeysPressed = true;
1389     // make the other key the new 'currently active solo key'
1390     pChannel->SoloKey = i;
1391     // get final portamento position of currently active voice
1392     if (pChannel->PortamentoMode) {
1393     VoiceIterator itVoice = pKey->pActiveVoices->first();
1394     if (itVoice) itVoice->UpdatePortamentoPos(itNoteOffEventOnKeyList);
1395     }
1396     // create a pseudo note on event
1397     RTList<Event>::Iterator itPseudoNoteOnEvent = pOtherKey->pEvents->allocAppend();
1398     if (itPseudoNoteOnEvent) {
1399     // copy event
1400     *itPseudoNoteOnEvent = *itNoteOffEventOnKeyList;
1401     // transform event to a note on event
1402     itPseudoNoteOnEvent->Type = Event::type_note_on;
1403     itPseudoNoteOnEvent->Param.Note.Key = i;
1404     itPseudoNoteOnEvent->Param.Note.Velocity = pOtherKey->Velocity;
1405     // allocate and trigger new voice(s) for the other key
1406     TriggerNewVoices(pChannel, itPseudoNoteOnEvent, false);
1407     // if neither a voice was spawned or postponed then remove note on event from key again
1408     if (!pOtherKey->Active && !pOtherKey->VoiceTheftsQueued)
1409     pOtherKey->pEvents->free(itPseudoNoteOnEvent);
1410    
1411     } else dmsg(1,("Could not respawn voice, no free event left\n"));
1412     break; // done
1413     }
1414     }
1415     }
1416     if (bOtherKeysPressed) {
1417     if (pKey->Active) { // kill all voices on this key
1418     bShouldRelease = false; // no need to release, as we kill it here
1419     VoiceIterator itVoiceToBeKilled = pKey->pActiveVoices->first();
1420     VoiceIterator end = pKey->pActiveVoices->end();
1421     for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
1422 persson 2115 if (!(itVoiceToBeKilled->Type & Voice::type_release_trigger))
1423 iliev 2012 itVoiceToBeKilled->Kill(itNoteOffEventOnKeyList);
1424     }
1425     }
1426     } else pChannel->PortamentoPos = -1.0f;
1427     }
1428    
1429     // if no solo mode (the usual case) or if solo mode and no other key pressed, then release voices on this key if needed
1430     if (bShouldRelease) {
1431     itNoteOffEventOnKeyList->Type = Event::type_release; // transform event type
1432    
1433     // spawn release triggered voice(s) if needed
1434     if (pKey->ReleaseTrigger && pChannel->pInstrument) {
1435     TriggerReleaseVoices(pChannel, itNoteOffEventOnKeyList);
1436     pKey->ReleaseTrigger = false;
1437     }
1438     }
1439    
1440     // if neither a voice was spawned or postponed on this key then remove note off event from key again
1441     if (!pKey->Active && !pKey->VoiceTheftsQueued)
1442     pKey->pEvents->free(itNoteOffEventOnKeyList);
1443    
1444     pChannel->listeners.PostProcessNoteOff(iKey, vel);
1445     }
1446    
1447     /**
1448     * Reset all voices and disk thread and clear input event queue and all
1449     * control and status variables. This method is protected by a mutex.
1450     */
1451     virtual void ResetInternal() {
1452 persson 2427 LockGuard lock(ResetInternalMutex);
1453 iliev 2012
1454     // make sure that the engine does not get any sysex messages
1455     // while it's reseting
1456     bool sysexDisabled = MidiInputPort::RemoveSysexListener(this);
1457     SetVoiceCount(0);
1458     ActiveVoiceCountMax = 0;
1459    
1460     // reset voice stealing parameters
1461     pVoiceStealingQueue->clear();
1462     itLastStolenVoice = VoiceIterator();
1463     itLastStolenVoiceGlobally = VoiceIterator();
1464     iuiLastStolenKey = RTList<uint>::Iterator();
1465     iuiLastStolenKeyGlobally = RTList<uint>::Iterator();
1466     pLastStolenChannel = NULL;
1467    
1468     // reset all voices
1469     for (VoiceIterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
1470     iterVoice->Reset();
1471     }
1472     pVoicePool->clear();
1473    
1474     // reset disk thread
1475     if (pDiskThread) pDiskThread->Reset();
1476    
1477     // delete all input events
1478     pEventQueue->init();
1479     pSysexBuffer->init();
1480     if (sysexDisabled) MidiInputPort::AddSysexListener(this);
1481     }
1482    
1483     /**
1484     * Kills all voices on an engine channel as soon as possible. Voices
1485     * won't get into release state, their volume level will be ramped down
1486     * as fast as possible.
1487     *
1488     * @param pEngineChannel - engine channel on which all voices should be killed
1489     * @param itKillEvent - event which caused this killing of all voices
1490     */
1491     virtual void KillAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itKillEvent) {
1492     EngineChannelBase<V, R, I>* pChannel = static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
1493     int count = pChannel->KillAllVoices(itKillEvent);
1494     VoiceSpawnsLeft -= count; //FIXME: just a temporary workaround, we should check the cause in StealVoice() instead
1495     }
1496    
1497     /**
1498     * Allocates and triggers a new voice. This method will usually be
1499     * called by the ProcessNoteOn() method and by the voices itself
1500     * (e.g. to spawn further voices on the same key for layered sounds).
1501     *
1502     * @param pEngineChannel - engine channel on which this event occured on
1503     * @param itNoteOnEvent - key, velocity and time stamp of the event
1504     * @param iLayer - layer index for the new voice (optional - only
1505     * in case of layered sounds of course)
1506     * @param ReleaseTriggerVoice - if new voice is a release triggered voice
1507     * (optional, default = false)
1508     * @param VoiceStealing - if voice stealing should be performed
1509     * when there is no free voice
1510     * (optional, default = true)
1511     * @param HandleKeyGroupConflicts - if voices should be killed due to a
1512     * key group conflict
1513     * @returns pointer to new voice or NULL if there was no free voice or
1514     * if the voice wasn't triggered (for example when no region is
1515     * defined for the given key).
1516     */
1517     virtual PoolVoiceIterator LaunchVoice (
1518     EngineChannel* pEngineChannel,
1519     Pool<Event>::Iterator& itNoteOnEvent,
1520     int iLayer,
1521     bool ReleaseTriggerVoice,
1522     bool VoiceStealing,
1523     bool HandleKeyGroupConflicts
1524     ) = 0;
1525    
1526 iliev 2015 virtual int GetMinFadeOutSamples() { return MinFadeOutSamples; }
1527    
1528 iliev 2027 int InitNewVoice (
1529     EngineChannelBase<V, R, I>* pChannel,
1530     R* pRegion,
1531     Pool<Event>::Iterator& itNoteOnEvent,
1532     Voice::type_t VoiceType,
1533     int iLayer,
1534     int iKeyGroup,
1535     bool ReleaseTriggerVoice,
1536     bool VoiceStealing,
1537     typename Pool<V>::Iterator& itNewVoice
1538     ) {
1539     int key = itNoteOnEvent->Param.Note.Key;
1540     typename MidiKeyboardManager<V>::MidiKey* pKey = &pChannel->pMIDIKeyInfo[key];
1541     if (itNewVoice) {
1542     // launch the new voice
1543     if (itNewVoice->Trigger(pChannel, itNoteOnEvent, pChannel->Pitch, pRegion, VoiceType, iKeyGroup) < 0) {
1544     dmsg(4,("Voice not triggered\n"));
1545     pKey->pActiveVoices->free(itNewVoice);
1546     }
1547     else { // on success
1548     --VoiceSpawnsLeft;
1549     if (!pKey->Active) { // mark as active key
1550     pKey->Active = true;
1551     pKey->itSelf = pChannel->pActiveKeys->allocAppend();
1552     *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
1553     }
1554 persson 2115 if (itNewVoice->Type & Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)
1555 iliev 2027 return 0; // success
1556     }
1557     }
1558     else if (VoiceStealing) {
1559     // try to steal one voice
1560     int result = StealVoice(pChannel, itNoteOnEvent);
1561     if (!result) { // voice stolen successfully
1562     // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died
1563     RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();
1564     if (itStealEvent) {
1565     *itStealEvent = *itNoteOnEvent; // copy event
1566     itStealEvent->Param.Note.Layer = iLayer;
1567     itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;
1568     pKey->VoiceTheftsQueued++;
1569     }
1570     else dmsg(1,("Voice stealing queue full!\n"));
1571     }
1572     }
1573    
1574     return -1;
1575     }
1576 schoenebeck 2448
1577     /**
1578     * Checks whether scale tuning setting has been changed since last
1579     * time this method was called, if yes, it recalculates the pitch
1580     * for all active voices.
1581     */
1582     void ProcessScaleTuningChange() {
1583     const bool changed = ScaleTuningChanged.readAndReset();
1584     if (!changed) return;
1585    
1586     for (int i = 0; i < engineChannels.size(); i++) {
1587     EngineChannelBase<V, R, I>* channel =
1588     static_cast<EngineChannelBase<V, R, I>*>(engineChannels[i]);
1589     channel->OnScaleTuningChanged();
1590     }
1591     }
1592 iliev 2027
1593 iliev 2012 private:
1594     Pool<V>* pVoicePool; ///< Contains all voices that can be activated.
1595     Pool<RR*> SuspendedRegions;
1596     Mutex SuspendedRegionsMutex;
1597     Condition SuspensionChangeOngoing;
1598     RR* pPendingRegionSuspension;
1599     RR* pPendingRegionResumption;
1600     int iPendingStreamDeletions;
1601     };
1602    
1603     template <class V, class RR, class R, class D, class IM, class I>
1604     IM EngineBase<V, RR, R, D, IM, I>::instruments;
1605    
1606     } // namespace LinuxSampler
1607    
1608     #endif /* __LS_ENGINEBASE_H__ */
1609    

  ViewVC Help
Powered by ViewVC