/[svn]/linuxsampler/trunk/src/engines/gig/Engine.cpp
ViewVC logotype

Annotation of /linuxsampler/trunk/src/engines/gig/Engine.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1037 - (hide annotations) (download)
Tue Jan 23 20:03:22 2007 UTC (17 years, 2 months ago) by schoenebeck
File size: 81550 byte(s)
* bugfix regarding FX Sends: when more than one sampler channel used FX
  sends, only the audio signal of the last sampler channel made it into the
  final output signal
* fixed small autoconf compilation issue on certain systems (complained
  about missing AM_PATH_ARTS macro)

1 schoenebeck 53 /***************************************************************************
2     * *
3     * LinuxSampler - modular, streaming capable sampler *
4     * *
5 capela 1012 * Copyright (C) 2003,2004 by Benno Senoner and Christian Schoenebeck *
6     * Copyright (C) 2005-2007 Christian Schoenebeck *
7 schoenebeck 53 * *
8     * This program is free software; you can redistribute it and/or modify *
9     * it under the terms of the GNU General Public License as published by *
10     * the Free Software Foundation; either version 2 of the License, or *
11     * (at your option) any later version. *
12     * *
13     * This program is distributed in the hope that it will be useful, *
14     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16     * GNU General Public License for more details. *
17     * *
18     * You should have received a copy of the GNU General Public License *
19     * along with this program; if not, write to the Free Software *
20     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
21     * MA 02111-1307 USA *
22     ***************************************************************************/
23    
24     #include <sstream>
25     #include "DiskThread.h"
26     #include "Voice.h"
27 schoenebeck 285 #include "EGADSR.h"
28 schoenebeck 420 #include "../EngineFactory.h"
29 schoenebeck 53
30     #include "Engine.h"
31    
32     namespace LinuxSampler { namespace gig {
33    
34 schoenebeck 411 InstrumentResourceManager Engine::instruments;
35 schoenebeck 53
36 schoenebeck 411 std::map<AudioOutputDevice*,Engine*> Engine::engines;
37    
38 schoenebeck 412 /**
39     * Get a gig::Engine object for the given gig::EngineChannel and the
40     * given AudioOutputDevice. All engine channels which are connected to
41     * the same audio output device will use the same engine instance. This
42     * method will be called by a gig::EngineChannel whenever it's
43     * connecting to a audio output device.
44     *
45     * @param pChannel - engine channel which acquires an engine object
46     * @param pDevice - the audio output device \a pChannel is connected to
47     */
48 schoenebeck 411 Engine* Engine::AcquireEngine(LinuxSampler::gig::EngineChannel* pChannel, AudioOutputDevice* pDevice) {
49 schoenebeck 412 Engine* pEngine = NULL;
50     // check if there's already an engine for the given audio output device
51 schoenebeck 411 if (engines.count(pDevice)) {
52 schoenebeck 412 dmsg(4,("Using existing gig::Engine.\n"));
53 persson 438 pEngine = engines[pDevice];
54 schoenebeck 412 } else { // create a new engine (and disk thread) instance for the given audio output device
55     dmsg(4,("Creating new gig::Engine.\n"));
56 schoenebeck 420 pEngine = (Engine*) EngineFactory::Create("gig");
57 schoenebeck 411 pEngine->Connect(pDevice);
58 persson 438 engines[pDevice] = pEngine;
59 schoenebeck 411 }
60 schoenebeck 412 // register engine channel to the engine instance
61 schoenebeck 460 pEngine->engineChannels.add(pChannel);
62     // remember index in the ArrayList
63     pChannel->iEngineIndexSelf = pEngine->engineChannels.size() - 1;
64 schoenebeck 412 dmsg(4,("This gig::Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));
65 schoenebeck 411 return pEngine;
66     }
67    
68 schoenebeck 412 /**
69     * Once an engine channel is disconnected from an audio output device,
70     * it wil immediately call this method to unregister itself from the
71     * engine instance and if that engine instance is not used by any other
72     * engine channel anymore, then that engine instance will be destroyed.
73     *
74     * @param pChannel - engine channel which wants to disconnect from it's
75     * engine instance
76     * @param pDevice - audio output device \a pChannel was connected to
77     */
78 schoenebeck 411 void Engine::FreeEngine(LinuxSampler::gig::EngineChannel* pChannel, AudioOutputDevice* pDevice) {
79 schoenebeck 412 dmsg(4,("Disconnecting EngineChannel from gig::Engine.\n"));
80 schoenebeck 411 Engine* pEngine = engines[pDevice];
81 schoenebeck 412 // unregister EngineChannel from the Engine instance
82     pEngine->engineChannels.remove(pChannel);
83     // if the used Engine instance is not used anymore, then destroy it
84     if (pEngine->engineChannels.empty()) {
85     pDevice->Disconnect(pEngine);
86     engines.erase(pDevice);
87     delete pEngine;
88     dmsg(4,("Destroying gig::Engine.\n"));
89     }
90     else dmsg(4,("This gig::Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));
91 schoenebeck 411 }
92    
93 schoenebeck 473 /**
94     * Constructor
95     */
96 schoenebeck 53 Engine::Engine() {
97     pAudioOutputDevice = NULL;
98     pDiskThread = NULL;
99     pEventGenerator = NULL;
100 schoenebeck 970 pSysexBuffer = new RingBuffer<uint8_t,false>(CONFIG_SYSEX_BUFFER_SIZE, 0);
101     pEventQueue = new RingBuffer<Event,false>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);
102 schoenebeck 554 pEventPool = new Pool<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT);
103     pVoicePool = new Pool<Voice>(CONFIG_MAX_VOICES);
104 schoenebeck 271 pVoiceStealingQueue = new RTList<Event>(pEventPool);
105 schoenebeck 460 pGlobalEvents = new RTList<Event>(pEventPool);
106 schoenebeck 271 for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
107     iterVoice->SetEngine(this);
108 schoenebeck 53 }
109     pVoicePool->clear();
110    
111     ResetInternal();
112 schoenebeck 659 ResetScaleTuning();
113 schoenebeck 53 }
114    
115 schoenebeck 473 /**
116     * Destructor
117     */
118 schoenebeck 53 Engine::~Engine() {
119 persson 846 MidiInputPort::RemoveSysexListener(this);
120 schoenebeck 53 if (pDiskThread) {
121 senkov 329 dmsg(1,("Stopping disk thread..."));
122 schoenebeck 53 pDiskThread->StopThread();
123     delete pDiskThread;
124 senkov 329 dmsg(1,("OK\n"));
125 schoenebeck 53 }
126     if (pEventQueue) delete pEventQueue;
127     if (pEventPool) delete pEventPool;
128 schoenebeck 411 if (pVoicePool) {
129     pVoicePool->clear();
130     delete pVoicePool;
131     }
132 schoenebeck 53 if (pEventGenerator) delete pEventGenerator;
133 schoenebeck 250 if (pVoiceStealingQueue) delete pVoiceStealingQueue;
134 schoenebeck 411 if (pSysexBuffer) delete pSysexBuffer;
135 capela 1012 Unregister();
136 schoenebeck 53 }
137    
138     void Engine::Enable() {
139     dmsg(3,("gig::Engine: enabling\n"));
140     EngineDisabled.PushAndUnlock(false, 2); // set condition object 'EngineDisabled' to false (wait max. 2s)
141 schoenebeck 64 dmsg(3,("gig::Engine: enabled (val=%d)\n", EngineDisabled.GetUnsafe()));
142 schoenebeck 53 }
143    
144     void Engine::Disable() {
145     dmsg(3,("gig::Engine: disabling\n"));
146     bool* pWasDisabled = EngineDisabled.PushAndUnlock(true, 2); // wait max. 2s
147     if (!pWasDisabled) dmsg(3,("gig::Engine warning: Timeout waiting to disable engine.\n"));
148     }
149    
150     void Engine::DisableAndLock() {
151     dmsg(3,("gig::Engine: disabling\n"));
152     bool* pWasDisabled = EngineDisabled.Push(true, 2); // wait max. 2s
153     if (!pWasDisabled) dmsg(3,("gig::Engine warning: Timeout waiting to disable engine.\n"));
154     }
155    
156     /**
157     * Reset all voices and disk thread and clear input event queue and all
158     * control and status variables.
159     */
160     void Engine::Reset() {
161     DisableAndLock();
162     ResetInternal();
163 schoenebeck 659 ResetScaleTuning();
164 schoenebeck 53 Enable();
165     }
166    
167     /**
168     * Reset all voices and disk thread and clear input event queue and all
169 persson 846 * control and status variables. This method is protected by a mutex.
170 schoenebeck 53 */
171     void Engine::ResetInternal() {
172 persson 846 ResetInternalMutex.Lock();
173    
174     // make sure that the engine does not get any sysex messages
175     // while it's reseting
176     bool sysexDisabled = MidiInputPort::RemoveSysexListener(this);
177 schoenebeck 53 ActiveVoiceCount = 0;
178     ActiveVoiceCountMax = 0;
179    
180 schoenebeck 250 // reset voice stealing parameters
181     pVoiceStealingQueue->clear();
182 schoenebeck 649 itLastStolenVoice = RTList<Voice>::Iterator();
183     itLastStolenVoiceGlobally = RTList<Voice>::Iterator();
184     iuiLastStolenKey = RTList<uint>::Iterator();
185     iuiLastStolenKeyGlobally = RTList<uint>::Iterator();
186     pLastStolenChannel = NULL;
187 schoenebeck 250
188 schoenebeck 53 // reset all voices
189 schoenebeck 271 for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
190     iterVoice->Reset();
191 schoenebeck 53 }
192     pVoicePool->clear();
193    
194     // reset disk thread
195     if (pDiskThread) pDiskThread->Reset();
196    
197     // delete all input events
198     pEventQueue->init();
199 schoenebeck 775 pSysexBuffer->init();
200 persson 846 if (sysexDisabled) MidiInputPort::AddSysexListener(this);
201     ResetInternalMutex.Unlock();
202 persson 438 }
203 schoenebeck 53
204 schoenebeck 473 /**
205 schoenebeck 659 * Reset to normal, chromatic scale (means equal tempered).
206     */
207     void Engine::ResetScaleTuning() {
208     memset(&ScaleTuning[0], 0x00, 12);
209     }
210    
211     /**
212 schoenebeck 473 * Connect this engine instance with the given audio output device.
213     * This method will be called when an Engine instance is created.
214     * All of the engine's data structures which are dependant to the used
215     * audio output device / driver will be (re)allocated and / or
216     * adjusted appropriately.
217     *
218     * @param pAudioOut - audio output device to connect to
219     */
220 schoenebeck 53 void Engine::Connect(AudioOutputDevice* pAudioOut) {
221     pAudioOutputDevice = pAudioOut;
222    
223     ResetInternal();
224    
225     // inform audio driver for the need of two channels
226     try {
227     pAudioOutputDevice->AcquireChannels(2); // gig engine only stereo
228     }
229     catch (AudioOutputException e) {
230     String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();
231 schoenebeck 880 throw Exception(msg);
232 schoenebeck 53 }
233 persson 438
234 schoenebeck 460 this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle();
235     this->SampleRate = pAudioOutputDevice->SampleRate();
236 schoenebeck 225
237 schoenebeck 285 // FIXME: audio drivers with varying fragment sizes might be a problem here
238 schoenebeck 554 MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * CONFIG_EG_MIN_RELEASE_TIME) - 1;
239 schoenebeck 688 if (MaxFadeOutPos < 0) {
240     std::cerr << "gig::Engine: WARNING, CONFIG_EG_MIN_RELEASE_TIME "
241     << "too big for current audio fragment size & sampling rate! "
242 schoenebeck 690 << "May lead to click sounds if voice stealing chimes in!\n" << std::flush;
243 schoenebeck 688 // force volume ramp downs at the beginning of each fragment
244     MaxFadeOutPos = 0;
245     // lower minimum release time
246     const float minReleaseTime = (float) MaxSamplesPerCycle / (float) SampleRate;
247     for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
248 schoenebeck 738 iterVoice->EG1.CalculateFadeOutCoeff(minReleaseTime, SampleRate);
249 schoenebeck 688 }
250     pVoicePool->clear();
251     }
252 schoenebeck 285
253 schoenebeck 53 // (re)create disk thread
254     if (this->pDiskThread) {
255 senkov 329 dmsg(1,("Stopping disk thread..."));
256 schoenebeck 53 this->pDiskThread->StopThread();
257     delete this->pDiskThread;
258 senkov 329 dmsg(1,("OK\n"));
259 schoenebeck 53 }
260 schoenebeck 554 this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << CONFIG_MAX_PITCH) << 1) + 6); //FIXME: assuming stereo
261 schoenebeck 53 if (!pDiskThread) {
262     dmsg(0,("gig::Engine new diskthread = NULL\n"));
263     exit(EXIT_FAILURE);
264     }
265    
266 schoenebeck 271 for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
267     iterVoice->pDiskThread = this->pDiskThread;
268 schoenebeck 53 dmsg(3,("d"));
269     }
270     pVoicePool->clear();
271    
272     // (re)create event generator
273     if (pEventGenerator) delete pEventGenerator;
274     pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
275    
276     dmsg(1,("Starting disk thread..."));
277     pDiskThread->StartThread();
278     dmsg(1,("OK\n"));
279    
280 schoenebeck 271 for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
281     if (!iterVoice->pDiskThread) {
282 schoenebeck 53 dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));
283     exit(EXIT_FAILURE);
284     }
285     }
286     }
287    
288 schoenebeck 473 /**
289     * Clear all engine global event lists.
290     */
291 schoenebeck 412 void Engine::ClearEventLists() {
292 schoenebeck 460 pGlobalEvents->clear();
293 schoenebeck 412 }
294    
295 schoenebeck 53 /**
296 schoenebeck 460 * Copy all events from the engine's global input queue buffer to the
297     * engine's internal event list. This will be done at the beginning of
298     * each audio cycle (that is each RenderAudio() call) to distinguish
299     * all global events which have to be processed in the current audio
300     * cycle. These events are usually just SysEx messages. Every
301     * EngineChannel has it's own input event queue buffer and event list
302     * to handle common events like NoteOn, NoteOff and ControlChange
303     * events.
304 schoenebeck 412 *
305 schoenebeck 460 * @param Samples - number of sample points to be processed in the
306     * current audio cycle
307 schoenebeck 412 */
308 schoenebeck 460 void Engine::ImportEvents(uint Samples) {
309 schoenebeck 970 RingBuffer<Event,false>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
310 schoenebeck 412 Event* pEvent;
311     while (true) {
312     // get next event from input event queue
313     if (!(pEvent = eventQueueReader.pop())) break;
314     // if younger event reached, ignore that and all subsequent ones for now
315     if (pEvent->FragmentPos() >= Samples) {
316     eventQueueReader--;
317     dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
318     pEvent->ResetFragmentPos();
319     break;
320     }
321     // copy event to internal event list
322 schoenebeck 460 if (pGlobalEvents->poolIsEmpty()) {
323 schoenebeck 412 dmsg(1,("Event pool emtpy!\n"));
324     break;
325     }
326 schoenebeck 460 *pGlobalEvents->allocAppend() = *pEvent;
327 schoenebeck 412 }
328     eventQueueReader.free(); // free all copied events from input queue
329 persson 438 }
330 schoenebeck 412
331     /**
332 schoenebeck 924 * Let this engine proceed to render the given amount of sample points.
333     * The engine will iterate through all engine channels and render audio
334     * for each engine channel independently. The calculated audio data of
335     * all voices of each engine channel will be placed into the audio sum
336     * buffers of the respective audio output device, connected to the
337     * respective engine channel.
338 schoenebeck 53 *
339     * @param Samples - number of sample points to be rendered
340     * @returns 0 on success
341     */
342 schoenebeck 412 int Engine::RenderAudio(uint Samples) {
343 schoenebeck 947 dmsg(7,("RenderAudio(Samples=%d)\n", Samples));
344 schoenebeck 53
345 schoenebeck 412 // return if engine disabled
346 schoenebeck 53 if (EngineDisabled.Pop()) {
347     dmsg(5,("gig::Engine: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));
348     return 0;
349     }
350    
351 schoenebeck 293 // update time of start and end of this audio fragment (as events' time stamps relate to this)
352     pEventGenerator->UpdateFragmentTime(Samples);
353    
354 schoenebeck 663 // We only allow a maximum of CONFIG_MAX_VOICES voices to be spawned
355     // in each audio fragment. All subsequent request for spawning new
356     // voices in the same audio fragment will be ignored.
357     VoiceSpawnsLeft = CONFIG_MAX_VOICES;
358    
359 schoenebeck 412 // get all events from the engine's global input event queue which belong to the current fragment
360     // (these are usually just SysEx messages)
361 schoenebeck 460 ImportEvents(Samples);
362 schoenebeck 412
363     // process engine global events (these are currently only MIDI System Exclusive messages)
364     {
365 schoenebeck 460 RTList<Event>::Iterator itEvent = pGlobalEvents->first();
366     RTList<Event>::Iterator end = pGlobalEvents->end();
367 schoenebeck 412 for (; itEvent != end; ++itEvent) {
368     switch (itEvent->Type) {
369     case Event::type_sysex:
370     dmsg(5,("Engine: Sysex received\n"));
371     ProcessSysex(itEvent);
372     break;
373     }
374     }
375 schoenebeck 53 }
376 schoenebeck 412
377     // reset internal voice counter (just for statistic of active voices)
378     ActiveVoiceCountTemp = 0;
379    
380 schoenebeck 466 // handle events on all engine channels
381 schoenebeck 460 for (int i = 0; i < engineChannels.size(); i++) {
382     if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
383     ProcessEvents(engineChannels[i], Samples);
384 schoenebeck 466 }
385    
386     // render all 'normal', active voices on all engine channels
387     for (int i = 0; i < engineChannels.size(); i++) {
388     if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
389 schoenebeck 460 RenderActiveVoices(engineChannels[i], Samples);
390 schoenebeck 412 }
391    
392 schoenebeck 460 // now that all ordinary voices on ALL engine channels are rendered, render new stolen voices
393     RenderStolenVoices(Samples);
394    
395 schoenebeck 1001 // handle audio routing for engine channels with FX sends
396     for (int i = 0; i < engineChannels.size(); i++) {
397     if (engineChannels[i]->fxSends.empty()) continue; // ignore if no FX sends
398     RouteAudio(engineChannels[i], Samples);
399     }
400    
401 schoenebeck 460 // handle cleanup on all engine channels for the next audio fragment
402     for (int i = 0; i < engineChannels.size(); i++) {
403     if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
404     PostProcess(engineChannels[i]);
405     }
406    
407    
408     // empty the engine's event list for the next audio fragment
409     ClearEventLists();
410    
411     // reset voice stealing for the next audio fragment
412     pVoiceStealingQueue->clear();
413    
414 schoenebeck 412 // just some statistics about this engine instance
415     ActiveVoiceCount = ActiveVoiceCountTemp;
416     if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;
417    
418 persson 630 FrameTime += Samples;
419    
420 schoenebeck 412 return 0;
421     }
422    
423 schoenebeck 473 /**
424     * Dispatch and handle all events in this audio fragment for the given
425     * engine channel.
426     *
427     * @param pEngineChannel - engine channel on which events should be
428     * processed
429     * @param Samples - amount of sample points to be processed in
430     * this audio fragment cycle
431     */
432 schoenebeck 460 void Engine::ProcessEvents(EngineChannel* pEngineChannel, uint Samples) {
433 schoenebeck 412 // get all events from the engine channels's input event queue which belong to the current fragment
434     // (these are the common events like NoteOn, NoteOff, ControlChange, etc.)
435 schoenebeck 460 pEngineChannel->ImportEvents(Samples);
436 schoenebeck 53
437     // process events
438 schoenebeck 271 {
439 schoenebeck 460 RTList<Event>::Iterator itEvent = pEngineChannel->pEvents->first();
440     RTList<Event>::Iterator end = pEngineChannel->pEvents->end();
441 schoenebeck 271 for (; itEvent != end; ++itEvent) {
442     switch (itEvent->Type) {
443     case Event::type_note_on:
444     dmsg(5,("Engine: Note on received\n"));
445 schoenebeck 412 ProcessNoteOn((EngineChannel*)itEvent->pEngineChannel, itEvent);
446 schoenebeck 271 break;
447     case Event::type_note_off:
448     dmsg(5,("Engine: Note off received\n"));
449 schoenebeck 412 ProcessNoteOff((EngineChannel*)itEvent->pEngineChannel, itEvent);
450 schoenebeck 271 break;
451     case Event::type_control_change:
452     dmsg(5,("Engine: MIDI CC received\n"));
453 schoenebeck 412 ProcessControlChange((EngineChannel*)itEvent->pEngineChannel, itEvent);
454 schoenebeck 271 break;
455     case Event::type_pitchbend:
456     dmsg(5,("Engine: Pitchbend received\n"));
457 schoenebeck 412 ProcessPitchbend((EngineChannel*)itEvent->pEngineChannel, itEvent);
458 schoenebeck 271 break;
459     }
460 schoenebeck 53 }
461     }
462 schoenebeck 649
463     // reset voice stealing for the next engine channel (or next audio fragment)
464     itLastStolenVoice = RTList<Voice>::Iterator();
465     itLastStolenVoiceGlobally = RTList<Voice>::Iterator();
466     iuiLastStolenKey = RTList<uint>::Iterator();
467     iuiLastStolenKeyGlobally = RTList<uint>::Iterator();
468     pLastStolenChannel = NULL;
469 schoenebeck 460 }
470 schoenebeck 53
471 schoenebeck 473 /**
472     * Render all 'normal' voices (that is voices which were not stolen in
473     * this fragment) on the given engine channel.
474     *
475     * @param pEngineChannel - engine channel on which audio should be
476     * rendered
477     * @param Samples - amount of sample points to be rendered in
478     * this audio fragment cycle
479     */
480 schoenebeck 460 void Engine::RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {
481 iliev 716 #if !CONFIG_PROCESS_MUTED_CHANNELS
482 schoenebeck 705 if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
483 iliev 716 #endif
484 schoenebeck 705
485 schoenebeck 460 RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
486     RTList<uint>::Iterator end = pEngineChannel->pActiveKeys->end();
487     while (iuiKey != end) { // iterate through all active keys
488     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
489     ++iuiKey;
490 schoenebeck 53
491 schoenebeck 460 RTList<Voice>::Iterator itVoice = pKey->pActiveVoices->first();
492     RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
493     for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
494     // now render current voice
495     itVoice->Render(Samples);
496     if (itVoice->IsActive()) ActiveVoiceCountTemp++; // still active
497     else { // voice reached end, is now inactive
498     FreeVoice(pEngineChannel, itVoice); // remove voice from the list of active voices
499 schoenebeck 53 }
500     }
501     }
502 schoenebeck 460 }
503 schoenebeck 53
504 schoenebeck 473 /**
505     * Render all stolen voices (only voices which were stolen in this
506     * fragment) on the given engine channel. Stolen voices are rendered
507     * after all normal voices have been rendered; this is needed to render
508     * audio of those voices which were selected for voice stealing until
509     * the point were the stealing (that is the take over of the voice)
510     * actually happened.
511     *
512     * @param pEngineChannel - engine channel on which audio should be
513     * rendered
514     * @param Samples - amount of sample points to be rendered in
515     * this audio fragment cycle
516     */
517 schoenebeck 460 void Engine::RenderStolenVoices(uint Samples) {
518     RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();
519     RTList<Event>::Iterator end = pVoiceStealingQueue->end();
520     for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
521     EngineChannel* pEngineChannel = (EngineChannel*) itVoiceStealEvent->pEngineChannel;
522     Pool<Voice>::Iterator itNewVoice =
523 schoenebeck 668 LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false, false);
524 schoenebeck 460 if (itNewVoice) {
525     itNewVoice->Render(Samples);
526     if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active
527     else { // voice reached end, is now inactive
528     FreeVoice(pEngineChannel, itNewVoice); // remove voice from the list of active voices
529 schoenebeck 250 }
530     }
531 schoenebeck 460 else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));
532 schoenebeck 473
533     // we need to clear the key's event list explicitly here in case key was never active
534     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itVoiceStealEvent->Param.Note.Key];
535     pKey->VoiceTheftsQueued--;
536     if (!pKey->Active && !pKey->VoiceTheftsQueued) pKey->pEvents->clear();
537 schoenebeck 250 }
538 schoenebeck 460 }
539 schoenebeck 250
540 schoenebeck 473 /**
541 schoenebeck 1001 * Will be called in case the respective engine channel sports FX send
542     * channels. In this particular case, engine channel local buffers are
543     * used to render and mix all voices to. This method is responsible for
544     * copying the audio data from those local buffers to the master audio
545     * output channels as well as to the FX send audio output channels with
546     * their respective FX send levels.
547     *
548     * @param pEngineChannel - engine channel from which audio should be
549     * routed
550     * @param Samples - amount of sample points to be routed in
551     * this audio fragment cycle
552     */
553     void Engine::RouteAudio(EngineChannel* pEngineChannel, uint Samples) {
554     // route master signal
555     {
556     AudioChannel* pDstL = pAudioOutputDevice->Channel(pEngineChannel->AudioDeviceChannelLeft);
557     AudioChannel* pDstR = pAudioOutputDevice->Channel(pEngineChannel->AudioDeviceChannelRight);
558 schoenebeck 1037 pEngineChannel->pChannelLeft->MixTo(pDstL, Samples);
559     pEngineChannel->pChannelRight->MixTo(pDstR, Samples);
560 schoenebeck 1001 }
561     // route FX send signal
562     {
563     for (int iFxSend = 0; iFxSend < pEngineChannel->GetFxSendCount(); iFxSend++) {
564     FxSend* pFxSend = pEngineChannel->GetFxSend(iFxSend);
565     // left channel
566     const int iDstL = pFxSend->DestinationChannel(0);
567     if (iDstL < 0) {
568     dmsg(1,("Engine::RouteAudio() Error: invalid FX send (L) destination channel"));
569     } else {
570     AudioChannel* pDstL = pAudioOutputDevice->Channel(iDstL);
571     if (!pDstL) {
572     dmsg(1,("Engine::RouteAudio() Error: invalid FX send (L) destination channel"));
573 schoenebeck 1037 } else pEngineChannel->pChannelLeft->MixTo(pDstL, Samples, pFxSend->Level());
574 schoenebeck 1001 }
575     // right channel
576     const int iDstR = pFxSend->DestinationChannel(1);
577     if (iDstR < 0) {
578     dmsg(1,("Engine::RouteAudio() Error: invalid FX send (R) destination channel"));
579     } else {
580     AudioChannel* pDstR = pAudioOutputDevice->Channel(iDstR);
581     if (!pDstR) {
582     dmsg(1,("Engine::RouteAudio() Error: invalid FX send (R) destination channel"));
583 schoenebeck 1037 } else pEngineChannel->pChannelRight->MixTo(pDstR, Samples, pFxSend->Level());
584 schoenebeck 1001 }
585     }
586     }
587     // reset buffers with silence (zero out) for the next audio cycle
588     pEngineChannel->pChannelLeft->Clear();
589     pEngineChannel->pChannelRight->Clear();
590     }
591    
592     /**
593 schoenebeck 473 * Free all keys which have turned inactive in this audio fragment, from
594     * the list of active keys and clear all event lists on that engine
595     * channel.
596     *
597     * @param pEngineChannel - engine channel to cleanup
598     */
599 schoenebeck 460 void Engine::PostProcess(EngineChannel* pEngineChannel) {
600 schoenebeck 287 // free all keys which have no active voices left
601     {
602 schoenebeck 411 RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
603     RTList<uint>::Iterator end = pEngineChannel->pActiveKeys->end();
604 schoenebeck 287 while (iuiKey != end) { // iterate through all active keys
605 schoenebeck 411 midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
606 schoenebeck 287 ++iuiKey;
607 schoenebeck 411 if (pKey->pActiveVoices->isEmpty()) FreeKey(pEngineChannel, pKey);
608 schoenebeck 554 #if CONFIG_DEVMODE
609 schoenebeck 563 else { // just a sanity check for debugging
610 schoenebeck 287 RTList<Voice>::Iterator itVoice = pKey->pActiveVoices->first();
611     RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
612     for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
613     if (itVoice->itKillEvent) {
614     dmsg(1,("gig::Engine: ERROR, killed voice survived !!!\n"));
615     }
616     }
617     }
618 schoenebeck 554 #endif // CONFIG_DEVMODE
619 schoenebeck 287 }
620     }
621 schoenebeck 460
622     // empty the engine channel's own event lists
623     pEngineChannel->ClearEventLists();
624 schoenebeck 412 }
625 schoenebeck 287
626 schoenebeck 53 /**
627 schoenebeck 244 * Will be called by the MIDI input device whenever a MIDI system
628     * exclusive message has arrived.
629     *
630     * @param pData - pointer to sysex data
631     * @param Size - lenght of sysex data (in bytes)
632     */
633     void Engine::SendSysex(void* pData, uint Size) {
634 schoenebeck 246 Event event = pEventGenerator->CreateEvent();
635     event.Type = Event::type_sysex;
636     event.Param.Sysex.Size = Size;
637 schoenebeck 412 event.pEngineChannel = NULL; // as Engine global event
638 schoenebeck 244 if (pEventQueue->write_space() > 0) {
639     if (pSysexBuffer->write_space() >= Size) {
640     // copy sysex data to input buffer
641     uint toWrite = Size;
642     uint8_t* pPos = (uint8_t*) pData;
643     while (toWrite) {
644     const uint writeNow = RTMath::Min(toWrite, pSysexBuffer->write_space_to_end());
645     pSysexBuffer->write(pPos, writeNow);
646     toWrite -= writeNow;
647     pPos += writeNow;
648    
649     }
650     // finally place sysex event into input event queue
651     pEventQueue->push(&event);
652     }
653 schoenebeck 554 else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,CONFIG_SYSEX_BUFFER_SIZE));
654 schoenebeck 244 }
655     else dmsg(1,("Engine: Input event queue full!"));
656     }
657    
658     /**
659 schoenebeck 53 * Assigns and triggers a new voice for the respective MIDI key.
660     *
661 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
662 schoenebeck 271 * @param itNoteOnEvent - key, velocity and time stamp of the event
663 schoenebeck 53 */
664 schoenebeck 411 void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
665 iliev 716 #if !CONFIG_PROCESS_MUTED_CHANNELS
666     if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
667     #endif
668 persson 438
669 schoenebeck 354 const int key = itNoteOnEvent->Param.Note.Key;
670 schoenebeck 829 midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];
671 schoenebeck 354
672 schoenebeck 829 // move note on event to the key's own event list
673     RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
674    
675     // if Solo Mode then kill all already active voices
676     if (pEngineChannel->SoloMode) {
677     Pool<uint>::Iterator itYoungestKey = pEngineChannel->pActiveKeys->last();
678     if (itYoungestKey) {
679     const int iYoungestKey = *itYoungestKey;
680     const midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[iYoungestKey];
681     if (pOtherKey->Active) {
682     // get final portamento position of currently active voice
683     if (pEngineChannel->PortamentoMode) {
684     RTList<Voice>::Iterator itVoice = pOtherKey->pActiveVoices->last();
685     if (itVoice) itVoice->UpdatePortamentoPos(itNoteOnEventOnKeyList);
686     }
687     // kill all voices on the (other) key
688     RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
689     RTList<Voice>::Iterator end = pOtherKey->pActiveVoices->end();
690     for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
691     if (itVoiceToBeKilled->Type != Voice::type_release_trigger)
692     itVoiceToBeKilled->Kill(itNoteOnEventOnKeyList);
693     }
694     }
695     }
696     // set this key as 'currently active solo key'
697     pEngineChannel->SoloKey = key;
698     }
699    
700 schoenebeck 354 // Change key dimension value if key is in keyswitching area
701 schoenebeck 411 {
702     const ::gig::Instrument* pInstrument = pEngineChannel->pInstrument;
703     if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high)
704 persson 865 pEngineChannel->CurrentKeyDimension = float(key - pInstrument->DimensionKeyRange.low) /
705 schoenebeck 411 (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);
706     }
707 schoenebeck 354
708 schoenebeck 53 pKey->KeyPressed = true; // the MIDI key was now pressed down
709 schoenebeck 829 pKey->Velocity = itNoteOnEventOnKeyList->Param.Note.Velocity;
710     pKey->NoteOnTime = FrameTime + itNoteOnEventOnKeyList->FragmentPos(); // will be used to calculate note length
711 schoenebeck 53
712     // cancel release process of voices on this key if needed
713 schoenebeck 411 if (pKey->Active && !pEngineChannel->SustainPedal) {
714 schoenebeck 271 RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
715     if (itCancelReleaseEvent) {
716 schoenebeck 829 *itCancelReleaseEvent = *itNoteOnEventOnKeyList; // copy event
717 schoenebeck 271 itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type
718 schoenebeck 239 }
719     else dmsg(1,("Event pool emtpy!\n"));
720 schoenebeck 53 }
721    
722 schoenebeck 460 // allocate and trigger new voice(s) for the key
723     {
724     // first, get total amount of required voices (dependant on amount of layers)
725     ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOnEventOnKeyList->Param.Note.Key);
726     if (pRegion) {
727     int voicesRequired = pRegion->Layers;
728     // now launch the required amount of voices
729     for (int i = 0; i < voicesRequired; i++)
730 schoenebeck 668 LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true, true);
731 schoenebeck 460 }
732     }
733 persson 438
734 schoenebeck 473 // if neither a voice was spawned or postponed then remove note on event from key again
735     if (!pKey->Active && !pKey->VoiceTheftsQueued)
736     pKey->pEvents->free(itNoteOnEventOnKeyList);
737    
738 schoenebeck 829 if (!pEngineChannel->SoloMode || pEngineChannel->PortamentoPos < 0.0f) pEngineChannel->PortamentoPos = (float) key;
739 persson 438 pKey->RoundRobinIndex++;
740 schoenebeck 53 }
741    
742     /**
743     * Releases the voices on the given key if sustain pedal is not pressed.
744     * If sustain is pressed, the release of the note will be postponed until
745     * sustain pedal will be released or voice turned inactive by itself (e.g.
746     * due to completion of sample playback).
747     *
748 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
749 schoenebeck 271 * @param itNoteOffEvent - key, velocity and time stamp of the event
750 schoenebeck 53 */
751 schoenebeck 411 void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {
752 iliev 716 #if !CONFIG_PROCESS_MUTED_CHANNELS
753 schoenebeck 705 if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
754 iliev 716 #endif
755 schoenebeck 705
756 schoenebeck 829 const int iKey = itNoteOffEvent->Param.Note.Key;
757     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[iKey];
758 schoenebeck 53 pKey->KeyPressed = false; // the MIDI key was now released
759    
760 schoenebeck 829 // move event to the key's own event list
761     RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
762 schoenebeck 242
763 schoenebeck 829 bool bShouldRelease = pKey->Active && ShouldReleaseVoice(pEngineChannel, itNoteOffEventOnKeyList->Param.Note.Key);
764 schoenebeck 271
765 schoenebeck 829 // in case Solo Mode is enabled, kill all voices on this key and respawn a voice on the highest pressed key (if any)
766     if (pEngineChannel->SoloMode) { //TODO: this feels like too much code just for handling solo mode :P
767     bool bOtherKeysPressed = false;
768     if (iKey == pEngineChannel->SoloKey) {
769     pEngineChannel->SoloKey = -1;
770     // if there's still a key pressed down, respawn a voice (group) on the highest key
771     for (int i = 127; i > 0; i--) {
772     midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[i];
773     if (pOtherKey->KeyPressed) {
774     bOtherKeysPressed = true;
775     // make the other key the new 'currently active solo key'
776     pEngineChannel->SoloKey = i;
777     // get final portamento position of currently active voice
778     if (pEngineChannel->PortamentoMode) {
779     RTList<Voice>::Iterator itVoice = pKey->pActiveVoices->first();
780     if (itVoice) itVoice->UpdatePortamentoPos(itNoteOffEventOnKeyList);
781     }
782     // create a pseudo note on event
783     RTList<Event>::Iterator itPseudoNoteOnEvent = pOtherKey->pEvents->allocAppend();
784     if (itPseudoNoteOnEvent) {
785     // copy event
786     *itPseudoNoteOnEvent = *itNoteOffEventOnKeyList;
787     // transform event to a note on event
788     itPseudoNoteOnEvent->Type = Event::type_note_on;
789     itPseudoNoteOnEvent->Param.Note.Key = i;
790     itPseudoNoteOnEvent->Param.Note.Velocity = pOtherKey->Velocity;
791     // allocate and trigger new voice(s) for the other key
792     {
793     // first, get total amount of required voices (dependant on amount of layers)
794     ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(i);
795     if (pRegion) {
796     int voicesRequired = pRegion->Layers;
797     // now launch the required amount of voices
798     for (int iLayer = 0; iLayer < voicesRequired; iLayer++)
799     LaunchVoice(pEngineChannel, itPseudoNoteOnEvent, iLayer, false, true, false);
800     }
801     }
802     // if neither a voice was spawned or postponed then remove note on event from key again
803     if (!pOtherKey->Active && !pOtherKey->VoiceTheftsQueued)
804     pOtherKey->pEvents->free(itPseudoNoteOnEvent);
805    
806     } else dmsg(1,("Could not respawn voice, no free event left\n"));
807     break; // done
808     }
809     }
810     }
811     if (bOtherKeysPressed) {
812     if (pKey->Active) { // kill all voices on this key
813     bShouldRelease = false; // no need to release, as we kill it here
814     RTList<Voice>::Iterator itVoiceToBeKilled = pKey->pActiveVoices->first();
815     RTList<Voice>::Iterator end = pKey->pActiveVoices->end();
816     for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
817     if (itVoiceToBeKilled->Type != Voice::type_release_trigger)
818     itVoiceToBeKilled->Kill(itNoteOffEventOnKeyList);
819     }
820     }
821     } else pEngineChannel->PortamentoPos = -1.0f;
822     }
823    
824     // if no solo mode (the usual case) or if solo mode and no other key pressed, then release voices on this key if needed
825     if (bShouldRelease) {
826     itNoteOffEventOnKeyList->Type = Event::type_release; // transform event type
827    
828 persson 497 // spawn release triggered voice(s) if needed
829 persson 630 if (pKey->ReleaseTrigger) {
830 persson 497 // first, get total amount of required voices (dependant on amount of layers)
831     ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOffEventOnKeyList->Param.Note.Key);
832     if (pRegion) {
833     int voicesRequired = pRegion->Layers;
834 persson 630
835     // MIDI note-on velocity is used instead of note-off velocity
836     itNoteOffEventOnKeyList->Param.Note.Velocity = pKey->Velocity;
837    
838 persson 497 // now launch the required amount of voices
839     for (int i = 0; i < voicesRequired; i++)
840 schoenebeck 668 LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, i, true, false, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
841 persson 497 }
842     pKey->ReleaseTrigger = false;
843 schoenebeck 460 }
844 schoenebeck 829 }
845 persson 497
846 schoenebeck 829 // if neither a voice was spawned or postponed on this key then remove note off event from key again
847     if (!pKey->Active && !pKey->VoiceTheftsQueued)
848     pKey->pEvents->free(itNoteOffEventOnKeyList);
849 schoenebeck 53 }
850    
851     /**
852 schoenebeck 738 * Moves pitchbend event from the general (input) event list to the engine
853     * channel's event list. It will actually processed later by the
854     * respective voice.
855 schoenebeck 53 *
856 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
857 schoenebeck 271 * @param itPitchbendEvent - absolute pitch value and time stamp of the event
858 schoenebeck 53 */
859 schoenebeck 411 void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {
860     pEngineChannel->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value
861 schoenebeck 53 }
862    
863     /**
864 schoenebeck 233 * Allocates and triggers a new voice. This method will usually be
865     * called by the ProcessNoteOn() method and by the voices itself
866     * (e.g. to spawn further voices on the same key for layered sounds).
867     *
868 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
869 schoenebeck 271 * @param itNoteOnEvent - key, velocity and time stamp of the event
870 schoenebeck 242 * @param iLayer - layer index for the new voice (optional - only
871     * in case of layered sounds of course)
872     * @param ReleaseTriggerVoice - if new voice is a release triggered voice
873     * (optional, default = false)
874 schoenebeck 250 * @param VoiceStealing - if voice stealing should be performed
875     * when there is no free voice
876     * (optional, default = true)
877 schoenebeck 668 * @param HandleKeyGroupConflicts - if voices should be killed due to a
878     * key group conflict
879 schoenebeck 250 * @returns pointer to new voice or NULL if there was no free voice or
880 schoenebeck 354 * if the voice wasn't triggered (for example when no region is
881     * defined for the given key).
882 schoenebeck 233 */
883 schoenebeck 668 Pool<Voice>::Iterator Engine::LaunchVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing, bool HandleKeyGroupConflicts) {
884 schoenebeck 669 int MIDIKey = itNoteOnEvent->Param.Note.Key;
885     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[MIDIKey];
886     ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(MIDIKey);
887 schoenebeck 233
888 schoenebeck 668 // if nothing defined for this key
889     if (!pRegion) return Pool<Voice>::Iterator(); // nothing to do
890    
891 schoenebeck 669 // only mark the first voice of a layered voice (group) to be in a
892     // key group, so the layered voices won't kill each other
893     int iKeyGroup = (iLayer == 0 && !ReleaseTriggerVoice) ? pRegion->KeyGroup : 0;
894    
895 schoenebeck 668 // handle key group (a.k.a. exclusive group) conflicts
896     if (HandleKeyGroupConflicts) {
897     if (iKeyGroup) { // if this voice / key belongs to a key group
898     uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[iKeyGroup];
899     if (*ppKeyGroup) { // if there's already an active key in that key group
900     midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[**ppKeyGroup];
901     // kill all voices on the (other) key
902     RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
903     RTList<Voice>::Iterator end = pOtherKey->pActiveVoices->end();
904     for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
905     if (itVoiceToBeKilled->Type != Voice::type_release_trigger) {
906     itVoiceToBeKilled->Kill(itNoteOnEvent);
907     --VoiceSpawnsLeft; //FIXME: just a hack, we should better check in StealVoice() if the voice was killed due to key conflict
908     }
909     }
910     }
911     }
912     }
913    
914 schoenebeck 669 Voice::type_t VoiceType = Voice::type_normal;
915    
916     // get current dimension values to select the right dimension region
917     //TODO: for stolen voices this dimension region selection block is processed twice, this should be changed
918     //FIXME: controller values for selecting the dimension region here are currently not sample accurate
919     uint DimValues[8] = { 0 };
920     for (int i = pRegion->Dimensions - 1; i >= 0; i--) {
921     switch (pRegion->pDimensionDefinitions[i].dimension) {
922     case ::gig::dimension_samplechannel:
923     DimValues[i] = 0; //TODO: we currently ignore this dimension
924     break;
925     case ::gig::dimension_layer:
926     DimValues[i] = iLayer;
927     break;
928     case ::gig::dimension_velocity:
929     DimValues[i] = itNoteOnEvent->Param.Note.Velocity;
930     break;
931     case ::gig::dimension_channelaftertouch:
932 persson 903 DimValues[i] = pEngineChannel->ControllerTable[128];
933 schoenebeck 669 break;
934     case ::gig::dimension_releasetrigger:
935     VoiceType = (ReleaseTriggerVoice) ? Voice::type_release_trigger : (!iLayer) ? Voice::type_release_trigger_required : Voice::type_normal;
936     DimValues[i] = (uint) ReleaseTriggerVoice;
937     break;
938     case ::gig::dimension_keyboard:
939 persson 865 DimValues[i] = (uint) (pEngineChannel->CurrentKeyDimension * pRegion->pDimensionDefinitions[i].zones);
940 schoenebeck 669 break;
941     case ::gig::dimension_roundrobin:
942     DimValues[i] = (uint) pEngineChannel->pMIDIKeyInfo[MIDIKey].RoundRobinIndex; // incremented for each note on
943     break;
944     case ::gig::dimension_random:
945     RandomSeed = RandomSeed * 1103515245 + 12345; // classic pseudo random number generator
946     DimValues[i] = (uint) RandomSeed >> (32 - pRegion->pDimensionDefinitions[i].bits); // highest bits are most random
947     break;
948     case ::gig::dimension_modwheel:
949     DimValues[i] = pEngineChannel->ControllerTable[1];
950     break;
951     case ::gig::dimension_breath:
952     DimValues[i] = pEngineChannel->ControllerTable[2];
953     break;
954     case ::gig::dimension_foot:
955     DimValues[i] = pEngineChannel->ControllerTable[4];
956     break;
957     case ::gig::dimension_portamentotime:
958     DimValues[i] = pEngineChannel->ControllerTable[5];
959     break;
960     case ::gig::dimension_effect1:
961     DimValues[i] = pEngineChannel->ControllerTable[12];
962     break;
963     case ::gig::dimension_effect2:
964     DimValues[i] = pEngineChannel->ControllerTable[13];
965     break;
966     case ::gig::dimension_genpurpose1:
967     DimValues[i] = pEngineChannel->ControllerTable[16];
968     break;
969     case ::gig::dimension_genpurpose2:
970     DimValues[i] = pEngineChannel->ControllerTable[17];
971     break;
972     case ::gig::dimension_genpurpose3:
973     DimValues[i] = pEngineChannel->ControllerTable[18];
974     break;
975     case ::gig::dimension_genpurpose4:
976     DimValues[i] = pEngineChannel->ControllerTable[19];
977     break;
978     case ::gig::dimension_sustainpedal:
979     DimValues[i] = pEngineChannel->ControllerTable[64];
980     break;
981     case ::gig::dimension_portamento:
982     DimValues[i] = pEngineChannel->ControllerTable[65];
983     break;
984     case ::gig::dimension_sostenutopedal:
985     DimValues[i] = pEngineChannel->ControllerTable[66];
986     break;
987     case ::gig::dimension_softpedal:
988     DimValues[i] = pEngineChannel->ControllerTable[67];
989     break;
990     case ::gig::dimension_genpurpose5:
991     DimValues[i] = pEngineChannel->ControllerTable[80];
992     break;
993     case ::gig::dimension_genpurpose6:
994     DimValues[i] = pEngineChannel->ControllerTable[81];
995     break;
996     case ::gig::dimension_genpurpose7:
997     DimValues[i] = pEngineChannel->ControllerTable[82];
998     break;
999     case ::gig::dimension_genpurpose8:
1000     DimValues[i] = pEngineChannel->ControllerTable[83];
1001     break;
1002     case ::gig::dimension_effect1depth:
1003     DimValues[i] = pEngineChannel->ControllerTable[91];
1004     break;
1005     case ::gig::dimension_effect2depth:
1006     DimValues[i] = pEngineChannel->ControllerTable[92];
1007     break;
1008     case ::gig::dimension_effect3depth:
1009     DimValues[i] = pEngineChannel->ControllerTable[93];
1010     break;
1011     case ::gig::dimension_effect4depth:
1012     DimValues[i] = pEngineChannel->ControllerTable[94];
1013     break;
1014     case ::gig::dimension_effect5depth:
1015     DimValues[i] = pEngineChannel->ControllerTable[95];
1016     break;
1017     case ::gig::dimension_none:
1018     std::cerr << "gig::Engine::LaunchVoice() Error: dimension=none\n" << std::flush;
1019     break;
1020     default:
1021     std::cerr << "gig::Engine::LaunchVoice() Error: Unknown dimension\n" << std::flush;
1022     }
1023     }
1024     ::gig::DimensionRegion* pDimRgn = pRegion->GetDimensionRegionByValue(DimValues);
1025    
1026     // no need to continue if sample is silent
1027     if (!pDimRgn->pSample || !pDimRgn->pSample->SamplesTotal) return Pool<Voice>::Iterator();
1028    
1029 schoenebeck 233 // allocate a new voice for the key
1030 schoenebeck 271 Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
1031     if (itNewVoice) {
1032 schoenebeck 233 // launch the new voice
1033 schoenebeck 669 if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pDimRgn, VoiceType, iKeyGroup) < 0) {
1034 schoenebeck 354 dmsg(4,("Voice not triggered\n"));
1035 schoenebeck 271 pKey->pActiveVoices->free(itNewVoice);
1036 schoenebeck 233 }
1037 schoenebeck 239 else { // on success
1038 schoenebeck 663 --VoiceSpawnsLeft;
1039 schoenebeck 239 if (!pKey->Active) { // mark as active key
1040     pKey->Active = true;
1041 schoenebeck 411 pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();
1042 schoenebeck 271 *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
1043 schoenebeck 239 }
1044 schoenebeck 271 if (itNewVoice->KeyGroup) {
1045 schoenebeck 668 uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup];
1046 schoenebeck 271 *ppKeyGroup = &*pKey->itSelf; // put key as the (new) active key to its key group
1047 schoenebeck 239 }
1048 schoenebeck 271 if (itNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)
1049     return itNewVoice; // success
1050 schoenebeck 233 }
1051     }
1052 schoenebeck 285 else if (VoiceStealing) {
1053 schoenebeck 460 // try to steal one voice
1054 schoenebeck 473 int result = StealVoice(pEngineChannel, itNoteOnEvent);
1055     if (!result) { // voice stolen successfully
1056     // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died
1057     RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();
1058     if (itStealEvent) {
1059     *itStealEvent = *itNoteOnEvent; // copy event
1060     itStealEvent->Param.Note.Layer = iLayer;
1061     itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;
1062     pKey->VoiceTheftsQueued++;
1063     }
1064     else dmsg(1,("Voice stealing queue full!\n"));
1065 schoenebeck 285 }
1066     }
1067    
1068 schoenebeck 271 return Pool<Voice>::Iterator(); // no free voice or error
1069 schoenebeck 233 }
1070    
1071     /**
1072 schoenebeck 250 * Will be called by LaunchVoice() method in case there are no free
1073     * voices left. This method will select and kill one old voice for
1074     * voice stealing and postpone the note-on event until the selected
1075     * voice actually died.
1076     *
1077 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
1078 schoenebeck 285 * @param itNoteOnEvent - key, velocity and time stamp of the event
1079 schoenebeck 473 * @returns 0 on success, a value < 0 if no active voice could be picked for voice stealing
1080 schoenebeck 250 */
1081 schoenebeck 473 int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
1082 schoenebeck 663 if (VoiceSpawnsLeft <= 0) {
1083 schoenebeck 554 dmsg(1,("Max. voice thefts per audio fragment reached (you may raise CONFIG_MAX_VOICES).\n"));
1084 schoenebeck 473 return -1;
1085 schoenebeck 460 }
1086 schoenebeck 271 if (!pEventPool->poolIsEmpty()) {
1087 schoenebeck 250
1088 schoenebeck 460 RTList<Voice>::Iterator itSelectedVoice;
1089 schoenebeck 250
1090     // Select one voice for voice stealing
1091 schoenebeck 554 switch (CONFIG_VOICE_STEAL_ALGO) {
1092 schoenebeck 250
1093     // try to pick the oldest voice on the key where the new
1094     // voice should be spawned, if there is no voice on that
1095 schoenebeck 563 // key, or no voice left to kill, then procceed with
1096 schoenebeck 250 // 'oldestkey' algorithm
1097 schoenebeck 460 case voice_steal_algo_oldestvoiceonkey: {
1098     midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
1099 schoenebeck 563 itSelectedVoice = pSelectedKey->pActiveVoices->first();
1100     // proceed iterating if voice was created in this fragment cycle
1101 schoenebeck 663 while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1102 schoenebeck 563 // if we haven't found a voice then proceed with algorithm 'oldestkey'
1103 schoenebeck 663 if (itSelectedVoice && itSelectedVoice->IsStealable()) break;
1104 schoenebeck 250 } // no break - intentional !
1105    
1106     // try to pick the oldest voice on the oldest active key
1107 schoenebeck 563 // from the same engine channel
1108 schoenebeck 460 // (caution: must stay after 'oldestvoiceonkey' algorithm !)
1109 schoenebeck 250 case voice_steal_algo_oldestkey: {
1110 schoenebeck 649 // if we already stole in this fragment, try to proceed on same key
1111 schoenebeck 460 if (this->itLastStolenVoice) {
1112     itSelectedVoice = this->itLastStolenVoice;
1113 schoenebeck 649 do {
1114     ++itSelectedVoice;
1115 schoenebeck 663 } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1116 schoenebeck 649 // found a "stealable" voice ?
1117 schoenebeck 663 if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1118 schoenebeck 649 // remember which voice we stole, so we can simply proceed on next voice stealing
1119     this->itLastStolenVoice = itSelectedVoice;
1120 schoenebeck 460 break; // selection succeeded
1121 schoenebeck 250 }
1122     }
1123 schoenebeck 649 // get (next) oldest key
1124     RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKey) ? ++this->iuiLastStolenKey : pEngineChannel->pActiveKeys->first();
1125     while (iuiSelectedKey) {
1126     midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];
1127 schoenebeck 659 itSelectedVoice = pSelectedKey->pActiveVoices->first();
1128 schoenebeck 649 // proceed iterating if voice was created in this fragment cycle
1129 schoenebeck 663 while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1130 schoenebeck 649 // found a "stealable" voice ?
1131 schoenebeck 663 if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1132 schoenebeck 649 // remember which voice on which key we stole, so we can simply proceed on next voice stealing
1133     this->iuiLastStolenKey = iuiSelectedKey;
1134     this->itLastStolenVoice = itSelectedVoice;
1135     break; // selection succeeded
1136     }
1137     ++iuiSelectedKey; // get next oldest key
1138     }
1139 schoenebeck 250 break;
1140     }
1141    
1142     // don't steal anything
1143     case voice_steal_algo_none:
1144     default: {
1145     dmsg(1,("No free voice (voice stealing disabled)!\n"));
1146 schoenebeck 473 return -1;
1147 schoenebeck 250 }
1148     }
1149    
1150 schoenebeck 563 // if we couldn't steal a voice from the same engine channel then
1151     // steal oldest voice on the oldest key from any other engine channel
1152 schoenebeck 649 // (the smaller engine channel number, the higher priority)
1153 schoenebeck 663 if (!itSelectedVoice || !itSelectedVoice->IsStealable()) {
1154 schoenebeck 649 EngineChannel* pSelectedChannel;
1155     int iChannelIndex;
1156     // select engine channel
1157     if (pLastStolenChannel) {
1158     pSelectedChannel = pLastStolenChannel;
1159     iChannelIndex = pSelectedChannel->iEngineIndexSelf;
1160     } else { // pick the engine channel followed by this engine channel
1161     iChannelIndex = (pEngineChannel->iEngineIndexSelf + 1) % engineChannels.size();
1162     pSelectedChannel = engineChannels[iChannelIndex];
1163     }
1164 schoenebeck 663
1165     // if we already stole in this fragment, try to proceed on same key
1166     if (this->itLastStolenVoiceGlobally) {
1167     itSelectedVoice = this->itLastStolenVoiceGlobally;
1168     do {
1169     ++itSelectedVoice;
1170     } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1171     }
1172    
1173     #if CONFIG_DEVMODE
1174     EngineChannel* pBegin = pSelectedChannel; // to detect endless loop
1175     #endif // CONFIG_DEVMODE
1176    
1177     // did we find a 'stealable' voice?
1178     if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1179     // remember which voice we stole, so we can simply proceed on next voice stealing
1180     this->itLastStolenVoiceGlobally = itSelectedVoice;
1181     } else while (true) { // iterate through engine channels
1182 schoenebeck 649 // get (next) oldest key
1183 schoenebeck 663 RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKeyGlobally) ? ++this->iuiLastStolenKeyGlobally : pSelectedChannel->pActiveKeys->first();
1184     this->iuiLastStolenKeyGlobally = RTList<uint>::Iterator(); // to prevent endless loop (see line above)
1185 schoenebeck 649 while (iuiSelectedKey) {
1186 schoenebeck 663 midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];
1187 schoenebeck 649 itSelectedVoice = pSelectedKey->pActiveVoices->first();
1188     // proceed iterating if voice was created in this fragment cycle
1189 schoenebeck 663 while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1190 schoenebeck 649 // found a "stealable" voice ?
1191 schoenebeck 663 if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1192 schoenebeck 649 // remember which voice on which key on which engine channel we stole, so we can simply proceed on next voice stealing
1193     this->iuiLastStolenKeyGlobally = iuiSelectedKey;
1194     this->itLastStolenVoiceGlobally = itSelectedVoice;
1195     this->pLastStolenChannel = pSelectedChannel;
1196 schoenebeck 665 goto stealable_voice_found; // selection succeeded
1197 schoenebeck 649 }
1198     ++iuiSelectedKey; // get next key on current engine channel
1199     }
1200     // get next engine channel
1201 schoenebeck 460 iChannelIndex = (iChannelIndex + 1) % engineChannels.size();
1202 schoenebeck 649 pSelectedChannel = engineChannels[iChannelIndex];
1203 schoenebeck 663
1204     #if CONFIG_DEVMODE
1205     if (pSelectedChannel == pBegin) {
1206     dmsg(1,("FATAL ERROR: voice stealing endless loop!\n"));
1207     dmsg(1,("VoiceSpawnsLeft=%d.\n", VoiceSpawnsLeft));
1208     dmsg(1,("Exiting.\n"));
1209     exit(-1);
1210     }
1211     #endif // CONFIG_DEVMODE
1212 schoenebeck 460 }
1213     }
1214    
1215 schoenebeck 665 // jump point if a 'stealable' voice was found
1216     stealable_voice_found:
1217    
1218 schoenebeck 563 #if CONFIG_DEVMODE
1219 schoenebeck 473 if (!itSelectedVoice->IsActive()) {
1220     dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
1221     return -1;
1222     }
1223 schoenebeck 563 #endif // CONFIG_DEVMODE
1224 schoenebeck 287
1225 schoenebeck 250 // now kill the selected voice
1226 schoenebeck 659 itSelectedVoice->Kill(itNoteOnEvent);
1227 schoenebeck 460
1228 schoenebeck 663 --VoiceSpawnsLeft;
1229 schoenebeck 473
1230     return 0; // success
1231 schoenebeck 250 }
1232 schoenebeck 473 else {
1233     dmsg(1,("Event pool emtpy!\n"));
1234     return -1;
1235     }
1236 schoenebeck 250 }
1237    
1238     /**
1239 schoenebeck 285 * Removes the given voice from the MIDI key's list of active voices.
1240     * This method will be called when a voice went inactive, e.g. because
1241     * it finished to playback its sample, finished its release stage or
1242     * just was killed.
1243 schoenebeck 53 *
1244 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
1245 schoenebeck 285 * @param itVoice - points to the voice to be freed
1246 schoenebeck 53 */
1247 schoenebeck 411 void Engine::FreeVoice(EngineChannel* pEngineChannel, Pool<Voice>::Iterator& itVoice) {
1248 schoenebeck 271 if (itVoice) {
1249 schoenebeck 411 midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itVoice->MIDIKey];
1250 schoenebeck 53
1251 schoenebeck 271 uint keygroup = itVoice->KeyGroup;
1252    
1253 schoenebeck 53 // free the voice object
1254 schoenebeck 271 pVoicePool->free(itVoice);
1255 schoenebeck 53
1256 schoenebeck 287 // if no other voices left and member of a key group, remove from key group
1257     if (pKey->pActiveVoices->isEmpty() && keygroup) {
1258 schoenebeck 411 uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[keygroup];
1259 schoenebeck 287 if (*ppKeyGroup == &*pKey->itSelf) *ppKeyGroup = NULL; // remove key from key group
1260 schoenebeck 53 }
1261     }
1262 schoenebeck 285 else std::cerr << "Couldn't release voice! (!itVoice)\n" << std::flush;
1263 schoenebeck 53 }
1264    
1265     /**
1266 schoenebeck 287 * Called when there's no more voice left on a key, this call will
1267     * update the key info respectively.
1268     *
1269 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
1270 schoenebeck 287 * @param pKey - key which is now inactive
1271     */
1272 schoenebeck 411 void Engine::FreeKey(EngineChannel* pEngineChannel, midi_key_info_t* pKey) {
1273 schoenebeck 287 if (pKey->pActiveVoices->isEmpty()) {
1274     pKey->Active = false;
1275 schoenebeck 411 pEngineChannel->pActiveKeys->free(pKey->itSelf); // remove key from list of active keys
1276 schoenebeck 287 pKey->itSelf = RTList<uint>::Iterator();
1277     pKey->ReleaseTrigger = false;
1278     pKey->pEvents->clear();
1279     dmsg(3,("Key has no more voices now\n"));
1280     }
1281     else dmsg(1,("gig::Engine: Oops, tried to free a key which contains voices.\n"));
1282     }
1283    
1284     /**
1285 schoenebeck 53 * Reacts on supported control change commands (e.g. pitch bend wheel,
1286     * modulation wheel, aftertouch).
1287     *
1288 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
1289 schoenebeck 271 * @param itControlChangeEvent - controller, value and time stamp of the event
1290 schoenebeck 53 */
1291 schoenebeck 411 void Engine::ProcessControlChange(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itControlChangeEvent) {
1292 schoenebeck 271 dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", itControlChangeEvent->Param.CC.Controller, itControlChangeEvent->Param.CC.Value));
1293 schoenebeck 53
1294 schoenebeck 473 // update controller value in the engine channel's controller table
1295     pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
1296    
1297 schoenebeck 1001 // handle hard coded MIDI controllers
1298 schoenebeck 769 switch (itControlChangeEvent->Param.CC.Controller) {
1299 schoenebeck 829 case 5: { // portamento time
1300     pEngineChannel->PortamentoTime = (float) itControlChangeEvent->Param.CC.Value / 127.0f * (float) CONFIG_PORTAMENTO_TIME_MAX + (float) CONFIG_PORTAMENTO_TIME_MIN;
1301     break;
1302     }
1303 schoenebeck 424 case 7: { // volume
1304     //TODO: not sample accurate yet
1305 schoenebeck 947 pEngineChannel->MidiVolume = VolumeCurve[itControlChangeEvent->Param.CC.Value];
1306 schoenebeck 660 pEngineChannel->bStatusChanged = true; // engine channel status has changed, so set notify flag
1307 schoenebeck 424 break;
1308     }
1309     case 10: { // panpot
1310     //TODO: not sample accurate yet
1311 persson 831 pEngineChannel->GlobalPanLeft = PanCurve[128 - itControlChangeEvent->Param.CC.Value];
1312     pEngineChannel->GlobalPanRight = PanCurve[itControlChangeEvent->Param.CC.Value];
1313 schoenebeck 424 break;
1314     }
1315     case 64: { // sustain
1316 schoenebeck 769 if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {
1317 iliev 776 dmsg(4,("DAMPER (RIGHT) PEDAL DOWN\n"));
1318 schoenebeck 411 pEngineChannel->SustainPedal = true;
1319 schoenebeck 53
1320 iliev 716 #if !CONFIG_PROCESS_MUTED_CHANNELS
1321 schoenebeck 705 if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1322 iliev 716 #endif
1323 schoenebeck 705
1324 schoenebeck 53 // cancel release process of voices if necessary
1325 schoenebeck 411 RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1326 schoenebeck 473 for (; iuiKey; ++iuiKey) {
1327     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1328     if (!pKey->KeyPressed) {
1329     RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1330     if (itNewEvent) {
1331 schoenebeck 769 *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1332 schoenebeck 473 itNewEvent->Type = Event::type_cancel_release; // transform event type
1333 schoenebeck 53 }
1334 schoenebeck 473 else dmsg(1,("Event pool emtpy!\n"));
1335 schoenebeck 53 }
1336     }
1337     }
1338 schoenebeck 769 if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {
1339 iliev 776 dmsg(4,("DAMPER (RIGHT) PEDAL UP\n"));
1340 schoenebeck 411 pEngineChannel->SustainPedal = false;
1341 schoenebeck 53
1342 iliev 716 #if !CONFIG_PROCESS_MUTED_CHANNELS
1343 schoenebeck 705 if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1344 iliev 716 #endif
1345 schoenebeck 705
1346 schoenebeck 53 // release voices if their respective key is not pressed
1347 schoenebeck 411 RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1348 schoenebeck 473 for (; iuiKey; ++iuiKey) {
1349     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1350 iliev 776 if (!pKey->KeyPressed && ShouldReleaseVoice(pEngineChannel, *iuiKey)) {
1351 schoenebeck 473 RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1352     if (itNewEvent) {
1353 schoenebeck 769 *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1354 schoenebeck 473 itNewEvent->Type = Event::type_release; // transform event type
1355 schoenebeck 53 }
1356 schoenebeck 473 else dmsg(1,("Event pool emtpy!\n"));
1357 schoenebeck 53 }
1358     }
1359     }
1360     break;
1361     }
1362 schoenebeck 829 case 65: { // portamento on / off
1363     KillAllVoices(pEngineChannel, itControlChangeEvent);
1364     pEngineChannel->PortamentoMode = itControlChangeEvent->Param.CC.Value >= 64;
1365     break;
1366     }
1367 iliev 776 case 66: { // sostenuto
1368     if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SostenutoPedal) {
1369     dmsg(4,("SOSTENUTO (CENTER) PEDAL DOWN\n"));
1370     pEngineChannel->SostenutoPedal = true;
1371 schoenebeck 53
1372 iliev 776 #if !CONFIG_PROCESS_MUTED_CHANNELS
1373     if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1374     #endif
1375 schoenebeck 53
1376 iliev 776 SostenutoKeyCount = 0;
1377     // Remeber the pressed keys
1378     RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1379     for (; iuiKey; ++iuiKey) {
1380     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1381     if (pKey->KeyPressed && SostenutoKeyCount < 128) SostenutoKeys[SostenutoKeyCount++] = *iuiKey;
1382     }
1383     }
1384     if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SostenutoPedal) {
1385     dmsg(4,("SOSTENUTO (CENTER) PEDAL UP\n"));
1386     pEngineChannel->SostenutoPedal = false;
1387    
1388     #if !CONFIG_PROCESS_MUTED_CHANNELS
1389     if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1390     #endif
1391    
1392     // release voices if the damper pedal is up and their respective key is not pressed
1393     for (int i = 0; i < SostenutoKeyCount; i++) {
1394     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[SostenutoKeys[i]];
1395     if (!pKey->KeyPressed && !pEngineChannel->SustainPedal) {
1396     RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1397     if (itNewEvent) {
1398     *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1399     itNewEvent->Type = Event::type_release; // transform event type
1400     }
1401     else dmsg(1,("Event pool emtpy!\n"));
1402     }
1403     }
1404     }
1405     break;
1406     }
1407    
1408    
1409 schoenebeck 473 // Channel Mode Messages
1410    
1411     case 120: { // all sound off
1412 schoenebeck 769 KillAllVoices(pEngineChannel, itControlChangeEvent);
1413 schoenebeck 473 break;
1414     }
1415     case 121: { // reset all controllers
1416     pEngineChannel->ResetControllers();
1417     break;
1418     }
1419     case 123: { // all notes off
1420 schoenebeck 849 #if CONFIG_PROCESS_ALL_NOTES_OFF
1421 schoenebeck 769 ReleaseAllVoices(pEngineChannel, itControlChangeEvent);
1422 schoenebeck 849 #endif // CONFIG_PROCESS_ALL_NOTES_OFF
1423 schoenebeck 473 break;
1424     }
1425 schoenebeck 829 case 126: { // mono mode on
1426     KillAllVoices(pEngineChannel, itControlChangeEvent);
1427     pEngineChannel->SoloMode = true;
1428     break;
1429     }
1430     case 127: { // poly mode on
1431     KillAllVoices(pEngineChannel, itControlChangeEvent);
1432     pEngineChannel->SoloMode = false;
1433     break;
1434     }
1435 schoenebeck 473 }
1436 schoenebeck 1001
1437     // handle FX send controllers
1438     if (!pEngineChannel->fxSends.empty()) {
1439     for (int iFxSend = 0; iFxSend < pEngineChannel->GetFxSendCount(); iFxSend++) {
1440     FxSend* pFxSend = pEngineChannel->GetFxSend(iFxSend);
1441     if (pFxSend->MidiController() == itControlChangeEvent->Param.CC.Controller)
1442     pFxSend->SetLevel(itControlChangeEvent->Param.CC.Value);
1443     }
1444     }
1445 schoenebeck 53 }
1446    
1447     /**
1448 schoenebeck 244 * Reacts on MIDI system exclusive messages.
1449     *
1450 schoenebeck 271 * @param itSysexEvent - sysex data size and time stamp of the sysex event
1451 schoenebeck 244 */
1452 schoenebeck 271 void Engine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) {
1453 schoenebeck 970 RingBuffer<uint8_t,false>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();
1454 schoenebeck 244
1455     uint8_t exclusive_status, id;
1456     if (!reader.pop(&exclusive_status)) goto free_sysex_data;
1457     if (!reader.pop(&id)) goto free_sysex_data;
1458     if (exclusive_status != 0xF0) goto free_sysex_data;
1459    
1460     switch (id) {
1461     case 0x41: { // Roland
1462 schoenebeck 493 dmsg(3,("Roland Sysex\n"));
1463 schoenebeck 244 uint8_t device_id, model_id, cmd_id;
1464     if (!reader.pop(&device_id)) goto free_sysex_data;
1465     if (!reader.pop(&model_id)) goto free_sysex_data;
1466     if (!reader.pop(&cmd_id)) goto free_sysex_data;
1467     if (model_id != 0x42 /*GS*/) goto free_sysex_data;
1468     if (cmd_id != 0x12 /*DT1*/) goto free_sysex_data;
1469    
1470     // command address
1471     uint8_t addr[3]; // 2 byte addr MSB, followed by 1 byte addr LSB)
1472 schoenebeck 970 const RingBuffer<uint8_t,false>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later
1473 schoenebeck 244 if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;
1474     if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters
1475 schoenebeck 493 dmsg(3,("\tSystem Parameter\n"));
1476 schoenebeck 244 }
1477     else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters
1478 schoenebeck 493 dmsg(3,("\tCommon Parameter\n"));
1479 schoenebeck 244 }
1480     else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)
1481 schoenebeck 493 dmsg(3,("\tPart Parameter\n"));
1482     switch (addr[2]) {
1483 schoenebeck 244 case 0x40: { // scale tuning
1484 schoenebeck 493 dmsg(3,("\t\tScale Tuning\n"));
1485 schoenebeck 244 uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave
1486     if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;
1487     uint8_t checksum;
1488 schoenebeck 493 if (!reader.pop(&checksum)) goto free_sysex_data;
1489 schoenebeck 563 #if CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1490     if (GSCheckSum(checksum_reader, 12)) goto free_sysex_data;
1491     #endif // CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1492 schoenebeck 244 for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;
1493     AdjustScale((int8_t*) scale_tunes);
1494 schoenebeck 493 dmsg(3,("\t\t\tNew scale applied.\n"));
1495 schoenebeck 244 break;
1496     }
1497     }
1498     }
1499     else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x20) { // Part Parameters (2)
1500     }
1501     else if (addr[0] == 0x41) { // Drum Setup Parameters
1502     }
1503     break;
1504     }
1505     }
1506    
1507     free_sysex_data: // finally free sysex data
1508 schoenebeck 271 pSysexBuffer->increment_read_ptr(itSysexEvent->Param.Sysex.Size);
1509 schoenebeck 244 }
1510    
1511     /**
1512     * Calculates the Roland GS sysex check sum.
1513     *
1514     * @param AddrReader - reader which currently points to the first GS
1515     * command address byte of the GS sysex message in
1516     * question
1517     * @param DataSize - size of the GS message data (in bytes)
1518     */
1519 schoenebeck 970 uint8_t Engine::GSCheckSum(const RingBuffer<uint8_t,false>::NonVolatileReader AddrReader, uint DataSize) {
1520     RingBuffer<uint8_t,false>::NonVolatileReader reader = AddrReader;
1521 schoenebeck 244 uint bytes = 3 /*addr*/ + DataSize;
1522     uint8_t addr_and_data[bytes];
1523     reader.read(&addr_and_data[0], bytes);
1524     uint8_t sum = 0;
1525     for (uint i = 0; i < bytes; i++) sum += addr_and_data[i];
1526     return 128 - sum % 128;
1527     }
1528    
1529     /**
1530     * Allows to tune each of the twelve semitones of an octave.
1531     *
1532     * @param ScaleTunes - detuning of all twelve semitones (in cents)
1533     */
1534     void Engine::AdjustScale(int8_t ScaleTunes[12]) {
1535     memcpy(&this->ScaleTuning[0], &ScaleTunes[0], 12); //TODO: currently not sample accurate
1536     }
1537    
1538     /**
1539 schoenebeck 473 * Releases all voices on an engine channel. All voices will go into
1540     * the release stage and thus it might take some time (e.g. dependant to
1541     * their envelope release time) until they actually die.
1542     *
1543     * @param pEngineChannel - engine channel on which all voices should be released
1544     * @param itReleaseEvent - event which caused this releasing of all voices
1545     */
1546     void Engine::ReleaseAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itReleaseEvent) {
1547     RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1548     while (iuiKey) {
1549     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1550     ++iuiKey;
1551     // append a 'release' event to the key's own event list
1552     RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1553     if (itNewEvent) {
1554     *itNewEvent = *itReleaseEvent; // copy original event (to the key's event list)
1555     itNewEvent->Type = Event::type_release; // transform event type
1556     }
1557     else dmsg(1,("Event pool emtpy!\n"));
1558     }
1559     }
1560    
1561     /**
1562     * Kills all voices on an engine channel as soon as possible. Voices
1563     * won't get into release state, their volume level will be ramped down
1564     * as fast as possible.
1565     *
1566     * @param pEngineChannel - engine channel on which all voices should be killed
1567     * @param itKillEvent - event which caused this killing of all voices
1568     */
1569     void Engine::KillAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itKillEvent) {
1570     RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1571     RTList<uint>::Iterator end = pEngineChannel->pActiveKeys->end();
1572     while (iuiKey != end) { // iterate through all active keys
1573     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1574     ++iuiKey;
1575     RTList<Voice>::Iterator itVoice = pKey->pActiveVoices->first();
1576     RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
1577     for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
1578     itVoice->Kill(itKillEvent);
1579 schoenebeck 663 --VoiceSpawnsLeft; //FIXME: just a temporary workaround, we should check the cause in StealVoice() instead
1580 schoenebeck 473 }
1581     }
1582     }
1583    
1584 iliev 776 /**
1585     * Determines whether the specified voice should be released.
1586     *
1587     * @param pEngineChannel - The engine channel on which the voice should be checked
1588     * @param Key - The key number
1589     * @returns true if the specified should be released, false otherwise.
1590     */
1591     bool Engine::ShouldReleaseVoice(EngineChannel* pEngineChannel, int Key) {
1592     if (pEngineChannel->SustainPedal) return false;
1593    
1594     if (pEngineChannel->SostenutoPedal) {
1595     for (int i = 0; i < SostenutoKeyCount; i++)
1596     if (Key == SostenutoKeys[i]) return false;
1597     }
1598    
1599     return true;
1600     }
1601    
1602 schoenebeck 53 uint Engine::VoiceCount() {
1603     return ActiveVoiceCount;
1604     }
1605    
1606     uint Engine::VoiceCountMax() {
1607     return ActiveVoiceCountMax;
1608     }
1609    
1610     bool Engine::DiskStreamSupported() {
1611     return true;
1612     }
1613    
1614     uint Engine::DiskStreamCount() {
1615     return (pDiskThread) ? pDiskThread->ActiveStreamCount : 0;
1616     }
1617    
1618     uint Engine::DiskStreamCountMax() {
1619     return (pDiskThread) ? pDiskThread->ActiveStreamCountMax : 0;
1620     }
1621    
1622     String Engine::DiskStreamBufferFillBytes() {
1623     return pDiskThread->GetBufferFillBytes();
1624     }
1625    
1626     String Engine::DiskStreamBufferFillPercentage() {
1627     return pDiskThread->GetBufferFillPercentage();
1628     }
1629    
1630 senkov 112 String Engine::EngineName() {
1631 schoenebeck 475 return LS_GIG_ENGINE_NAME;
1632 senkov 112 }
1633    
1634 schoenebeck 53 String Engine::Description() {
1635     return "Gigasampler Engine";
1636     }
1637    
1638     String Engine::Version() {
1639 schoenebeck 1037 String s = "$Revision: 1.70 $";
1640 schoenebeck 123 return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword
1641 schoenebeck 53 }
1642    
1643 schoenebeck 947 InstrumentManager* Engine::GetInstrumentManager() {
1644     return &instruments;
1645     }
1646    
1647 persson 831 // static constant initializers
1648     const float* Engine::VolumeCurve(InitVolumeCurve());
1649     const float* Engine::PanCurve(InitPanCurve());
1650 persson 832 const float* Engine::CrossfadeCurve(InitCrossfadeCurve());
1651 persson 831
1652     float* Engine::InitVolumeCurve() {
1653     // line-segment approximation
1654     const float segments[] = {
1655     0, 0, 2, 0.0046, 16, 0.016, 31, 0.051, 45, 0.115, 54.5, 0.2,
1656     64.5, 0.39, 74, 0.74, 92, 1.03, 114, 1.94, 119.2, 2.2, 127, 2.2
1657     };
1658     return InitCurve(segments);
1659     }
1660    
1661     float* Engine::InitPanCurve() {
1662     // line-segment approximation
1663     const float segments[] = {
1664     0, 0, 1, 0,
1665     2, 0.05, 31.5, 0.7, 51, 0.851, 74.5, 1.12,
1666     127, 1.41, 128, 1.41
1667     };
1668     return InitCurve(segments, 129);
1669     }
1670    
1671 persson 832 float* Engine::InitCrossfadeCurve() {
1672     // line-segment approximation
1673     const float segments[] = {
1674     0, 0, 1, 0.03, 10, 0.1, 51, 0.58, 127, 1
1675     };
1676     return InitCurve(segments);
1677     }
1678    
1679 persson 831 float* Engine::InitCurve(const float* segments, int size) {
1680     float* y = new float[size];
1681     for (int x = 0 ; x < size ; x++) {
1682     if (x > segments[2]) segments += 2;
1683     y[x] = segments[1] + (x - segments[0]) *
1684     (segments[3] - segments[1]) / (segments[2] - segments[0]);
1685     }
1686     return y;
1687     }
1688    
1689 schoenebeck 53 }} // namespace LinuxSampler::gig

  ViewVC Help
Powered by ViewVC