/[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 2935 - (hide annotations) (download) (as text)
Sun Jul 10 14:24:13 2016 UTC (7 years, 8 months ago) by schoenebeck
File MIME type: text/x-c++hdr
File size: 114991 byte(s)
* NKSP: Added & implemented built-in script function "change_cutoff()".
* NKSP: Added & implemented built-in script function "change_reso()".
* NKSP: Added & implemented built-in script function "event_status()".
* NKSP: Added built-in script constants "$EVENT_STATUS_INACTIVE" and
  "$EVENT_STATUS_NOTE_QUEUE" both for being used as flags for
  built-in "event_status()" script function.
* NKSP language: Added support for bitwise operators ".or.", ".and."
  and ".not.".
* NKSP language scanner: Fixed IDs matching to require at least one
  character (i.e. when matching function names or variable names).
* NKSP language scanner: disabled unusued rules.
* Bumped version (2.0.0.svn12).

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 schoenebeck 2871 * Copyright (C) 2009-2012 Christian Schoenebeck and Grigor Iliev *
8     * Copyright (C) 2012-2016 Christian Schoenebeck and Andreas Persson *
9 iliev 2012 * *
10     * This program is free software; you can redistribute it and/or modify *
11     * it under the terms of the GNU General Public License as published by *
12     * the Free Software Foundation; either version 2 of the License, or *
13     * (at your option) any later version. *
14     * *
15     * This program is distributed in the hope that it will be useful, *
16     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
17     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
18     * GNU General Public License for more details. *
19     * *
20     * You should have received a copy of the GNU General Public License *
21     * along with this program; if not, write to the Free Software *
22     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
23     * MA 02111-1307 USA *
24     ***************************************************************************/
25    
26     #ifndef __LS_ENGINEBASE_H__
27     #define __LS_ENGINEBASE_H__
28    
29     #include "AbstractEngine.h"
30     #include "EngineChannelBase.h"
31     #include "common/DiskThreadBase.h"
32     #include "common/MidiKeyboardManager.h"
33     #include "InstrumentManager.h"
34     #include "../common/global_private.h"
35    
36 schoenebeck 2879 // a bit headroom over CONFIG_MAX_VOICES to avoid minor complications i.e. under voice stealing conditions
37     #define MAX_NOTES_HEADROOM 3
38     #define GLOBAL_MAX_NOTES (GLOBAL_MAX_VOICES * MAX_NOTES_HEADROOM)
39 iliev 2012
40     namespace LinuxSampler {
41    
42     class AbstractEngineChannel;
43    
44     template <
45     class V /* Voice */,
46     class RR /* Root Region */,
47     class R /* Region */,
48     class D /* Disk Thread */,
49     class IM /* Instrument Manager */,
50     class I /* Instrument */
51     >
52 schoenebeck 2879 class EngineBase: public AbstractEngine, public RegionPools<R>, public NotePool<V> {
53 iliev 2012
54     public:
55 schoenebeck 2879 typedef typename RTList< Note<V> >::Iterator NoteIterator;
56 iliev 2012 typedef typename RTList<V>::Iterator VoiceIterator;
57     typedef typename Pool<V>::Iterator PoolVoiceIterator;
58     typedef typename RTList<RR*>::Iterator RootRegionIterator;
59     typedef typename MidiKeyboardManager<V>::MidiKey MidiKey;
60    
61 schoenebeck 2879 EngineBase() : SuspendedRegions(128), noteIDPool(GLOBAL_MAX_NOTES) {
62 iliev 2012 pDiskThread = NULL;
63 schoenebeck 2879 pNotePool = new Pool< Note<V> >(GLOBAL_MAX_NOTES);
64     pNotePool->setPoolElementIDsReservedBits(INSTR_SCRIPT_EVENT_ID_RESERVED_BITS);
65 iliev 2012 pVoicePool = new Pool<V>(GLOBAL_MAX_VOICES);
66     pRegionPool[0] = new Pool<R*>(GLOBAL_MAX_VOICES);
67     pRegionPool[1] = new Pool<R*>(GLOBAL_MAX_VOICES);
68     pVoiceStealingQueue = new RTList<Event>(pEventPool);
69     iMaxDiskStreams = GLOBAL_MAX_STREAMS;
70    
71 schoenebeck 2879 // init all Voice objects in voice pool
72     for (VoiceIterator iterVoice = pVoicePool->allocAppend();
73     iterVoice; iterVoice = pVoicePool->allocAppend())
74     {
75 iliev 2012 iterVoice->SetEngine(this);
76     }
77     pVoicePool->clear();
78    
79 schoenebeck 2879 // init all Note objects in note pool
80     for (NoteIterator itNote = pNotePool->allocAppend(); itNote;
81     itNote = pNotePool->allocAppend())
82     {
83     itNote->init(pVoicePool, &noteIDPool);
84     }
85     pNotePool->clear();
86    
87 iliev 2012 ResetInternal();
88     ResetScaleTuning();
89     ResetSuspendedRegions();
90     }
91    
92     virtual ~EngineBase() {
93     if (pDiskThread) {
94     dmsg(1,("Stopping disk thread..."));
95     pDiskThread->StopThread();
96     delete pDiskThread;
97     dmsg(1,("OK\n"));
98     }
99    
100 schoenebeck 2879 if (pNotePool) {
101     pNotePool->clear();
102     delete pNotePool;
103     }
104    
105 iliev 2012 if (pVoicePool) {
106     pVoicePool->clear();
107     delete pVoicePool;
108     }
109    
110     if (pVoiceStealingQueue) delete pVoiceStealingQueue;
111    
112     if (pRegionPool[0]) delete pRegionPool[0];
113     if (pRegionPool[1]) delete pRegionPool[1];
114     ResetSuspendedRegions();
115     }
116    
117     // implementation of abstract methods derived from class 'LinuxSampler::Engine'
118    
119     /**
120     * Let this engine proceed to render the given amount of sample points.
121     * The engine will iterate through all engine channels and render audio
122     * for each engine channel independently. The calculated audio data of
123     * all voices of each engine channel will be placed into the audio sum
124     * buffers of the respective audio output device, connected to the
125     * respective engine channel.
126     *
127     * @param Samples - number of sample points to be rendered
128     * @returns 0 on success
129     */
130 schoenebeck 2434 virtual int RenderAudio(uint Samples) OVERRIDE {
131 iliev 2012 dmsg(8,("RenderAudio(Samples=%d)\n", Samples));
132    
133     // return if engine disabled
134     if (EngineDisabled.Pop()) {
135     dmsg(5,("EngineBase: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));
136     EngineDisabled.RttDone();
137     return 0;
138     }
139    
140     // process requests for suspending / resuming regions (i.e. to avoid
141     // crashes while these regions are modified by an instrument editor)
142     ProcessSuspensionsChanges();
143    
144     // update time of start and end of this audio fragment (as events' time stamps relate to this)
145     pEventGenerator->UpdateFragmentTime(Samples);
146    
147     // We only allow the given maximum number of voices to be spawned
148     // in each audio fragment. All subsequent request for spawning new
149     // voices in the same audio fragment will be ignored.
150     VoiceSpawnsLeft = MaxVoices();
151    
152     // get all events from the engine's global input event queue which belong to the current fragment
153     // (these are usually just SysEx messages)
154     ImportEvents(Samples);
155    
156     // process engine global events (these are currently only MIDI System Exclusive messages)
157     {
158     RTList<Event>::Iterator itEvent = pGlobalEvents->first();
159     RTList<Event>::Iterator end = pGlobalEvents->end();
160     for (; itEvent != end; ++itEvent) {
161     switch (itEvent->Type) {
162     case Event::type_sysex:
163     dmsg(5,("Engine: Sysex received\n"));
164     ProcessSysex(itEvent);
165     break;
166     }
167     }
168     }
169 schoenebeck 2448
170     // In case scale tuning has been changed, recalculate pitch for
171     // all active voices.
172     ProcessScaleTuningChange();
173 iliev 2012
174     // reset internal voice counter (just for statistic of active voices)
175     ActiveVoiceCountTemp = 0;
176    
177     HandleInstrumentChanges();
178    
179     // handle events on all engine channels
180     for (int i = 0; i < engineChannels.size(); i++) {
181     ProcessEvents(engineChannels[i], Samples);
182     }
183    
184     // render all 'normal', active voices on all engine channels
185     for (int i = 0; i < engineChannels.size(); i++) {
186     RenderActiveVoices(engineChannels[i], Samples);
187     }
188    
189     // now that all ordinary voices on ALL engine channels are rendered, render new stolen voices
190     RenderStolenVoices(Samples);
191    
192     // handle audio routing for engine channels with FX sends
193     for (int i = 0; i < engineChannels.size(); i++) {
194     AbstractEngineChannel* pChannel = static_cast<AbstractEngineChannel*>(engineChannels[i]);
195     if (pChannel->fxSends.empty()) continue; // ignore if no FX sends
196     RouteAudio(engineChannels[i], Samples);
197     }
198    
199     // handle cleanup on all engine channels for the next audio fragment
200     for (int i = 0; i < engineChannels.size(); i++) {
201     PostProcess(engineChannels[i]);
202     }
203    
204    
205     // empty the engine's event list for the next audio fragment
206     ClearEventLists();
207    
208     // reset voice stealing for the next audio fragment
209     pVoiceStealingQueue->clear();
210    
211     // just some statistics about this engine instance
212     SetVoiceCount(ActiveVoiceCountTemp);
213     if (VoiceCount() > ActiveVoiceCountMax) ActiveVoiceCountMax = VoiceCount();
214    
215     // in case regions were previously suspended and we killed voices
216     // with disk streams due to that, check if those streams have finally
217     // been deleted by the disk thread
218     if (iPendingStreamDeletions) ProcessPendingStreamDeletions();
219    
220 persson 2162 // Release the instrument change command. (This has to
221     // be done after all voices have been rendered and not
222     // in HandleInstrumentChanges, as the RegionsInUse
223     // list has been built up by the voice renderers.)
224     for (int i = 0; i < engineChannels.size(); i++) {
225     EngineChannelBase<V, R, I>* channel =
226     static_cast<EngineChannelBase<V, R, I>*>(engineChannels[i]);
227     channel->InstrumentChangeCommandReader.Unlock();
228     }
229 iliev 2012 FrameTime += Samples;
230    
231     EngineDisabled.RttDone();
232     return 0;
233     }
234    
235 schoenebeck 2434 virtual int MaxVoices() OVERRIDE { return pVoicePool->poolSize(); }
236 iliev 2012
237 schoenebeck 2434 virtual void SetMaxVoices(int iVoices) throw (Exception) OVERRIDE {
238 iliev 2012 if (iVoices < 1)
239     throw Exception("Maximum voices for an engine cannot be set lower than 1");
240    
241     SuspendAll();
242    
243     // NOTE: we need to clear pRegionsInUse before deleting pDimRegionPool,
244     // otherwise memory corruption will occur if there are active voices (see bug #118)
245     for (int iChannel = 0; iChannel < engineChannels.size(); iChannel++) {
246     EngineChannelBase<V, R, I>* pChannel = static_cast<EngineChannelBase<V, R, I>*>(engineChannels[iChannel]);
247     pChannel->ClearRegionsInUse();
248     }
249    
250     if (pRegionPool[0]) delete pRegionPool[0];
251     if (pRegionPool[1]) delete pRegionPool[1];
252    
253     pRegionPool[0] = new Pool<R*>(iVoices);
254     pRegionPool[1] = new Pool<R*>(iVoices);
255    
256     for (int iChannel = 0; iChannel < engineChannels.size(); iChannel++) {
257     EngineChannelBase<V, R, I>* pChannel = static_cast<EngineChannelBase<V, R, I>*>(engineChannels[iChannel]);
258     pChannel->ResetRegionsInUse(pRegionPool);
259     }
260    
261 schoenebeck 2879 // FIXME: Shouldn't all those pool elements be freed before resizing the pools?
262 iliev 2012 try {
263     pVoicePool->resizePool(iVoices);
264 schoenebeck 2879 pNotePool->resizePool(iVoices * MAX_NOTES_HEADROOM);
265     noteIDPool.resizePool(iVoices * MAX_NOTES_HEADROOM);
266 iliev 2012 } catch (...) {
267     throw Exception("FATAL: Could not resize voice pool!");
268     }
269    
270 schoenebeck 2879 for (VoiceIterator iterVoice = pVoicePool->allocAppend();
271     iterVoice; iterVoice = pVoicePool->allocAppend())
272     {
273 iliev 2012 iterVoice->SetEngine(this);
274     iterVoice->pDiskThread = this->pDiskThread;
275     }
276     pVoicePool->clear();
277    
278 schoenebeck 2879 for (NoteIterator itNote = pNotePool->allocAppend(); itNote;
279     itNote = pNotePool->allocAppend())
280     {
281     itNote->init(pVoicePool, &noteIDPool);
282     }
283     pNotePool->clear();
284    
285 iliev 2244 PostSetMaxVoices(iVoices);
286 iliev 2012 ResumeAll();
287     }
288 iliev 2244
289     /** Called after the new max number of voices is set and before resuming the engine. */
290     virtual void PostSetMaxVoices(int iVoices) { }
291 iliev 2012
292 schoenebeck 2434 virtual uint DiskStreamCount() OVERRIDE { return (pDiskThread) ? pDiskThread->GetActiveStreamCount() : 0; }
293     virtual uint DiskStreamCountMax() OVERRIDE { return (pDiskThread) ? pDiskThread->ActiveStreamCountMax : 0; }
294     virtual int MaxDiskStreams() OVERRIDE { return iMaxDiskStreams; }
295 iliev 2012
296 schoenebeck 2434 virtual void SetMaxDiskStreams(int iStreams) throw (Exception) OVERRIDE {
297 iliev 2012 if (iStreams < 0)
298     throw Exception("Maximum disk streams for an engine cannot be set lower than 0");
299    
300     SuspendAll();
301    
302     iMaxDiskStreams = iStreams;
303    
304     // reconnect to audio output device, because that will automatically
305     // recreate the disk thread with the required amount of streams
306     if (pAudioOutputDevice) Connect(pAudioOutputDevice);
307    
308     ResumeAll();
309     }
310    
311 schoenebeck 2434 virtual String DiskStreamBufferFillBytes() OVERRIDE { return (pDiskThread) ? pDiskThread->GetBufferFillBytes() : ""; }
312     virtual String DiskStreamBufferFillPercentage() OVERRIDE { return (pDiskThread) ? pDiskThread->GetBufferFillPercentage() : ""; }
313     virtual InstrumentManager* GetInstrumentManager() OVERRIDE { return &instruments; }
314 iliev 2012
315     /**
316     * Connect this engine instance with the given audio output device.
317     * This method will be called when an Engine instance is created.
318     * All of the engine's data structures which are dependant to the used
319     * audio output device / driver will be (re)allocated and / or
320     * adjusted appropriately.
321     *
322     * @param pAudioOut - audio output device to connect to
323     */
324 schoenebeck 2434 virtual void Connect(AudioOutputDevice* pAudioOut) OVERRIDE {
325 iliev 2012 // caution: don't ignore if connecting to the same device here,
326     // because otherwise SetMaxDiskStreams() implementation won't work anymore!
327    
328     pAudioOutputDevice = pAudioOut;
329    
330     ResetInternal();
331    
332     // inform audio driver for the need of two channels
333     try {
334     pAudioOutputDevice->AcquireChannels(2); // default stereo
335     }
336     catch (AudioOutputException e) {
337     String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();
338     throw Exception(msg);
339     }
340    
341     this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle();
342     this->SampleRate = pAudioOutputDevice->SampleRate();
343    
344     MinFadeOutSamples = int(double(SampleRate) * CONFIG_EG_MIN_RELEASE_TIME) - 1;
345     if (MaxSamplesPerCycle < MinFadeOutSamples) {
346     std::cerr << "EngineBase: WARNING, CONFIG_EG_MIN_RELEASE_TIME "
347     << "too big for current audio fragment size & sampling rate! "
348     << "May lead to click sounds if voice stealing chimes in!\n" << std::flush;
349     // force volume ramp downs at the beginning of each fragment
350     MinFadeOutSamples = MaxSamplesPerCycle;
351     // lower minimum release time
352     const float minReleaseTime = (float) MaxSamplesPerCycle / (float) SampleRate;
353 schoenebeck 2879 pVoicePool->clear();
354 iliev 2012 for (VoiceIterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
355 persson 2327 iterVoice->CalculateFadeOutCoeff(minReleaseTime, SampleRate);
356 iliev 2012 }
357     pVoicePool->clear();
358     }
359    
360     // (re)create disk thread
361     if (this->pDiskThread) {
362     dmsg(1,("Stopping disk thread..."));
363     this->pDiskThread->StopThread();
364     delete this->pDiskThread;
365     dmsg(1,("OK\n"));
366     }
367     this->pDiskThread = CreateDiskThread();
368    
369     if (!pDiskThread) {
370     dmsg(0,("EngineBase new diskthread = NULL\n"));
371     exit(EXIT_FAILURE);
372     }
373    
374 schoenebeck 2879 pVoicePool->clear();
375 iliev 2012 for (VoiceIterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
376     iterVoice->pDiskThread = this->pDiskThread;
377     dmsg(3,("d"));
378     }
379     pVoicePool->clear();
380    
381     // (re)create event generator
382     if (pEventGenerator) delete pEventGenerator;
383     pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
384    
385     dmsg(1,("Starting disk thread..."));
386     pDiskThread->StartThread();
387     dmsg(1,("OK\n"));
388    
389 iliev 2298 bool printEqInfo = true;
390 iliev 2012 for (VoiceIterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
391     if (!iterVoice->pDiskThread) {
392     dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));
393     exit(EXIT_FAILURE);
394     }
395 iliev 2298
396     iterVoice->CreateEq();
397    
398     if(printEqInfo) {
399     iterVoice->PrintEqInfo();
400     printEqInfo = false;
401     }
402 iliev 2012 }
403     pVoicePool->clear();
404 schoenebeck 2121
405     // (re)create dedicated voice audio buffers
406     //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
407     if (pDedicatedVoiceChannelLeft) delete pDedicatedVoiceChannelLeft;
408     if (pDedicatedVoiceChannelRight) delete pDedicatedVoiceChannelRight;
409     pDedicatedVoiceChannelLeft = new AudioChannel(0, MaxSamplesPerCycle);
410     pDedicatedVoiceChannelRight = new AudioChannel(1, MaxSamplesPerCycle);
411 iliev 2012 }
412 schoenebeck 2410
413     // Implementattion for abstract method derived from Engine.
414 schoenebeck 2434 virtual void ReconnectAudioOutputDevice() OVERRIDE {
415 schoenebeck 2410 SuspendAll();
416     if (pAudioOutputDevice) Connect(pAudioOutputDevice);
417     ResumeAll();
418     }
419 iliev 2012
420     /**
421     * Similar to @c Disable() but this method additionally kills all voices
422     * and disk streams and blocks until all voices and disk streams are actually
423     * killed / deleted.
424     *
425     * @e Note: only the original calling thread is able to re-enable the
426     * engine afterwards by calling @c ResumeAll() later on!
427     */
428     virtual void SuspendAll() {
429     dmsg(2,("Engine: Suspending all ...\n"));
430     // stop the engine, so we can safely modify the engine's
431     // data structures from this foreign thread
432     DisableAndLock();
433     // we could also use the respective class member variable here,
434     // but this is probably safer and cleaner
435     int iPendingStreamDeletions = 0;
436     // kill all voices on all engine channels the *die hard* way
437     for (int iChannel = 0; iChannel < engineChannels.size(); iChannel++) {
438     EngineChannelBase<V, R, I>* pEngineChannel =
439     static_cast<EngineChannelBase<V, R, I>*>(engineChannels[iChannel]);
440    
441     iPendingStreamDeletions += pEngineChannel->KillAllVoicesImmediately();
442     }
443     // wait until all streams were actually deleted by the disk thread
444     while (iPendingStreamDeletions) {
445     while (
446     iPendingStreamDeletions &&
447     pDiskThread->AskForDeletedStream() != Stream::INVALID_HANDLE
448     ) iPendingStreamDeletions--;
449     if (!iPendingStreamDeletions) break;
450     usleep(10000); // sleep for 10ms
451     }
452     dmsg(2,("EngineBase: Everything suspended.\n"));
453     }
454    
455     /**
456     * At the moment same as calling @c Enable() directly, but this might
457     * change in future, so better call this method as counterpart to
458     * @c SuspendAll() instead of @c Enable() !
459     */
460     virtual void ResumeAll() { Enable(); }
461    
462     /**
463     * Order the engine to stop rendering audio for the given region.
464     * Additionally this method will block until all voices and their disk
465     * streams associated with that region are actually killed / deleted, so
466     * one can i.e. safely modify the region with an instrument editor after
467     * returning from this method.
468     *
469     * @param pRegion - region the engine shall stop using
470     */
471     virtual void Suspend(RR* pRegion) {
472 persson 2837 dmsg(2,("EngineBase: Suspending Region %p ...\n",(void*)pRegion));
473 persson 2427 {
474     LockGuard lock(SuspendedRegionsMutex);
475     SuspensionChangeOngoing.Set(true);
476     pPendingRegionSuspension = pRegion;
477     SuspensionChangeOngoing.WaitAndUnlockIf(true);
478     }
479 persson 2837 dmsg(2,("EngineBase: Region %p suspended.",(void*)pRegion));
480 iliev 2012 }
481    
482     /**
483     * Orders the engine to resume playing back the given region, previously
484     * suspended with @c Suspend() .
485     *
486     * @param pRegion - region the engine shall be allowed to use again
487     */
488     virtual void Resume(RR* pRegion) {
489 persson 2837 dmsg(2,("EngineBase: Resuming Region %p ...\n",(void*)pRegion));
490 persson 2427 {
491     LockGuard lock(SuspendedRegionsMutex);
492     SuspensionChangeOngoing.Set(true);
493     pPendingRegionResumption = pRegion;
494     SuspensionChangeOngoing.WaitAndUnlockIf(true);
495     }
496 persson 2837 dmsg(2,("EngineBase: Region %p resumed.\n",(void*)pRegion));
497 iliev 2012 }
498    
499     virtual void ResetSuspendedRegions() {
500     SuspendedRegions.clear();
501     iPendingStreamDeletions = 0;
502     pPendingRegionSuspension = pPendingRegionResumption = NULL;
503     SuspensionChangeOngoing.Set(false);
504     }
505    
506     /**
507     * Called by the engine's (audio) thread once per cycle to process requests
508     * from the outer world to suspend or resume a given @c gig::Region .
509     */
510     virtual void ProcessSuspensionsChanges() {
511     // process request for suspending one region
512     if (pPendingRegionSuspension) {
513     // kill all voices on all engine channels that use this region
514     for (int iChannel = 0; iChannel < engineChannels.size(); iChannel++) {
515     EngineChannelBase<V, R, I>* pEngineChannel =
516     static_cast<EngineChannelBase<V, R, I>*>(engineChannels[iChannel]);
517     SuspensionVoiceHandler handler(pPendingRegionSuspension);
518     pEngineChannel->ProcessActiveVoices(&handler);
519     iPendingStreamDeletions += handler.PendingStreamDeletions;
520     }
521     // make sure the region is not yet on the list
522     bool bAlreadySuspended = false;
523     RootRegionIterator iter = SuspendedRegions.first();
524     RootRegionIterator end = SuspendedRegions.end();
525     for (; iter != end; ++iter) { // iterate through all suspended regions
526     if (*iter == pPendingRegionSuspension) { // found
527     bAlreadySuspended = true;
528     dmsg(1,("EngineBase: attempt to suspend an already suspended region !!!\n"));
529     break;
530     }
531     }
532     if (!bAlreadySuspended) {
533     // put the region on the list of suspended regions
534     RootRegionIterator iter = SuspendedRegions.allocAppend();
535     if (iter) {
536     *iter = pPendingRegionSuspension;
537     } else std::cerr << "EngineBase: Could not suspend Region, list is full. This is a bug!!!\n" << std::flush;
538     }
539     // free request slot for next caller (and to make sure that
540     // we're not going to process the same request in the next cycle)
541     pPendingRegionSuspension = NULL;
542     // if no disk stream deletions are pending, awaken other side, as
543     // we're done in this case
544     if (!iPendingStreamDeletions) SuspensionChangeOngoing.Set(false);
545     }
546    
547     // process request for resuming one region
548     if (pPendingRegionResumption) {
549     // remove region from the list of suspended regions
550     RootRegionIterator iter = SuspendedRegions.first();
551     RootRegionIterator end = SuspendedRegions.end();
552     for (; iter != end; ++iter) { // iterate through all suspended regions
553     if (*iter == pPendingRegionResumption) { // found
554     SuspendedRegions.free(iter);
555     break; // done
556     }
557     }
558     // free request slot for next caller
559     pPendingRegionResumption = NULL;
560     // awake other side as we're done
561     SuspensionChangeOngoing.Set(false);
562     }
563     }
564    
565     /**
566     * Called by the engine's (audio) thread once per cycle to check if
567     * streams of voices that were killed due to suspension request have
568     * finally really been deleted by the disk thread.
569     */
570     virtual void ProcessPendingStreamDeletions() {
571     if (!iPendingStreamDeletions) return;
572     //TODO: or shall we better store a list with stream handles instead of a scalar amount of streams to be deleted? might be safer
573     while (
574     iPendingStreamDeletions &&
575     pDiskThread->AskForDeletedStream() != Stream::INVALID_HANDLE
576     ) iPendingStreamDeletions--;
577     // just for safety ...
578     while (pDiskThread->AskForDeletedStream() != Stream::INVALID_HANDLE);
579     // now that all disk streams are deleted, awake other side as
580     // we're finally done with suspending the requested region
581     if (!iPendingStreamDeletions) SuspensionChangeOngoing.Set(false);
582     }
583    
584     /**
585     * Returns @c true if the given region is currently set to be suspended
586     * from being used, @c false otherwise.
587     */
588     virtual bool RegionSuspended(RR* pRegion) {
589     if (SuspendedRegions.isEmpty()) return false;
590     //TODO: or shall we use a sorted container instead of the RTList? might be faster ... or trivial ;-)
591     RootRegionIterator iter = SuspendedRegions.first();
592     RootRegionIterator end = SuspendedRegions.end();
593     for (; iter != end; ++iter) // iterate through all suspended regions
594     if (*iter == pRegion) return true;
595     return false;
596     }
597    
598     // implementation of abstract method derived from class 'LinuxSampler::RegionPools'
599     virtual Pool<R*>* GetRegionPool(int index) {
600     if (index < 0 || index > 1) throw Exception("Index out of bounds");
601     return pRegionPool[index];
602     }
603    
604 schoenebeck 2879 // implementation of abstract methods derived from class 'LinuxSampler::NotePool'
605     virtual Pool<V>* GetVoicePool() OVERRIDE { return pVoicePool; }
606     virtual Pool< Note<V> >* GetNotePool() OVERRIDE { return pNotePool; }
607     virtual Pool<note_id_t>* GetNodeIDPool() OVERRIDE { return &noteIDPool; }
608 iliev 2012
609     D* GetDiskThread() { return pDiskThread; }
610    
611     //friend class EngineChannelBase<V, R, I>;
612    
613 persson 2127 static IM instruments;
614    
615 iliev 2012 protected:
616     class SuspensionVoiceHandler : public MidiKeyboardManager<V>::VoiceHandler {
617     public:
618     int PendingStreamDeletions;
619     RR* pPendingRegionSuspension;
620 schoenebeck 2434
621 iliev 2012 SuspensionVoiceHandler(RR* pPendingRegionSuspension) {
622     PendingStreamDeletions = 0;
623     this->pPendingRegionSuspension = pPendingRegionSuspension;
624     }
625    
626 schoenebeck 2434 virtual bool Process(MidiKey* pMidiKey) OVERRIDE {
627 schoenebeck 2879 NoteIterator itNote = pMidiKey->pActiveNotes->first();
628     VoiceIterator itVoice = itNote->pActiveVoices->first();
629 iliev 2012 // if current key is not associated with this region, skip this key
630     if (itVoice->GetRegion()->GetParent() != pPendingRegionSuspension) return false;
631    
632     return true;
633     }
634    
635 schoenebeck 2434 virtual void Process(VoiceIterator& itVoice) OVERRIDE {
636 iliev 2012 // request a notification from disk thread side for stream deletion
637     const Stream::Handle hStream = itVoice->KillImmediately(true);
638     if (hStream != Stream::INVALID_HANDLE) { // voice actually used a stream
639     PendingStreamDeletions++;
640     }
641     //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
642     }
643     };
644    
645     Pool<R*>* pRegionPool[2]; ///< Double buffered pool, used by the engine channels to keep track of regions in use.
646     int MinFadeOutSamples; ///< The number of samples needed to make an instant fade out (e.g. for voice stealing) without leading to clicks.
647     D* pDiskThread;
648    
649     int ActiveVoiceCountTemp; ///< number of currently active voices (for internal usage, will be used for incrementation)
650     VoiceIterator itLastStolenVoice; ///< Only for voice stealing: points to the last voice which was theft in current audio fragment, NULL otherwise.
651 schoenebeck 2879 NoteIterator itLastStolenNote; ///< Only for voice stealing: points to the last note from which was theft in current audio fragment, NULL otherwise.
652 iliev 2012 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.
653     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.
654     VoiceIterator itLastStolenVoiceGlobally; ///< Same as itLastStolenVoice, but engine globally
655 schoenebeck 2879 NoteIterator itLastStolenNoteGlobally; ///< Same as itLastStolenNote, but engine globally
656 iliev 2012 RTList<uint>::Iterator iuiLastStolenKeyGlobally; ///< Same as iuiLastStolenKey, but engine globally
657     RTList<Event>* pVoiceStealingQueue; ///< All voice-launching events which had to be postponed due to free voice shortage.
658     Mutex ResetInternalMutex; ///< Mutex to protect the ResetInternal function for concurrent usage (e.g. by the lscp and instrument loader threads).
659     int iMaxDiskStreams;
660    
661 schoenebeck 2879 NoteBase* NoteByID(note_id_t id) OVERRIDE {
662     NoteIterator itNote = GetNotePool()->fromID(id);
663     if (!itNote) return NULL;
664     return &*itNote;
665     }
666    
667 iliev 2012 /**
668 schoenebeck 2879 * Gets a new @c Note object from the note pool, initializes it
669     * appropriately, links it with requested parent note (if
670     * requested), moves it to the appropriate key's list of active
671     * notes it, and sticks the new note's unique ID to the
672     * passed @a pNoteOnEvent.
673     *
674     * @param pEngineChannel - engine channel on which this event happened
675     * @param pNoteOnEvent - event which caused this
676     * @returns new note's unique ID (or zero on error)
677     */
678     note_id_t LaunchNewNote(LinuxSampler::EngineChannel* pEngineChannel, Event* pNoteOnEvent) OVERRIDE {
679     EngineChannelBase<V, R, I>* pChannel = static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
680     Pool< Note<V> >* pNotePool = GetNotePool();
681    
682     if (pNotePool->poolIsEmpty()) {
683     dmsg(1,("Engine: Could not launch new note; Note pool empty!\n"));
684     return 0; // error
685     }
686    
687     // create a new note (for new voices to be assigned to)
688     //NoteIterator itNewNote = pKey->pActiveNotes->allocAppend();
689     NoteIterator itNewNote = pNotePool->allocAppend();
690     const note_id_t newNoteID = pNotePool->getID(itNewNote);
691    
692     // usually the new note (and its subsequent voices) will be
693     // allocated on the key provided by the event's note number,
694     // however if this new note is requested not to be a regular
695     // note, but rather a child note, then this new note will be
696     // allocated on the parent note's key instead in order to
697     // release the child note simultaniously with its parent note
698     itNewNote->hostKey = pNoteOnEvent->Param.Note.Key;
699    
700     // in case this new note was requested to be a child note,
701     // then retrieve its parent note and link them with each other
702     const note_id_t parentNoteID = pNoteOnEvent->Param.Note.ParentNoteID;
703     if (parentNoteID) {
704     NoteIterator itParentNote = pNotePool->fromID(parentNoteID);
705     if (itParentNote) {
706     RTList<note_id_t>::Iterator itChildNoteID = itParentNote->pChildNotes->allocAppend();
707     if (itChildNoteID) {
708     // link parent and child note with each other
709     *itChildNoteID = newNoteID;
710     itNewNote->parentNoteID = parentNoteID;
711     itNewNote->hostKey = itParentNote->hostKey;
712     } else {
713     dmsg(1,("Engine: Could not assign new note as child note; Note ID pool empty!\n"));
714     pNotePool->free(itNewNote);
715     return 0; // error
716     }
717     } else {
718     // the parent note was apparently released already, so
719     // free the new note again and inform caller that it
720     // should drop the event
721     dmsg(3,("Engine: Could not assign new note as child note; Parent note is gone!\n"));
722     pNotePool->free(itNewNote);
723     return 0; // error
724     }
725     }
726    
727     dmsg(2,("Launched new note on host key %d\n", itNewNote->hostKey));
728    
729     // copy event which caused this note
730     itNewNote->cause = *pNoteOnEvent;
731     itNewNote->eventID = pEventPool->getID(pNoteOnEvent);
732    
733     // move new note to its host key
734     MidiKey* pKey = &pChannel->pMIDIKeyInfo[itNewNote->hostKey];
735     itNewNote.moveToEndOf(pKey->pActiveNotes);
736    
737     // assign unique note ID of this new note to the original note on event
738     pNoteOnEvent->Param.Note.ID = newNoteID;
739    
740     return newNoteID; // success
741     }
742    
743     /**
744 iliev 2012 * Dispatch and handle all events in this audio fragment for the given
745     * engine channel.
746     *
747     * @param pEngineChannel - engine channel on which events should be
748     * processed
749     * @param Samples - amount of sample points to be processed in
750     * this audio fragment cycle
751     */
752     void ProcessEvents(EngineChannel* pEngineChannel, uint Samples) {
753     // get all events from the engine channels's input event queue which belong to the current fragment
754     // (these are the common events like NoteOn, NoteOff, ControlChange, etc.)
755     AbstractEngineChannel* pChannel = static_cast<AbstractEngineChannel*>(pEngineChannel);
756     pChannel->ImportEvents(Samples);
757    
758 schoenebeck 2594 // if a valid real-time instrument script is loaded, pre-process
759     // the event list by running the script now, since the script
760     // might filter events or add new ones for this cycle
761 schoenebeck 2659 if (pChannel->pScript) {
762 schoenebeck 2871 const sched_time_t fragmentEndTime = pEventGenerator->schedTimeAtCurrentFragmentEnd();
763 schoenebeck 2594
764 schoenebeck 2871 // resume suspended script executions been scheduled for
765     // this audio fragment cycle (which were suspended in a
766     // previous audio fragment cycle)
767     ProcessSuspendedScriptEvents(pChannel, fragmentEndTime);
768    
769 schoenebeck 2594 // spawn new script executions for the new MIDI events of
770     // this audio fragment cycle
771 schoenebeck 2871 //
772     // FIXME: it would probably be better to just schedule newly spawned script executions here and then execute them altogether with already suspended ones all at once in order of all their scheduled timing
773 schoenebeck 2594 for (RTList<Event>::Iterator itEvent = pChannel->pEvents->first(),
774 schoenebeck 2884 end = pChannel->pEvents->end(); itEvent != end; )
775 schoenebeck 2594 {
776 schoenebeck 2884 //HACK: avoids iterator invalidation which might happen below since an instrument script might drop an event by direct raw pointer access (it would be considerable to extend the Iterator class to detect and circumvent this case by checking the "reincarnation" member variable).
777     RTList<Event>::Iterator itNext = itEvent;
778     ++itNext;
779    
780 schoenebeck 2594 switch (itEvent->Type) {
781     case Event::type_note_on:
782 schoenebeck 2611 if (pChannel->pScript->handlerNote)
783     ProcessEventByScript(pChannel, itEvent, pChannel->pScript->handlerNote);
784 schoenebeck 2594 break;
785     case Event::type_note_off:
786 schoenebeck 2611 if (pChannel->pScript->handlerRelease)
787     ProcessEventByScript(pChannel, itEvent, pChannel->pScript->handlerRelease);
788 schoenebeck 2594 break;
789     case Event::type_control_change:
790     case Event::type_channel_pressure:
791     case Event::type_pitchbend:
792 schoenebeck 2611 if (pChannel->pScript->handlerController)
793     ProcessEventByScript(pChannel, itEvent, pChannel->pScript->handlerController);
794 schoenebeck 2594 break;
795     case Event::type_note_pressure:
796     //TODO: ...
797     break;
798     }
799 schoenebeck 2884
800     // see HACK comment above
801     itEvent = itNext;
802 schoenebeck 2594 }
803 schoenebeck 2871
804     // this has to be run again, since the newly spawned scripts
805     // above may have cause suspended scripts that must be
806     // resumed within this same audio fragment cycle
807     //
808     // FIXME: see FIXME comment above
809     ProcessSuspendedScriptEvents(pChannel, fragmentEndTime);
810 schoenebeck 2594 }
811    
812 schoenebeck 2871 // if there are any delayed events scheduled for the current
813     // audio fragment cycle, then move and sort them into the main
814     // event list
815     if (!pChannel->delayedEvents.queue.isEmpty()) {
816     dmsg(5,("Engine: There are delayed MIDI events (total queue size: %d) ...\n", pChannel->delayedEvents.queue.size()));
817     const sched_time_t fragmentEndTime = pEventGenerator->schedTimeAtCurrentFragmentEnd();
818     RTList<Event>::Iterator itEvent = pChannel->pEvents->first();
819     while (true) {
820     RTList<ScheduledEvent>::Iterator itDelayedEventNode =
821     pEventGenerator->popNextScheduledEvent(
822     pChannel->delayedEvents.queue,
823     pChannel->delayedEvents.schedulerNodes,
824     fragmentEndTime
825     );
826     if (!itDelayedEventNode) break;
827     // get the actual delayed event object and free the used scheduler node
828     RTList<Event>::Iterator itDelayedEvent = itDelayedEventNode->itEvent;
829     pChannel->delayedEvents.schedulerNodes.free(itDelayedEventNode);
830     if (!itDelayedEvent) { // should never happen, but just to be sure ...
831     dmsg(1,("Engine: Oops, invalid delayed event!\n"));
832     continue;
833     }
834     // skip all events on main event list which have a time
835     // before (or equal to) the delayed event to be inserted
836     for (; itEvent && itEvent->FragmentPos() <= itDelayedEvent->FragmentPos();
837     ++itEvent);
838     // now move delayed event from delayedEvents.pList to
839     // the current position on the main event list
840     itEvent = itDelayedEvent.moveBefore(itEvent);
841     dmsg(5,("Engine: Inserted event of type %d into main event list (queue size: %d).\n", itEvent->Type, pChannel->delayedEvents.queue.size()));
842     }
843     dmsg(5,("Engine: End of delayed events (total queue size: %d).\n", pChannel->delayedEvents.queue.size()));
844     }
845    
846 schoenebeck 2594 // now process all events regularly
847 iliev 2012 {
848     RTList<Event>::Iterator itEvent = pChannel->pEvents->first();
849     RTList<Event>::Iterator end = pChannel->pEvents->end();
850     for (; itEvent != end; ++itEvent) {
851     switch (itEvent->Type) {
852     case Event::type_note_on:
853     dmsg(5,("Engine: Note on received\n"));
854     ProcessNoteOn((EngineChannel*)itEvent->pEngineChannel, itEvent);
855     break;
856     case Event::type_note_off:
857     dmsg(5,("Engine: Note off received\n"));
858     ProcessNoteOff((EngineChannel*)itEvent->pEngineChannel, itEvent);
859     break;
860     case Event::type_control_change:
861     dmsg(5,("Engine: MIDI CC received\n"));
862     ProcessControlChange((EngineChannel*)itEvent->pEngineChannel, itEvent);
863     break;
864 schoenebeck 2559 case Event::type_channel_pressure:
865     dmsg(5,("Engine: MIDI Chan. Pressure received\n"));
866     ProcessChannelPressure((EngineChannel*)itEvent->pEngineChannel, itEvent);
867     break;
868     case Event::type_note_pressure:
869     dmsg(5,("Engine: MIDI Note Pressure received\n"));
870     ProcessPolyphonicKeyPressure((EngineChannel*)itEvent->pEngineChannel, itEvent);
871     break;
872 iliev 2012 case Event::type_pitchbend:
873     dmsg(5,("Engine: Pitchbend received\n"));
874     ProcessPitchbend(static_cast<AbstractEngineChannel*>(itEvent->pEngineChannel), itEvent);
875     break;
876 schoenebeck 2931 case Event::type_note_synth_param:
877     dmsg(5,("Engine: Note Synth Param received\n"));
878     ProcessNoteSynthParam(itEvent->pEngineChannel, itEvent);
879     break;
880 iliev 2012 }
881     }
882     }
883    
884     // reset voice stealing for the next engine channel (or next audio fragment)
885     itLastStolenVoice = VoiceIterator();
886     itLastStolenVoiceGlobally = VoiceIterator();
887 schoenebeck 2879 itLastStolenNote = NoteIterator();
888     itLastStolenNoteGlobally = NoteIterator();
889 iliev 2012 iuiLastStolenKey = RTList<uint>::Iterator();
890     iuiLastStolenKeyGlobally = RTList<uint>::Iterator();
891     pLastStolenChannel = NULL;
892     }
893    
894 schoenebeck 2871 /**
895     * Run all suspended script execution instances which are scheduled
896     * to be resumed for the current audio fragment cycle.
897     *
898     * @param pChannel - engine channel on which suspended events occurred
899     */
900     void ProcessSuspendedScriptEvents(AbstractEngineChannel* pChannel, const sched_time_t fragmentEndTime) {
901     while (true) {
902     RTList<ScriptEvent>::Iterator itEvent =
903     pEventGenerator->popNextScheduledScriptEvent(
904     pChannel->pScript->suspendedEvents,
905     *pChannel->pScript->pEvents, fragmentEndTime
906     );
907     if (!itEvent) break;
908     ResumeScriptEvent(pChannel, itEvent);
909     }
910     }
911    
912 schoenebeck 2594 /** @brief Call instrument script's event handler for this event.
913     *
914     * Causes a new execution instance of the currently loaded real-time
915     * instrument script's event handler (callback) to be spawned for
916     * the given MIDI event.
917     *
918 schoenebeck 2871 * @param pChannel - engine channel on which the MIDI event occurred
919 schoenebeck 2594 * @param itEvent - MIDI event that causes this new script execution
920     * @param pEventHandler - script's event handler to be executed
921     */
922     void ProcessEventByScript(AbstractEngineChannel* pChannel, RTList<Event>::Iterator& itEvent, VMEventHandler* pEventHandler) {
923 schoenebeck 2645 const int key = itEvent->Param.Note.Key; // even if this is not a note on/off event, accessing it does not mean any harm
924     // check if polyphonic data is passed from "note" to "release"
925     // script event handlers
926     if (pEventHandler == pChannel->pScript->handlerRelease &&
927     pChannel->pScript->handlerNote &&
928     pChannel->pScript->handlerNote->isPolyphonic() &&
929     pChannel->pScript->handlerRelease->isPolyphonic() &&
930     !pChannel->pScript->pKeyEvents[key]->isEmpty())
931     {
932     // polyphonic variable data is used/passed from "note" to
933     // "release" script callback, so we have to recycle the
934     // original "note on" script event(s)
935     RTList<ScriptEvent>::Iterator it = pChannel->pScript->pKeyEvents[key]->first();
936     RTList<ScriptEvent>::Iterator end = pChannel->pScript->pKeyEvents[key]->end();
937     for (; it != end; ++it) {
938     ProcessScriptEvent(
939     pChannel, itEvent, pEventHandler, it
940     );
941     }
942     } else {
943     // no polyphonic data is used/passed from "note" to
944     // "release" script callback, so just use a new fresh
945     // script event object
946     RTList<ScriptEvent>::Iterator itScriptEvent =
947     pChannel->pScript->pEvents->allocAppend();
948     ProcessScriptEvent(
949     pChannel, itEvent, pEventHandler, itScriptEvent
950     );
951     }
952     }
953 schoenebeck 2594
954 schoenebeck 2871 /** @brief Spawn new execution instance of an instrument script handler.
955     *
956     * Will be called to initiate a new execution of a real-time
957     * instrument script event right from the start of the script's
958     * respective handler. If script execution did not complete after
959     * calling this method, the respective script exeuction is then
960     * suspended and a call to ResumeScriptEvent() will be used next
961     * time to continue its execution.
962     *
963     * @param pChannel - engine channel this script is running for
964     * @param itEvent - event which caused execution of this script
965     * event handler
966     * @param pEventHandler - VM representation of event handler to be
967     * executed
968     * @param itScriptEvent - script event that shall be processed
969     */
970 schoenebeck 2645 void ProcessScriptEvent(AbstractEngineChannel* pChannel, RTList<Event>::Iterator& itEvent, VMEventHandler* pEventHandler, RTList<ScriptEvent>::Iterator& itScriptEvent) {
971     if (!itScriptEvent) return; // not a valid script event (i.e. because no free script event was left in the script event pool)
972 schoenebeck 2594
973     // fill the list of script handlers to be executed by this event
974     int i = 0;
975     itScriptEvent->handlers[i++] = pEventHandler; // actual event handler (i.e. note, controller)
976     itScriptEvent->handlers[i] = NULL; // NULL termination of list
977    
978     // initialize/reset other members
979     itScriptEvent->cause = *itEvent;
980     itScriptEvent->currentHandler = 0;
981     itScriptEvent->executionSlices = 0;
982 schoenebeck 2879 // this is the native representation of the $EVENT_ID script variable
983     itScriptEvent->id =
984     (itEvent->Type == Event::type_note_on)
985     ? ScriptID::fromNoteID( itEvent->Param.Note.ID )
986     : ScriptID::fromEventID( pEventPool->getID(itEvent) );
987 schoenebeck 2594
988     // run script handler(s)
989     VMExecStatus_t res = pScriptVM->exec(
990 schoenebeck 2611 pChannel->pScript->parserContext, &*itScriptEvent
991 schoenebeck 2594 );
992    
993 schoenebeck 2871 // was the script suspended?
994     if (res & VM_EXEC_SUSPENDED) { // script was suspended ...
995     // in case the script was suspended, keep it on the allocated
996     // ScriptEvent list to be resume at the scheduled time in future,
997     // additionally insert it into a sorted time queue
998     pEventGenerator->scheduleAheadMicroSec(
999     pChannel->pScript->suspendedEvents, // scheduler queue
1000     *itScriptEvent, // script event
1001     itScriptEvent->cause.FragmentPos(), // current time of script event (basis for its next execution)
1002     itScriptEvent->execCtx->suspensionTimeMicroseconds() // how long shall it be suspended
1003     );
1004     } else { // script execution has finished without 'suspended' status ...
1005 schoenebeck 2645 // if "polyphonic" variable data is passed from script's
1006     // "note" event handler to its "release" event handler, then
1007     // the script event must be kept and recycled for the later
1008     // occuring "release" script event ...
1009     if (pEventHandler == pChannel->pScript->handlerNote &&
1010     pChannel->pScript->handlerRelease &&
1011     pChannel->pScript->handlerNote->isPolyphonic() &&
1012     pChannel->pScript->handlerRelease->isPolyphonic())
1013     {
1014     const int key = itEvent->Param.Note.Key;
1015     itScriptEvent.moveToEndOf(pChannel->pScript->pKeyEvents[key & 127]);
1016     } else {
1017     // ... otherwise if no polyphonic data is passed and
1018     // script's execution has finished without suspension
1019     // status, then free the script event for a new future
1020     // script event to be triggered from start
1021     pChannel->pScript->pEvents->free(itScriptEvent);
1022     }
1023     }
1024 schoenebeck 2594 }
1025    
1026     /** @brief Resume execution of instrument script.
1027     *
1028     * Will be called to resume execution of a real-time instrument
1029 schoenebeck 2879 * script event which has been suspended previously.
1030 schoenebeck 2594 *
1031     * Script execution might be suspended for various reasons. Usually
1032     * a script will be suspended if the script called the built-in
1033     * "wait()" function, but it might also be suspended automatically
1034     * if the script took too much execution time in an audio fragment
1035     * cycle. So in the latter case automatic suspension is performed in
1036     * order to avoid harm for the sampler's overall real-time
1037     * requirements.
1038     *
1039     * @param pChannel - engine channel this script is running for
1040     * @param itScriptEvent - script execution that shall be resumed
1041     */
1042     void ResumeScriptEvent(AbstractEngineChannel* pChannel, RTList<ScriptEvent>::Iterator& itScriptEvent) {
1043 schoenebeck 2645 VMEventHandler* handler = itScriptEvent->handlers[itScriptEvent->currentHandler];
1044    
1045 schoenebeck 2594 // run script
1046     VMExecStatus_t res = pScriptVM->exec(
1047 schoenebeck 2611 pChannel->pScript->parserContext, &*itScriptEvent
1048 schoenebeck 2594 );
1049 schoenebeck 2645
1050 schoenebeck 2871 // was the script suspended?
1051     if (res & VM_EXEC_SUSPENDED) {
1052     // in case the script was suspended, keep it on the allocated
1053     // ScriptEvent list to be resume at the scheduled time in future,
1054     // additionally insert it into a sorted time queue
1055     pEventGenerator->scheduleAheadMicroSec(
1056     pChannel->pScript->suspendedEvents, // scheduler queue
1057     *itScriptEvent, // script event
1058     itScriptEvent->cause.FragmentPos(), // current time of script event (basis for its next execution)
1059     itScriptEvent->execCtx->suspensionTimeMicroseconds() // how long shall it be suspended
1060     );
1061     } else { // script execution has finished without 'suspended' status ...
1062 schoenebeck 2645 // if "polyphonic" variable data is passed from script's
1063     // "note" event handler to its "release" event handler, then
1064     // the script event must be kept and recycled for the later
1065     // occuring "release" script event ...
1066     if (handler && handler == pChannel->pScript->handlerNote &&
1067     pChannel->pScript->handlerRelease &&
1068     pChannel->pScript->handlerNote->isPolyphonic() &&
1069     pChannel->pScript->handlerRelease->isPolyphonic())
1070     {
1071     const int key = itScriptEvent->cause.Param.Note.Key;
1072     itScriptEvent.moveToEndOf(pChannel->pScript->pKeyEvents[key & 127]);
1073     } else {
1074     // ... otherwise if no polyphonic data is passed and
1075     // script's execution has finished without suspension
1076     // status, then free the script event for a new future
1077     // script event to be triggered from start
1078     pChannel->pScript->pEvents->free(itScriptEvent);
1079     }
1080     }
1081 schoenebeck 2594 }
1082    
1083 iliev 2012 /**
1084     * Will be called by LaunchVoice() method in case there are no free
1085     * voices left. This method will select and kill one old voice for
1086     * voice stealing and postpone the note-on event until the selected
1087     * voice actually died.
1088     *
1089 schoenebeck 2871 * @param pEngineChannel - engine channel on which this event occurred on
1090 iliev 2012 * @param itNoteOnEvent - key, velocity and time stamp of the event
1091     * @returns 0 on success, a value < 0 if no active voice could be picked for voice stealing
1092     */
1093 schoenebeck 2879 int StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
1094 iliev 2012 if (VoiceSpawnsLeft <= 0) {
1095     dmsg(1,("Max. voice thefts per audio fragment reached (you may raise CONFIG_MAX_VOICES).\n"));
1096     return -1;
1097     }
1098    
1099     EngineChannelBase<V, R, I>* pEngineChn = static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
1100    
1101 schoenebeck 2879 if (pEventPool->poolIsEmpty()) {
1102     dmsg(1,("Event pool emtpy!\n"));
1103     return -1;
1104     }
1105 iliev 2012
1106 schoenebeck 2879 if (!pEngineChn->StealVoice(itNoteOnEvent, &itLastStolenVoice, &itLastStolenNote, &iuiLastStolenKey)) {
1107     --VoiceSpawnsLeft;
1108     return 0;
1109     }
1110 iliev 2012
1111 schoenebeck 2879 // if we couldn't steal a voice from the same engine channel then
1112     // steal oldest voice on the oldest key from any other engine channel
1113     // (the smaller engine channel number, the higher priority)
1114     EngineChannelBase<V, R, I>* pSelectedChannel;
1115     int iChannelIndex;
1116     VoiceIterator itSelectedVoice;
1117 iliev 2012
1118 schoenebeck 2879 // select engine channel
1119     if (pLastStolenChannel) {
1120     pSelectedChannel = pLastStolenChannel;
1121     iChannelIndex = pSelectedChannel->iEngineIndexSelf;
1122     } else { // pick the engine channel followed by this engine channel
1123     iChannelIndex = (pEngineChn->iEngineIndexSelf + 1) % engineChannels.size();
1124     pSelectedChannel = static_cast<EngineChannelBase<V, R, I>*>(engineChannels[iChannelIndex]);
1125     }
1126 iliev 2012
1127 schoenebeck 2879 // if we already stole in this fragment, try to proceed on same note
1128     if (this->itLastStolenVoiceGlobally) {
1129     itSelectedVoice = this->itLastStolenVoiceGlobally;
1130     do {
1131     ++itSelectedVoice;
1132     } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1133     }
1134     // did we find a 'stealable' voice?
1135     if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1136     // remember which voice we stole, so we can simply proceed on next voice stealing
1137     this->itLastStolenVoiceGlobally = itSelectedVoice;
1138     // done
1139     goto stealable_voice_found;
1140     }
1141    
1142     // get (next) oldest note
1143     if (this->itLastStolenNoteGlobally) {
1144     for (NoteIterator itNote = ++this->itLastStolenNoteGlobally;
1145     itNote; ++itNote)
1146     {
1147     for (itSelectedVoice = itNote->pActiveVoices->first(); itSelectedVoice; ++itSelectedVoice) {
1148     // proceed iterating if voice was created in this audio fragment cycle
1149     if (itSelectedVoice->IsStealable()) {
1150     // remember which voice of which note we stole, so we can simply proceed on next voice stealing
1151     this->itLastStolenNoteGlobally = itNote;
1152     this->itLastStolenVoiceGlobally = itSelectedVoice;
1153     goto stealable_voice_found; // selection succeeded
1154     }
1155     }
1156 iliev 2012 }
1157 schoenebeck 2879 }
1158 iliev 2012
1159 schoenebeck 2879 #if CONFIG_DEVMODE
1160     EngineChannel* pBegin = pSelectedChannel; // to detect endless loop
1161     #endif // CONFIG_DEVMODE
1162 iliev 2012
1163 schoenebeck 2879 while (true) { // iterate through engine channels
1164     // get (next) oldest key
1165     RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKeyGlobally) ? ++this->iuiLastStolenKeyGlobally : pSelectedChannel->pActiveKeys->first();
1166     this->iuiLastStolenKeyGlobally = RTList<uint>::Iterator(); // to prevent endless loop (see line above)
1167     while (iuiSelectedKey) {
1168     MidiKey* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];
1169    
1170     for (NoteIterator itNote = pSelectedKey->pActiveNotes->first(),
1171     itNotesEnd = pSelectedKey->pActiveNotes->end();
1172     itNote != itNotesEnd; ++itNote)
1173     {
1174     itSelectedVoice = itNote->pActiveVoices->first();
1175 iliev 2012 // proceed iterating if voice was created in this fragment cycle
1176     while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1177     // found a "stealable" voice ?
1178     if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1179 schoenebeck 2879 // remember which voice of which note on which key on which engine channel we stole, so we can simply proceed on next voice stealing
1180 iliev 2012 this->iuiLastStolenKeyGlobally = iuiSelectedKey;
1181 schoenebeck 2879 this->itLastStolenNoteGlobally = itNote;
1182 iliev 2012 this->itLastStolenVoiceGlobally = itSelectedVoice;
1183     this->pLastStolenChannel = pSelectedChannel;
1184     goto stealable_voice_found; // selection succeeded
1185     }
1186     }
1187 schoenebeck 2879 ++iuiSelectedKey; // get next key on current engine channel
1188 iliev 2012 }
1189 schoenebeck 2879 // get next engine channel
1190     iChannelIndex = (iChannelIndex + 1) % engineChannels.size();
1191     pSelectedChannel = static_cast<EngineChannelBase<V, R, I>*>(engineChannels[iChannelIndex]);
1192 iliev 2012
1193     #if CONFIG_DEVMODE
1194 schoenebeck 2879 if (pSelectedChannel == pBegin) {
1195     dmsg(1,("FATAL ERROR: voice stealing endless loop!\n"));
1196     dmsg(1,("VoiceSpawnsLeft=%d.\n", VoiceSpawnsLeft));
1197     dmsg(1,("Exiting.\n"));
1198     exit(-1);
1199 iliev 2012 }
1200     #endif // CONFIG_DEVMODE
1201 schoenebeck 2879 }
1202 iliev 2012
1203 schoenebeck 2879 // jump point if a 'stealable' voice was found
1204     stealable_voice_found:
1205 iliev 2012
1206 schoenebeck 2879 #if CONFIG_DEVMODE
1207     if (!itSelectedVoice->IsActive()) {
1208     dmsg(1,("EngineBase: ERROR, tried to steal a voice which was not active !!!\n"));
1209 iliev 2012 return -1;
1210     }
1211 schoenebeck 2879 #endif // CONFIG_DEVMODE
1212    
1213     // now kill the selected voice
1214     itSelectedVoice->Kill(itNoteOnEvent);
1215    
1216     --VoiceSpawnsLeft;
1217    
1218     return 0; // success
1219 iliev 2012 }
1220    
1221     void HandleInstrumentChanges() {
1222     bool instrumentChanged = false;
1223     for (int i = 0; i < engineChannels.size(); i++) {
1224     EngineChannelBase<V, R, I>* pEngineChannel =
1225     static_cast<EngineChannelBase<V, R, I>*>(engineChannels[i]);
1226    
1227     // as we're going to (carefully) write some status to the
1228     // synchronized struct, we cast away the const
1229     InstrumentChangeCmd<R, I>& cmd =
1230     const_cast<InstrumentChangeCmd<R, I>&>(pEngineChannel->InstrumentChangeCommandReader.Lock());
1231    
1232     pEngineChannel->pRegionsInUse = cmd.pRegionsInUse;
1233     pEngineChannel->pRegionsInUse->clear();
1234    
1235     if (cmd.bChangeInstrument) {
1236     // change instrument
1237     dmsg(5,("Engine: instrument change command received\n"));
1238     cmd.bChangeInstrument = false;
1239     pEngineChannel->pInstrument = cmd.pInstrument;
1240 schoenebeck 2659 pEngineChannel->pScript =
1241     cmd.pScript->bHasValidScript ? cmd.pScript : NULL;
1242 iliev 2012 instrumentChanged = true;
1243    
1244     pEngineChannel->MarkAllActiveVoicesAsOrphans();
1245 schoenebeck 2611
1246     // the script's "init" event handler is only executed
1247     // once (when the script is loaded or reloaded)
1248     if (pEngineChannel->pScript && pEngineChannel->pScript->handlerInit) {
1249     RTList<ScriptEvent>::Iterator itScriptEvent =
1250     pEngineChannel->pScript->pEvents->allocAppend();
1251    
1252 schoenebeck 2614 itScriptEvent->cause.pEngineChannel = pEngineChannel;
1253 schoenebeck 2618 itScriptEvent->handlers[0] = pEngineChannel->pScript->handlerInit;
1254     itScriptEvent->handlers[1] = NULL;
1255 schoenebeck 2614
1256 schoenebeck 2611 VMExecStatus_t res = pScriptVM->exec(
1257     pEngineChannel->pScript->parserContext, &*itScriptEvent
1258     );
1259    
1260     pEngineChannel->pScript->pEvents->free(itScriptEvent);
1261     }
1262 iliev 2012 }
1263     }
1264    
1265     if (instrumentChanged) {
1266     //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
1267     ResetSuspendedRegions();
1268     }
1269     }
1270    
1271     /**
1272     * Render all 'normal' voices (that is voices which were not stolen in
1273     * this fragment) on the given engine channel.
1274     *
1275     * @param pEngineChannel - engine channel on which audio should be
1276     * rendered
1277     * @param Samples - amount of sample points to be rendered in
1278     * this audio fragment cycle
1279     */
1280     void RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {
1281     #if !CONFIG_PROCESS_MUTED_CHANNELS
1282     if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1283     #endif
1284    
1285     EngineChannelBase<V, R, I>* pChannel =
1286     static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
1287     pChannel->RenderActiveVoices(Samples);
1288    
1289     ActiveVoiceCountTemp += pEngineChannel->GetVoiceCount();
1290     }
1291    
1292     /**
1293     * Render all stolen voices (only voices which were stolen in this
1294     * fragment) on the given engine channel. Stolen voices are rendered
1295     * after all normal voices have been rendered; this is needed to render
1296     * audio of those voices which were selected for voice stealing until
1297     * the point were the stealing (that is the take over of the voice)
1298     * actually happened.
1299     *
1300     * @param pEngineChannel - engine channel on which audio should be
1301     * rendered
1302     * @param Samples - amount of sample points to be rendered in
1303     * this audio fragment cycle
1304     */
1305     void RenderStolenVoices(uint Samples) {
1306     RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();
1307     RTList<Event>::Iterator end = pVoiceStealingQueue->end();
1308     for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
1309     EngineChannelBase<V, R, I>* pEngineChannel =
1310     static_cast<EngineChannelBase<V, R, I>*>(itVoiceStealEvent->pEngineChannel);;
1311     if (!pEngineChannel->pInstrument) continue; // ignore if no instrument loaded
1312 schoenebeck 2879
1313 iliev 2012 PoolVoiceIterator itNewVoice =
1314     LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false, false);
1315     if (itNewVoice) {
1316 schoenebeck 2879 // usually there should already be a new Note object
1317     NoteIterator itNote = GetNotePool()->fromID(itVoiceStealEvent->Param.Note.ID);
1318     if (!itNote) { // should not happen, but just to be sure ...
1319     const note_id_t noteID = LaunchNewNote(pEngineChannel, &*itVoiceStealEvent);
1320     if (!noteID) {
1321     dmsg(1,("Engine: Voice stealing failed; No Note object and Note pool empty!\n"));
1322     continue;
1323     }
1324     itNote = GetNotePool()->fromID(noteID);
1325     }
1326     // move voice from whereever it was, to the new note's list of active voices
1327     itNewVoice = itNewVoice.moveToEndOf(itNote->pActiveVoices);
1328     // render audio of this new voice for the first time
1329 iliev 2012 itNewVoice->Render(Samples);
1330     if (itNewVoice->IsActive()) { // still active
1331     *(pEngineChannel->pRegionsInUse->allocAppend()) = itNewVoice->GetRegion();
1332     ActiveVoiceCountTemp++;
1333     pEngineChannel->SetVoiceCount(pEngineChannel->GetVoiceCount() + 1);
1334    
1335     if (itNewVoice->PlaybackState == Voice::playback_state_disk) {
1336     if (itNewVoice->DiskStreamRef.State != Stream::state_unused) {
1337     pEngineChannel->SetDiskStreamCount(pEngineChannel->GetDiskStreamCount() + 1);
1338     }
1339     }
1340     } else { // voice reached end, is now inactive
1341     pEngineChannel->FreeVoice(itNewVoice); // remove voice from the list of active voices
1342     }
1343     }
1344     else dmsg(1,("EngineBase: ERROR, voice stealing didn't work out!\n"));
1345    
1346     // we need to clear the key's event list explicitly here in case key was never active
1347     MidiKey* pKey = &pEngineChannel->pMIDIKeyInfo[itVoiceStealEvent->Param.Note.Key];
1348     pKey->VoiceTheftsQueued--;
1349     if (!pKey->Active && !pKey->VoiceTheftsQueued) pKey->pEvents->clear();
1350     }
1351     }
1352    
1353     /**
1354     * Free all keys which have turned inactive in this audio fragment, from
1355     * the list of active keys and clear all event lists on that engine
1356     * channel.
1357     *
1358     * @param pEngineChannel - engine channel to cleanup
1359     */
1360     void PostProcess(EngineChannel* pEngineChannel) {
1361     EngineChannelBase<V, R, I>* pChannel =
1362     static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
1363     pChannel->FreeAllInactiveKyes();
1364    
1365     // empty the engine channel's own event lists
1366 schoenebeck 2871 // (only events of the current audio fragment cycle)
1367     pChannel->ClearEventListsOfCurrentFragment();
1368 iliev 2012 }
1369    
1370 schoenebeck 2121 /**
1371     * Process MIDI control change events with hard coded behavior,
1372     * that is controllers whose behavior is defined independently
1373     * of the actual sampler engine type and instrument.
1374     *
1375     * @param pEngineChannel - engine channel on which the MIDI CC event was received
1376     * @param itControlChangeEvent - the actual MIDI CC event
1377     */
1378 iliev 2012 void ProcessHardcodedControllers (
1379     EngineChannel* pEngineChannel,
1380     Pool<Event>::Iterator& itControlChangeEvent
1381     ) {
1382     EngineChannelBase<V, R, I>* pChannel =
1383     static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
1384    
1385     switch (itControlChangeEvent->Param.CC.Controller) {
1386     case 5: { // portamento time
1387     pChannel->PortamentoTime = (float) itControlChangeEvent->Param.CC.Value / 127.0f * (float) CONFIG_PORTAMENTO_TIME_MAX + (float) CONFIG_PORTAMENTO_TIME_MIN;
1388     break;
1389     }
1390 schoenebeck 2121 case 6: { // data entry (currently only used for RPN and NRPN controllers)
1391     //dmsg(1,("DATA ENTRY %d\n", itControlChangeEvent->Param.CC.Value));
1392     if (pChannel->GetMidiRpnController() >= 0) { // RPN controller number was sent previously ...
1393     dmsg(4,("Guess it's an RPN ...\n"));
1394     if (pChannel->GetMidiRpnController() == 2) { // coarse tuning in half tones
1395     int transpose = (int) itControlChangeEvent->Param.CC.Value - 64;
1396     // limit to +- two octaves for now
1397     transpose = RTMath::Min(transpose, 24);
1398     transpose = RTMath::Max(transpose, -24);
1399     pChannel->GlobalTranspose = transpose;
1400     // workaround, so we won't have hanging notes
1401     pChannel->ReleaseAllVoices(itControlChangeEvent);
1402     }
1403     // to prevent other MIDI CC #6 messages to be misenterpreted as RPN controller data
1404     pChannel->ResetMidiRpnController();
1405     } else if (pChannel->GetMidiNrpnController() >= 0) { // NRPN controller number was sent previously ...
1406     dmsg(4,("Guess it's an NRPN ...\n"));
1407     const int NrpnCtrlMSB = pChannel->GetMidiNrpnController() >> 8;
1408     const int NrpnCtrlLSB = pChannel->GetMidiNrpnController() & 0xff;
1409     dmsg(4,("NRPN MSB=%d LSB=%d Data=%d\n", NrpnCtrlMSB, NrpnCtrlLSB, itControlChangeEvent->Param.CC.Value));
1410     switch (NrpnCtrlMSB) {
1411     case 0x1a: { // volume level of note (Roland GS NRPN)
1412     const uint note = NrpnCtrlLSB;
1413     const uint vol = itControlChangeEvent->Param.CC.Value;
1414     dmsg(4,("Note Volume NRPN received (note=%d,vol=%d).\n", note, vol));
1415     if (note < 128 && vol < 128)
1416     pChannel->pMIDIKeyInfo[note].Volume = VolumeCurve[vol];
1417     break;
1418     }
1419     case 0x1c: { // panpot of note (Roland GS NRPN)
1420     const uint note = NrpnCtrlLSB;
1421     const uint pan = itControlChangeEvent->Param.CC.Value;
1422     dmsg(4,("Note Pan NRPN received (note=%d,pan=%d).\n", note, pan));
1423     if (note < 128 && pan < 128) {
1424     pChannel->pMIDIKeyInfo[note].PanLeft = PanCurve[128 - pan];
1425     pChannel->pMIDIKeyInfo[note].PanRight = PanCurve[pan];
1426     }
1427     break;
1428     }
1429     case 0x1d: { // reverb send of note (Roland GS NRPN)
1430     const uint note = NrpnCtrlLSB;
1431     const float reverb = float(itControlChangeEvent->Param.CC.Value) / 127.0f;
1432 persson 2837 dmsg(4,("Note Reverb Send NRPN received (note=%d,send=%f).\n", note, reverb));
1433 schoenebeck 2121 if (note < 128)
1434     pChannel->pMIDIKeyInfo[note].ReverbSend = reverb;
1435     break;
1436     }
1437     case 0x1e: { // chorus send of note (Roland GS NRPN)
1438     const uint note = NrpnCtrlLSB;
1439     const float chorus = float(itControlChangeEvent->Param.CC.Value) / 127.0f;
1440 persson 2837 dmsg(4,("Note Chorus Send NRPN received (note=%d,send=%f).\n", note, chorus));
1441 schoenebeck 2121 if (note < 128)
1442     pChannel->pMIDIKeyInfo[note].ChorusSend = chorus;
1443     break;
1444     }
1445     }
1446     // to prevent other MIDI CC #6 messages to be misenterpreted as NRPN controller data
1447     pChannel->ResetMidiNrpnController();
1448 iliev 2012 }
1449     break;
1450     }
1451     case 7: { // volume
1452     //TODO: not sample accurate yet
1453     pChannel->MidiVolume = VolumeCurve[itControlChangeEvent->Param.CC.Value];
1454     pChannel->bStatusChanged = true; // engine channel status has changed, so set notify flag
1455     break;
1456     }
1457     case 10: { // panpot
1458     //TODO: not sample accurate yet
1459     pChannel->iLastPanRequest = itControlChangeEvent->Param.CC.Value;
1460     break;
1461     }
1462     case 64: { // sustain
1463     if (itControlChangeEvent->Param.CC.Value >= 64 && !pChannel->SustainPedal) {
1464     dmsg(4,("DAMPER (RIGHT) PEDAL DOWN\n"));
1465     pChannel->SustainPedal = true;
1466     pChannel->listeners.PreProcessSustainPedalDown();
1467    
1468     #if !CONFIG_PROCESS_MUTED_CHANNELS
1469     if (pEngineChannel->GetMute()) { // skip if sampler channel is muted
1470     pChannel->listeners.PostProcessSustainPedalDown();
1471     return;
1472     }
1473     #endif
1474    
1475     pChannel->ProcessSustainPedalDown(itControlChangeEvent);
1476     pChannel->listeners.PostProcessSustainPedalDown();
1477     }
1478     if (itControlChangeEvent->Param.CC.Value < 64 && pChannel->SustainPedal) {
1479     dmsg(4,("DAMPER (RIGHT) PEDAL UP\n"));
1480     pChannel->SustainPedal = false;
1481     pChannel->listeners.PreProcessSustainPedalUp();
1482    
1483     #if !CONFIG_PROCESS_MUTED_CHANNELS
1484     if (pChannel->GetMute()) { // skip if sampler channel is muted
1485     pChannel->listeners.PostProcessSustainPedalUp();
1486     return;
1487     }
1488     #endif
1489    
1490     pChannel->ProcessSustainPedalUp(itControlChangeEvent);
1491     pChannel->listeners.PostProcessSustainPedalUp();
1492     }
1493     break;
1494     }
1495     case 65: { // portamento on / off
1496     const bool bPortamento = itControlChangeEvent->Param.CC.Value >= 64;
1497     if (bPortamento != pChannel->PortamentoMode)
1498     KillAllVoices(pChannel, itControlChangeEvent);
1499     pChannel->PortamentoMode = bPortamento;
1500     break;
1501     }
1502     case 66: { // sostenuto
1503     if (itControlChangeEvent->Param.CC.Value >= 64 && !pChannel->SostenutoPedal) {
1504     dmsg(4,("SOSTENUTO (CENTER) PEDAL DOWN\n"));
1505     pChannel->SostenutoPedal = true;
1506     pChannel->listeners.PreProcessSostenutoPedalDown();
1507    
1508     #if !CONFIG_PROCESS_MUTED_CHANNELS
1509     if (pEngineChannel->GetMute()) { // skip if sampler channel is muted
1510     pChannel->listeners.PostProcessSostenutoPedalDown();
1511     return;
1512     }
1513     #endif
1514    
1515     pChannel->ProcessSostenutoPedalDown();
1516     pChannel->listeners.PostProcessSostenutoPedalDown();
1517     }
1518     if (itControlChangeEvent->Param.CC.Value < 64 && pChannel->SostenutoPedal) {
1519     dmsg(4,("SOSTENUTO (CENTER) PEDAL UP\n"));
1520     pChannel->SostenutoPedal = false;
1521     pChannel->listeners.PreProcessSostenutoPedalUp();
1522    
1523     #if !CONFIG_PROCESS_MUTED_CHANNELS
1524     if (pEngineChannel->GetMute()) { // skip if sampler channel is muted
1525     pChannel->listeners.PostProcessSostenutoPedalUp();
1526     return;
1527     }
1528     #endif
1529    
1530     pChannel->ProcessSostenutoPedalUp(itControlChangeEvent);
1531     pChannel->listeners.PostProcessSostenutoPedalUp();
1532     }
1533     break;
1534     }
1535 schoenebeck 2121 case 98: { // NRPN controller LSB
1536     dmsg(4,("NRPN LSB %d\n", itControlChangeEvent->Param.CC.Value));
1537     pEngineChannel->SetMidiNrpnControllerLsb(itControlChangeEvent->Param.CC.Value);
1538     break;
1539     }
1540     case 99: { // NRPN controller MSB
1541     dmsg(4,("NRPN MSB %d\n", itControlChangeEvent->Param.CC.Value));
1542     pEngineChannel->SetMidiNrpnControllerMsb(itControlChangeEvent->Param.CC.Value);
1543     break;
1544     }
1545 iliev 2012 case 100: { // RPN controller LSB
1546 schoenebeck 2121 dmsg(4,("RPN LSB %d\n", itControlChangeEvent->Param.CC.Value));
1547 iliev 2012 pEngineChannel->SetMidiRpnControllerLsb(itControlChangeEvent->Param.CC.Value);
1548     break;
1549     }
1550     case 101: { // RPN controller MSB
1551 schoenebeck 2121 dmsg(4,("RPN MSB %d\n", itControlChangeEvent->Param.CC.Value));
1552 iliev 2012 pEngineChannel->SetMidiRpnControllerMsb(itControlChangeEvent->Param.CC.Value);
1553     break;
1554     }
1555    
1556    
1557     // Channel Mode Messages
1558    
1559     case 120: { // all sound off
1560     KillAllVoices(pEngineChannel, itControlChangeEvent);
1561     break;
1562     }
1563     case 121: { // reset all controllers
1564     pChannel->ResetControllers();
1565     break;
1566     }
1567     case 123: { // all notes off
1568     #if CONFIG_PROCESS_ALL_NOTES_OFF
1569     pChannel->ReleaseAllVoices(itControlChangeEvent);
1570     #endif // CONFIG_PROCESS_ALL_NOTES_OFF
1571     break;
1572     }
1573     case 126: { // mono mode on
1574     if (!pChannel->SoloMode)
1575     KillAllVoices(pEngineChannel, itControlChangeEvent);
1576     pChannel->SoloMode = true;
1577     break;
1578     }
1579     case 127: { // poly mode on
1580     if (pChannel->SoloMode)
1581     KillAllVoices(pEngineChannel, itControlChangeEvent);
1582     pChannel->SoloMode = false;
1583     break;
1584     }
1585     }
1586     }
1587    
1588     virtual D* CreateDiskThread() = 0;
1589    
1590     /**
1591     * Assigns and triggers a new voice for the respective MIDI key.
1592     *
1593 schoenebeck 2871 * @param pEngineChannel - engine channel on which this event occurred on
1594 iliev 2012 * @param itNoteOnEvent - key, velocity and time stamp of the event
1595     */
1596     virtual void ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
1597     EngineChannelBase<V, R, I>* pChannel =
1598     static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
1599    
1600 schoenebeck 2879 const int key = itNoteOnEvent->Param.Note.Key;
1601     const int vel = itNoteOnEvent->Param.Note.Velocity;
1602     if (key < 0 || key > 127) return; // ignore event, key outside allowed key range
1603 iliev 2012
1604     MidiKey* pKey = &pChannel->pMIDIKeyInfo[key];
1605    
1606     pChannel->listeners.PreProcessNoteOn(key, vel);
1607     #if !CONFIG_PROCESS_MUTED_CHANNELS
1608     if (pEngineChannel->GetMute()) { // skip if sampler channel is muted
1609     pChannel->listeners.PostProcessNoteOn(key, vel);
1610     return;
1611     }
1612     #endif
1613    
1614     if (!pChannel->pInstrument) {
1615     pChannel->listeners.PostProcessNoteOn(key, vel);
1616     return; // ignore if no instrument loaded
1617     }
1618    
1619     // move note on event to the key's own event list
1620     RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
1621    
1622     // if Solo Mode then kill all already active voices
1623     if (pChannel->SoloMode) {
1624     Pool<uint>::Iterator itYoungestKey = pChannel->pActiveKeys->last();
1625     if (itYoungestKey) {
1626     const int iYoungestKey = *itYoungestKey;
1627     const MidiKey* pOtherKey = &pChannel->pMIDIKeyInfo[iYoungestKey];
1628     if (pOtherKey->Active) {
1629     // get final portamento position of currently active voice
1630     if (pChannel->PortamentoMode) {
1631 schoenebeck 2879 NoteIterator itNote = pOtherKey->pActiveNotes->last();
1632     if (itNote) {
1633     VoiceIterator itVoice = itNote->pActiveVoices->last();
1634     if (itVoice) itVoice->UpdatePortamentoPos(itNoteOnEventOnKeyList);
1635     }
1636 iliev 2012 }
1637     // kill all voices on the (other) key
1638 schoenebeck 2879 for (NoteIterator itNote = pOtherKey->pActiveNotes->first(); itNote; ++itNote) {
1639     VoiceIterator itVoiceToBeKilled = itNote->pActiveVoices->first();
1640     VoiceIterator end = itNote->pActiveVoices->end();
1641     for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
1642     if (!(itVoiceToBeKilled->Type & Voice::type_release_trigger))
1643     itVoiceToBeKilled->Kill(itNoteOnEventOnKeyList);
1644     }
1645 iliev 2012 }
1646     }
1647     }
1648     // set this key as 'currently active solo key'
1649     pChannel->SoloKey = key;
1650     }
1651    
1652     pChannel->ProcessKeySwitchChange(key);
1653    
1654     pKey->KeyPressed = true; // the MIDI key was now pressed down
1655 schoenebeck 2613 pChannel->KeyDown[key] = true; // just used as built-in %KEY_DOWN script variable
1656 iliev 2012 pKey->Velocity = itNoteOnEventOnKeyList->Param.Note.Velocity;
1657     pKey->NoteOnTime = FrameTime + itNoteOnEventOnKeyList->FragmentPos(); // will be used to calculate note length
1658    
1659     // cancel release process of voices on this key if needed
1660     if (pKey->Active && !pChannel->SustainPedal) {
1661     RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
1662     if (itCancelReleaseEvent) {
1663     *itCancelReleaseEvent = *itNoteOnEventOnKeyList; // copy event
1664     itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type
1665     }
1666     else dmsg(1,("Event pool emtpy!\n"));
1667     }
1668    
1669     TriggerNewVoices(pEngineChannel, itNoteOnEventOnKeyList);
1670    
1671     // if neither a voice was spawned or postponed then remove note on event from key again
1672     if (!pKey->Active && !pKey->VoiceTheftsQueued)
1673     pKey->pEvents->free(itNoteOnEventOnKeyList);
1674    
1675     if (!pChannel->SoloMode || pChannel->PortamentoPos < 0.0f) pChannel->PortamentoPos = (float) key;
1676 persson 2043 if (pKey->pRoundRobinIndex) {
1677     (*pKey->pRoundRobinIndex)++; // counter specific for the key or region
1678     pChannel->RoundRobinIndex++; // common counter for the channel
1679     }
1680 iliev 2012 pChannel->listeners.PostProcessNoteOn(key, vel);
1681     }
1682    
1683     /**
1684     * Allocate and trigger new voice(s) for the key.
1685     */
1686     virtual void TriggerNewVoices (
1687     EngineChannel* pEngineChannel,
1688     RTList<Event>::Iterator& itNoteOnEvent,
1689     bool HandleKeyGroupConflicts = true
1690     ) = 0;
1691    
1692     /**
1693     * Allocate and trigger release voice(s) for the key.
1694     */
1695     virtual void TriggerReleaseVoices (
1696     EngineChannel* pEngineChannel,
1697     RTList<Event>::Iterator& itNoteOffEvent
1698     ) = 0;
1699    
1700     /**
1701     * Releases the voices on the given key if sustain pedal is not pressed.
1702     * If sustain is pressed, the release of the note will be postponed until
1703     * sustain pedal will be released or voice turned inactive by itself (e.g.
1704     * due to completion of sample playback).
1705     *
1706 schoenebeck 2871 * @param pEngineChannel - engine channel on which this event occurred on
1707 iliev 2012 * @param itNoteOffEvent - key, velocity and time stamp of the event
1708     */
1709     virtual void ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {
1710     EngineChannelBase<V, R, I>* pChannel = static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
1711    
1712 schoenebeck 2879 const int iKey = itNoteOffEvent->Param.Note.Key;
1713     const int vel = itNoteOffEvent->Param.Note.Velocity;
1714     if (iKey < 0 || iKey > 127) return; // ignore event, key outside allowed key range
1715 iliev 2012
1716     MidiKey* pKey = &pChannel->pMIDIKeyInfo[iKey];
1717    
1718     pChannel->listeners.PreProcessNoteOff(iKey, vel);
1719    
1720     #if !CONFIG_PROCESS_MUTED_CHANNELS
1721     if (pEngineChannel->GetMute()) { // skip if sampler channel is muted
1722     pChannel->listeners.PostProcessNoteOff(iKey, vel);
1723     return;
1724     }
1725     #endif
1726    
1727     pKey->KeyPressed = false; // the MIDI key was now released
1728 schoenebeck 2613 pChannel->KeyDown[iKey] = false; // just used as built-in %KEY_DOWN script variable
1729 iliev 2012
1730     // move event to the key's own event list
1731     RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
1732    
1733     bool bShouldRelease = pKey->Active && pChannel->ShouldReleaseVoice(itNoteOffEventOnKeyList->Param.Note.Key);
1734    
1735     // in case Solo Mode is enabled, kill all voices on this key and respawn a voice on the highest pressed key (if any)
1736     if (pChannel->SoloMode && pChannel->pInstrument) { //TODO: this feels like too much code just for handling solo mode :P
1737     bool bOtherKeysPressed = false;
1738     if (iKey == pChannel->SoloKey) {
1739     pChannel->SoloKey = -1;
1740     // if there's still a key pressed down, respawn a voice (group) on the highest key
1741     for (int i = 127; i > 0; i--) {
1742     MidiKey* pOtherKey = &pChannel->pMIDIKeyInfo[i];
1743     if (pOtherKey->KeyPressed) {
1744     bOtherKeysPressed = true;
1745     // make the other key the new 'currently active solo key'
1746     pChannel->SoloKey = i;
1747     // get final portamento position of currently active voice
1748     if (pChannel->PortamentoMode) {
1749 schoenebeck 2879 NoteIterator itNote = pKey->pActiveNotes->first();
1750     VoiceIterator itVoice = itNote->pActiveVoices->first();
1751 iliev 2012 if (itVoice) itVoice->UpdatePortamentoPos(itNoteOffEventOnKeyList);
1752     }
1753     // create a pseudo note on event
1754     RTList<Event>::Iterator itPseudoNoteOnEvent = pOtherKey->pEvents->allocAppend();
1755     if (itPseudoNoteOnEvent) {
1756     // copy event
1757     *itPseudoNoteOnEvent = *itNoteOffEventOnKeyList;
1758     // transform event to a note on event
1759     itPseudoNoteOnEvent->Type = Event::type_note_on;
1760     itPseudoNoteOnEvent->Param.Note.Key = i;
1761     itPseudoNoteOnEvent->Param.Note.Velocity = pOtherKey->Velocity;
1762 schoenebeck 2879 // assign a new note to this note-on event
1763     if (LaunchNewNote(pChannel, &*itPseudoNoteOnEvent)) {
1764     // allocate and trigger new voice(s) for the other key
1765     TriggerNewVoices(pChannel, itPseudoNoteOnEvent, false);
1766     }
1767 iliev 2012 // if neither a voice was spawned or postponed then remove note on event from key again
1768     if (!pOtherKey->Active && !pOtherKey->VoiceTheftsQueued)
1769     pOtherKey->pEvents->free(itPseudoNoteOnEvent);
1770    
1771     } else dmsg(1,("Could not respawn voice, no free event left\n"));
1772     break; // done
1773     }
1774     }
1775     }
1776     if (bOtherKeysPressed) {
1777     if (pKey->Active) { // kill all voices on this key
1778     bShouldRelease = false; // no need to release, as we kill it here
1779 schoenebeck 2879 for (NoteIterator itNote = pKey->pActiveNotes->first(); itNote; ++itNote) {
1780     VoiceIterator itVoiceToBeKilled = itNote->pActiveVoices->first();
1781     VoiceIterator end = itNote->pActiveVoices->end();
1782     for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
1783     if (!(itVoiceToBeKilled->Type & Voice::type_release_trigger))
1784     itVoiceToBeKilled->Kill(itNoteOffEventOnKeyList);
1785     }
1786 iliev 2012 }
1787     }
1788     } else pChannel->PortamentoPos = -1.0f;
1789     }
1790    
1791     // if no solo mode (the usual case) or if solo mode and no other key pressed, then release voices on this key if needed
1792     if (bShouldRelease) {
1793     itNoteOffEventOnKeyList->Type = Event::type_release; // transform event type
1794     // spawn release triggered voice(s) if needed
1795 schoenebeck 2927 ProcessReleaseTrigger(pChannel, itNoteOffEventOnKeyList, pKey);
1796 iliev 2012 }
1797    
1798     // if neither a voice was spawned or postponed on this key then remove note off event from key again
1799     if (!pKey->Active && !pKey->VoiceTheftsQueued)
1800     pKey->pEvents->free(itNoteOffEventOnKeyList);
1801    
1802     pChannel->listeners.PostProcessNoteOff(iKey, vel);
1803     }
1804    
1805     /**
1806 schoenebeck 2927 * Called on sustain pedal up events to check and if required,
1807     * launch release trigger voices on the respective active key.
1808     *
1809     * @param pEngineChannel - engine channel on which this event occurred on
1810     * @param itEvent - release trigger event (contains note number)
1811     */
1812     virtual void ProcessReleaseTrigger(EngineChannel* pEngineChannel, RTList<Event>::Iterator& itEvent) OVERRIDE {
1813     EngineChannelBase<V, R, I>* pChannel = static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
1814    
1815     const int iKey = itEvent->Param.Note.Key;
1816     if (iKey < 0 || iKey > 127) return; // ignore event, key outside allowed key range
1817    
1818     MidiKey* pKey = &pChannel->pMIDIKeyInfo[iKey];
1819    
1820     ProcessReleaseTrigger(pChannel, itEvent, pKey);
1821     }
1822    
1823     /**
1824     * Called on note-off and sustain pedal up events to check and if
1825     * required, launch release trigger voices on the respective active
1826     * key.
1827     *
1828     * @param pEngineChannel - engine channel on which this event occurred on
1829     * @param itEvent - note off event / release trigger event
1830     * @param pKey - key on which the release trigger voices shall be spawned
1831     */
1832     inline void ProcessReleaseTrigger(EngineChannelBase<V, R, I>* pChannel, RTList<Event>::Iterator& itEvent, MidiKey* pKey) {
1833     // spawn release triggered voice(s) if needed
1834     if (pKey->ReleaseTrigger && pChannel->pInstrument) {
1835     // assign a new note to this release event
1836     if (LaunchNewNote(pChannel, &*itEvent)) {
1837     // allocate and trigger new release voice(s)
1838     TriggerReleaseVoices(pChannel, itEvent);
1839     }
1840     pKey->ReleaseTrigger = false;
1841     }
1842     }
1843    
1844     /**
1845 schoenebeck 2931 * Called on note synthesis parameter change events. These are
1846     * internal events caused by calling built-in real-time instrument
1847     * script functions like change_vol(), change_pitch(), etc.
1848     *
1849     * This method performs two tasks:
1850     *
1851     * - It converts the event's relative values changes (Deltas) to
1852     * the respective final new synthesis parameter value (AbsValue),
1853     * for that particular moment of the event that is.
1854     *
1855     * - It moves the individual events to the Note's own event list
1856     * (or actually to the event list of the MIDI key), so that
1857     * voices can process those events sample accurately.
1858     *
1859     * @param pEngineChannel - engine channel on which this event occurred on
1860     * @param itEvent - note synthesis parameter change event
1861     */
1862     virtual void ProcessNoteSynthParam(EngineChannel* pEngineChannel, RTList<Event>::Iterator& itEvent) OVERRIDE {
1863     EngineChannelBase<V, R, I>* pChannel = static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
1864    
1865     NoteBase* pNote = pChannel->pEngine->NoteByID( itEvent->Param.NoteSynthParam.NoteID );
1866     if (!pNote || pNote->hostKey < 0 || pNote->hostKey >= 128) return;
1867    
1868     const bool& relative = itEvent->Param.NoteSynthParam.Relative;
1869    
1870     switch (itEvent->Param.NoteSynthParam.Type) {
1871     case Event::synth_param_volume:
1872     if (relative)
1873     pNote->Override.Volume *= itEvent->Param.NoteSynthParam.Delta;
1874     else
1875     pNote->Override.Volume = itEvent->Param.NoteSynthParam.Delta;
1876     itEvent->Param.NoteSynthParam.AbsValue = pNote->Override.Volume;
1877     break;
1878     case Event::synth_param_pitch:
1879     if (relative)
1880     pNote->Override.Pitch *= itEvent->Param.NoteSynthParam.Delta;
1881     else
1882     pNote->Override.Pitch = itEvent->Param.NoteSynthParam.Delta;
1883     itEvent->Param.NoteSynthParam.AbsValue = pNote->Override.Pitch;
1884     break;
1885     case Event::synth_param_pan:
1886     if (relative) {
1887     pNote->Override.Pan = RTMath::RelativeSummedAvg(pNote->Override.Pan, itEvent->Param.NoteSynthParam.Delta, ++pNote->Override.PanSources);
1888     } else {
1889     pNote->Override.Pan = itEvent->Param.NoteSynthParam.Delta;
1890     pNote->Override.PanSources = 1; // only relevant on subsequent change_pan() instrument script calls on same note with 'relative' argument being set
1891     }
1892     itEvent->Param.NoteSynthParam.AbsValue = pNote->Override.Pan;
1893     break;
1894 schoenebeck 2935 case Event::synth_param_cutoff:
1895     pNote->Override.Cutoff = itEvent->Param.NoteSynthParam.AbsValue = itEvent->Param.NoteSynthParam.Delta;
1896     break;
1897     case Event::synth_param_resonance:
1898     pNote->Override.Resonance = itEvent->Param.NoteSynthParam.AbsValue = itEvent->Param.NoteSynthParam.Delta;
1899     break;
1900 schoenebeck 2931 }
1901    
1902     // move note parameter event to its MIDI key
1903     MidiKey* pKey = &pChannel->pMIDIKeyInfo[pNote->hostKey];
1904     itEvent.moveToEndOf(pKey->pEvents);
1905     }
1906    
1907     /**
1908 iliev 2012 * Reset all voices and disk thread and clear input event queue and all
1909     * control and status variables. This method is protected by a mutex.
1910     */
1911     virtual void ResetInternal() {
1912 persson 2427 LockGuard lock(ResetInternalMutex);
1913 iliev 2012
1914     // make sure that the engine does not get any sysex messages
1915     // while it's reseting
1916     bool sysexDisabled = MidiInputPort::RemoveSysexListener(this);
1917     SetVoiceCount(0);
1918     ActiveVoiceCountMax = 0;
1919    
1920     // reset voice stealing parameters
1921     pVoiceStealingQueue->clear();
1922     itLastStolenVoice = VoiceIterator();
1923     itLastStolenVoiceGlobally = VoiceIterator();
1924 schoenebeck 2879 itLastStolenNote = NoteIterator();
1925     itLastStolenNoteGlobally = NoteIterator();
1926 iliev 2012 iuiLastStolenKey = RTList<uint>::Iterator();
1927     iuiLastStolenKeyGlobally = RTList<uint>::Iterator();
1928     pLastStolenChannel = NULL;
1929    
1930 schoenebeck 2879 // reset all notes
1931     pNotePool->clear();
1932     for (NoteIterator itNote = pNotePool->allocAppend(); itNote;
1933     itNote = pNotePool->allocAppend())
1934     {
1935     itNote->reset();
1936     }
1937     pNotePool->clear();
1938    
1939 iliev 2012 // reset all voices
1940 schoenebeck 2879 pVoicePool->clear();
1941 iliev 2012 for (VoiceIterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
1942     iterVoice->Reset();
1943     }
1944     pVoicePool->clear();
1945    
1946 schoenebeck 2871 // reset all engine channels
1947     for (int i = 0; i < engineChannels.size(); i++) {
1948     AbstractEngineChannel* pEngineChannel =
1949     static_cast<AbstractEngineChannel*>(engineChannels[i]);
1950     pEngineChannel->ResetInternal(false/*don't reset engine*/);
1951     }
1952    
1953 iliev 2012 // reset disk thread
1954     if (pDiskThread) pDiskThread->Reset();
1955    
1956     // delete all input events
1957     pEventQueue->init();
1958     pSysexBuffer->init();
1959     if (sysexDisabled) MidiInputPort::AddSysexListener(this);
1960     }
1961    
1962     /**
1963     * Kills all voices on an engine channel as soon as possible. Voices
1964     * won't get into release state, their volume level will be ramped down
1965     * as fast as possible.
1966     *
1967     * @param pEngineChannel - engine channel on which all voices should be killed
1968     * @param itKillEvent - event which caused this killing of all voices
1969     */
1970     virtual void KillAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itKillEvent) {
1971     EngineChannelBase<V, R, I>* pChannel = static_cast<EngineChannelBase<V, R, I>*>(pEngineChannel);
1972     int count = pChannel->KillAllVoices(itKillEvent);
1973     VoiceSpawnsLeft -= count; //FIXME: just a temporary workaround, we should check the cause in StealVoice() instead
1974     }
1975    
1976     /**
1977     * Allocates and triggers a new voice. This method will usually be
1978     * called by the ProcessNoteOn() method and by the voices itself
1979     * (e.g. to spawn further voices on the same key for layered sounds).
1980     *
1981 schoenebeck 2871 * @param pEngineChannel - engine channel on which this event occurred on
1982 iliev 2012 * @param itNoteOnEvent - key, velocity and time stamp of the event
1983     * @param iLayer - layer index for the new voice (optional - only
1984     * in case of layered sounds of course)
1985     * @param ReleaseTriggerVoice - if new voice is a release triggered voice
1986     * (optional, default = false)
1987     * @param VoiceStealing - if voice stealing should be performed
1988     * when there is no free voice
1989     * (optional, default = true)
1990     * @param HandleKeyGroupConflicts - if voices should be killed due to a
1991     * key group conflict
1992     * @returns pointer to new voice or NULL if there was no free voice or
1993     * if the voice wasn't triggered (for example when no region is
1994     * defined for the given key).
1995     */
1996     virtual PoolVoiceIterator LaunchVoice (
1997     EngineChannel* pEngineChannel,
1998     Pool<Event>::Iterator& itNoteOnEvent,
1999     int iLayer,
2000     bool ReleaseTriggerVoice,
2001     bool VoiceStealing,
2002     bool HandleKeyGroupConflicts
2003     ) = 0;
2004    
2005 iliev 2015 virtual int GetMinFadeOutSamples() { return MinFadeOutSamples; }
2006    
2007 iliev 2027 int InitNewVoice (
2008     EngineChannelBase<V, R, I>* pChannel,
2009     R* pRegion,
2010     Pool<Event>::Iterator& itNoteOnEvent,
2011     Voice::type_t VoiceType,
2012     int iLayer,
2013     int iKeyGroup,
2014     bool ReleaseTriggerVoice,
2015     bool VoiceStealing,
2016     typename Pool<V>::Iterator& itNewVoice
2017     ) {
2018     int key = itNoteOnEvent->Param.Note.Key;
2019     typename MidiKeyboardManager<V>::MidiKey* pKey = &pChannel->pMIDIKeyInfo[key];
2020     if (itNewVoice) {
2021     // launch the new voice
2022     if (itNewVoice->Trigger(pChannel, itNoteOnEvent, pChannel->Pitch, pRegion, VoiceType, iKeyGroup) < 0) {
2023     dmsg(4,("Voice not triggered\n"));
2024 schoenebeck 2879 GetVoicePool()->free(itNewVoice);
2025 iliev 2027 }
2026     else { // on success
2027     --VoiceSpawnsLeft;
2028     if (!pKey->Active) { // mark as active key
2029     pKey->Active = true;
2030     pKey->itSelf = pChannel->pActiveKeys->allocAppend();
2031     *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
2032     }
2033 persson 2115 if (itNewVoice->Type & Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)
2034 iliev 2027 return 0; // success
2035     }
2036     }
2037     else if (VoiceStealing) {
2038     // try to steal one voice
2039     int result = StealVoice(pChannel, itNoteOnEvent);
2040     if (!result) { // voice stolen successfully
2041     // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died
2042     RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();
2043     if (itStealEvent) {
2044     *itStealEvent = *itNoteOnEvent; // copy event
2045     itStealEvent->Param.Note.Layer = iLayer;
2046     itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;
2047     pKey->VoiceTheftsQueued++;
2048     }
2049     else dmsg(1,("Voice stealing queue full!\n"));
2050     }
2051     }
2052    
2053     return -1;
2054     }
2055 schoenebeck 2448
2056     /**
2057     * Checks whether scale tuning setting has been changed since last
2058     * time this method was called, if yes, it recalculates the pitch
2059     * for all active voices.
2060     */
2061     void ProcessScaleTuningChange() {
2062     const bool changed = ScaleTuningChanged.readAndReset();
2063     if (!changed) return;
2064    
2065     for (int i = 0; i < engineChannels.size(); i++) {
2066     EngineChannelBase<V, R, I>* channel =
2067     static_cast<EngineChannelBase<V, R, I>*>(engineChannels[i]);
2068     channel->OnScaleTuningChanged();
2069     }
2070     }
2071 iliev 2027
2072 iliev 2012 private:
2073 schoenebeck 2879 Pool< Note<V> >* pNotePool;
2074     Pool<note_id_t> noteIDPool;
2075 iliev 2012 Pool<V>* pVoicePool; ///< Contains all voices that can be activated.
2076     Pool<RR*> SuspendedRegions;
2077     Mutex SuspendedRegionsMutex;
2078     Condition SuspensionChangeOngoing;
2079     RR* pPendingRegionSuspension;
2080     RR* pPendingRegionResumption;
2081     int iPendingStreamDeletions;
2082     };
2083    
2084     template <class V, class RR, class R, class D, class IM, class I>
2085     IM EngineBase<V, RR, R, D, IM, I>::instruments;
2086    
2087     } // namespace LinuxSampler
2088    
2089     #endif /* __LS_ENGINEBASE_H__ */
2090    

  ViewVC Help
Powered by ViewVC