/[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 924 - (hide annotations) (download)
Sat Oct 21 14:13:09 2006 UTC (17 years, 5 months ago) by schoenebeck
File size: 77976 byte(s)
just minor code comment update

1 schoenebeck 53 /***************************************************************************
2     * *
3     * LinuxSampler - modular, streaming capable sampler *
4     * *
5 schoenebeck 56 * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck *
6 schoenebeck 829 * Copyright (C) 2005, 2006 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 554 pSysexBuffer = new RingBuffer<uint8_t>(CONFIG_SYSEX_BUFFER_SIZE, 0);
101     pEventQueue = new RingBuffer<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);
102     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 schoenebeck 420 EngineFactory::Destroy(this);
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 412 RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
310     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 53 dmsg(5,("RenderAudio(Samples=%d)\n", Samples));
344    
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     // handle cleanup on all engine channels for the next audio fragment
396     for (int i = 0; i < engineChannels.size(); i++) {
397     if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
398     PostProcess(engineChannels[i]);
399     }
400    
401    
402     // empty the engine's event list for the next audio fragment
403     ClearEventLists();
404    
405     // reset voice stealing for the next audio fragment
406     pVoiceStealingQueue->clear();
407    
408 schoenebeck 412 // just some statistics about this engine instance
409     ActiveVoiceCount = ActiveVoiceCountTemp;
410     if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;
411    
412 persson 630 FrameTime += Samples;
413    
414 schoenebeck 412 return 0;
415     }
416    
417 schoenebeck 473 /**
418     * Dispatch and handle all events in this audio fragment for the given
419     * engine channel.
420     *
421     * @param pEngineChannel - engine channel on which events should be
422     * processed
423     * @param Samples - amount of sample points to be processed in
424     * this audio fragment cycle
425     */
426 schoenebeck 460 void Engine::ProcessEvents(EngineChannel* pEngineChannel, uint Samples) {
427 schoenebeck 412 // get all events from the engine channels's input event queue which belong to the current fragment
428     // (these are the common events like NoteOn, NoteOff, ControlChange, etc.)
429 schoenebeck 460 pEngineChannel->ImportEvents(Samples);
430 schoenebeck 53
431     // process events
432 schoenebeck 271 {
433 schoenebeck 460 RTList<Event>::Iterator itEvent = pEngineChannel->pEvents->first();
434     RTList<Event>::Iterator end = pEngineChannel->pEvents->end();
435 schoenebeck 271 for (; itEvent != end; ++itEvent) {
436     switch (itEvent->Type) {
437     case Event::type_note_on:
438     dmsg(5,("Engine: Note on received\n"));
439 schoenebeck 412 ProcessNoteOn((EngineChannel*)itEvent->pEngineChannel, itEvent);
440 schoenebeck 271 break;
441     case Event::type_note_off:
442     dmsg(5,("Engine: Note off received\n"));
443 schoenebeck 412 ProcessNoteOff((EngineChannel*)itEvent->pEngineChannel, itEvent);
444 schoenebeck 271 break;
445     case Event::type_control_change:
446     dmsg(5,("Engine: MIDI CC received\n"));
447 schoenebeck 412 ProcessControlChange((EngineChannel*)itEvent->pEngineChannel, itEvent);
448 schoenebeck 271 break;
449     case Event::type_pitchbend:
450     dmsg(5,("Engine: Pitchbend received\n"));
451 schoenebeck 412 ProcessPitchbend((EngineChannel*)itEvent->pEngineChannel, itEvent);
452 schoenebeck 271 break;
453     }
454 schoenebeck 53 }
455     }
456 schoenebeck 649
457     // reset voice stealing for the next engine channel (or next audio fragment)
458     itLastStolenVoice = RTList<Voice>::Iterator();
459     itLastStolenVoiceGlobally = RTList<Voice>::Iterator();
460     iuiLastStolenKey = RTList<uint>::Iterator();
461     iuiLastStolenKeyGlobally = RTList<uint>::Iterator();
462     pLastStolenChannel = NULL;
463 schoenebeck 460 }
464 schoenebeck 53
465 schoenebeck 473 /**
466     * Render all 'normal' voices (that is voices which were not stolen in
467     * this fragment) on the given engine channel.
468     *
469     * @param pEngineChannel - engine channel on which audio should be
470     * rendered
471     * @param Samples - amount of sample points to be rendered in
472     * this audio fragment cycle
473     */
474 schoenebeck 460 void Engine::RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {
475 iliev 716 #if !CONFIG_PROCESS_MUTED_CHANNELS
476 schoenebeck 705 if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
477 iliev 716 #endif
478 schoenebeck 705
479 schoenebeck 460 RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
480     RTList<uint>::Iterator end = pEngineChannel->pActiveKeys->end();
481     while (iuiKey != end) { // iterate through all active keys
482     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
483     ++iuiKey;
484 schoenebeck 53
485 schoenebeck 460 RTList<Voice>::Iterator itVoice = pKey->pActiveVoices->first();
486     RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
487     for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
488     // now render current voice
489     itVoice->Render(Samples);
490     if (itVoice->IsActive()) ActiveVoiceCountTemp++; // still active
491     else { // voice reached end, is now inactive
492     FreeVoice(pEngineChannel, itVoice); // remove voice from the list of active voices
493 schoenebeck 53 }
494     }
495     }
496 schoenebeck 460 }
497 schoenebeck 53
498 schoenebeck 473 /**
499     * Render all stolen voices (only voices which were stolen in this
500     * fragment) on the given engine channel. Stolen voices are rendered
501     * after all normal voices have been rendered; this is needed to render
502     * audio of those voices which were selected for voice stealing until
503     * the point were the stealing (that is the take over of the voice)
504     * actually happened.
505     *
506     * @param pEngineChannel - engine channel on which audio should be
507     * rendered
508     * @param Samples - amount of sample points to be rendered in
509     * this audio fragment cycle
510     */
511 schoenebeck 460 void Engine::RenderStolenVoices(uint Samples) {
512     RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();
513     RTList<Event>::Iterator end = pVoiceStealingQueue->end();
514     for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
515     EngineChannel* pEngineChannel = (EngineChannel*) itVoiceStealEvent->pEngineChannel;
516     Pool<Voice>::Iterator itNewVoice =
517 schoenebeck 668 LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false, false);
518 schoenebeck 460 if (itNewVoice) {
519     itNewVoice->Render(Samples);
520     if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active
521     else { // voice reached end, is now inactive
522     FreeVoice(pEngineChannel, itNewVoice); // remove voice from the list of active voices
523 schoenebeck 250 }
524     }
525 schoenebeck 460 else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));
526 schoenebeck 473
527     // we need to clear the key's event list explicitly here in case key was never active
528     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itVoiceStealEvent->Param.Note.Key];
529     pKey->VoiceTheftsQueued--;
530     if (!pKey->Active && !pKey->VoiceTheftsQueued) pKey->pEvents->clear();
531 schoenebeck 250 }
532 schoenebeck 460 }
533 schoenebeck 250
534 schoenebeck 473 /**
535     * Free all keys which have turned inactive in this audio fragment, from
536     * the list of active keys and clear all event lists on that engine
537     * channel.
538     *
539     * @param pEngineChannel - engine channel to cleanup
540     */
541 schoenebeck 460 void Engine::PostProcess(EngineChannel* pEngineChannel) {
542 schoenebeck 287 // free all keys which have no active voices left
543     {
544 schoenebeck 411 RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
545     RTList<uint>::Iterator end = pEngineChannel->pActiveKeys->end();
546 schoenebeck 287 while (iuiKey != end) { // iterate through all active keys
547 schoenebeck 411 midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
548 schoenebeck 287 ++iuiKey;
549 schoenebeck 411 if (pKey->pActiveVoices->isEmpty()) FreeKey(pEngineChannel, pKey);
550 schoenebeck 554 #if CONFIG_DEVMODE
551 schoenebeck 563 else { // just a sanity check for debugging
552 schoenebeck 287 RTList<Voice>::Iterator itVoice = pKey->pActiveVoices->first();
553     RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
554     for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
555     if (itVoice->itKillEvent) {
556     dmsg(1,("gig::Engine: ERROR, killed voice survived !!!\n"));
557     }
558     }
559     }
560 schoenebeck 554 #endif // CONFIG_DEVMODE
561 schoenebeck 287 }
562     }
563 schoenebeck 460
564     // empty the engine channel's own event lists
565     pEngineChannel->ClearEventLists();
566 schoenebeck 412 }
567 schoenebeck 287
568 schoenebeck 53 /**
569 schoenebeck 244 * Will be called by the MIDI input device whenever a MIDI system
570     * exclusive message has arrived.
571     *
572     * @param pData - pointer to sysex data
573     * @param Size - lenght of sysex data (in bytes)
574     */
575     void Engine::SendSysex(void* pData, uint Size) {
576 schoenebeck 246 Event event = pEventGenerator->CreateEvent();
577     event.Type = Event::type_sysex;
578     event.Param.Sysex.Size = Size;
579 schoenebeck 412 event.pEngineChannel = NULL; // as Engine global event
580 schoenebeck 244 if (pEventQueue->write_space() > 0) {
581     if (pSysexBuffer->write_space() >= Size) {
582     // copy sysex data to input buffer
583     uint toWrite = Size;
584     uint8_t* pPos = (uint8_t*) pData;
585     while (toWrite) {
586     const uint writeNow = RTMath::Min(toWrite, pSysexBuffer->write_space_to_end());
587     pSysexBuffer->write(pPos, writeNow);
588     toWrite -= writeNow;
589     pPos += writeNow;
590    
591     }
592     // finally place sysex event into input event queue
593     pEventQueue->push(&event);
594     }
595 schoenebeck 554 else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,CONFIG_SYSEX_BUFFER_SIZE));
596 schoenebeck 244 }
597     else dmsg(1,("Engine: Input event queue full!"));
598     }
599    
600     /**
601 schoenebeck 53 * Assigns and triggers a new voice for the respective MIDI key.
602     *
603 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
604 schoenebeck 271 * @param itNoteOnEvent - key, velocity and time stamp of the event
605 schoenebeck 53 */
606 schoenebeck 411 void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
607 iliev 716 #if !CONFIG_PROCESS_MUTED_CHANNELS
608     if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
609     #endif
610 persson 438
611 schoenebeck 354 const int key = itNoteOnEvent->Param.Note.Key;
612 schoenebeck 829 midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];
613 schoenebeck 354
614 schoenebeck 829 // move note on event to the key's own event list
615     RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
616    
617     // if Solo Mode then kill all already active voices
618     if (pEngineChannel->SoloMode) {
619     Pool<uint>::Iterator itYoungestKey = pEngineChannel->pActiveKeys->last();
620     if (itYoungestKey) {
621     const int iYoungestKey = *itYoungestKey;
622     const midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[iYoungestKey];
623     if (pOtherKey->Active) {
624     // get final portamento position of currently active voice
625     if (pEngineChannel->PortamentoMode) {
626     RTList<Voice>::Iterator itVoice = pOtherKey->pActiveVoices->last();
627     if (itVoice) itVoice->UpdatePortamentoPos(itNoteOnEventOnKeyList);
628     }
629     // kill all voices on the (other) key
630     RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
631     RTList<Voice>::Iterator end = pOtherKey->pActiveVoices->end();
632     for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
633     if (itVoiceToBeKilled->Type != Voice::type_release_trigger)
634     itVoiceToBeKilled->Kill(itNoteOnEventOnKeyList);
635     }
636     }
637     }
638     // set this key as 'currently active solo key'
639     pEngineChannel->SoloKey = key;
640     }
641    
642 schoenebeck 354 // Change key dimension value if key is in keyswitching area
643 schoenebeck 411 {
644     const ::gig::Instrument* pInstrument = pEngineChannel->pInstrument;
645     if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high)
646 persson 865 pEngineChannel->CurrentKeyDimension = float(key - pInstrument->DimensionKeyRange.low) /
647 schoenebeck 411 (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);
648     }
649 schoenebeck 354
650 schoenebeck 53 pKey->KeyPressed = true; // the MIDI key was now pressed down
651 schoenebeck 829 pKey->Velocity = itNoteOnEventOnKeyList->Param.Note.Velocity;
652     pKey->NoteOnTime = FrameTime + itNoteOnEventOnKeyList->FragmentPos(); // will be used to calculate note length
653 schoenebeck 53
654     // cancel release process of voices on this key if needed
655 schoenebeck 411 if (pKey->Active && !pEngineChannel->SustainPedal) {
656 schoenebeck 271 RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
657     if (itCancelReleaseEvent) {
658 schoenebeck 829 *itCancelReleaseEvent = *itNoteOnEventOnKeyList; // copy event
659 schoenebeck 271 itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type
660 schoenebeck 239 }
661     else dmsg(1,("Event pool emtpy!\n"));
662 schoenebeck 53 }
663    
664 schoenebeck 460 // allocate and trigger new voice(s) for the key
665     {
666     // first, get total amount of required voices (dependant on amount of layers)
667     ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOnEventOnKeyList->Param.Note.Key);
668     if (pRegion) {
669     int voicesRequired = pRegion->Layers;
670     // now launch the required amount of voices
671     for (int i = 0; i < voicesRequired; i++)
672 schoenebeck 668 LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true, true);
673 schoenebeck 460 }
674     }
675 persson 438
676 schoenebeck 473 // if neither a voice was spawned or postponed then remove note on event from key again
677     if (!pKey->Active && !pKey->VoiceTheftsQueued)
678     pKey->pEvents->free(itNoteOnEventOnKeyList);
679    
680 schoenebeck 829 if (!pEngineChannel->SoloMode || pEngineChannel->PortamentoPos < 0.0f) pEngineChannel->PortamentoPos = (float) key;
681 persson 438 pKey->RoundRobinIndex++;
682 schoenebeck 53 }
683    
684     /**
685     * Releases the voices on the given key if sustain pedal is not pressed.
686     * If sustain is pressed, the release of the note will be postponed until
687     * sustain pedal will be released or voice turned inactive by itself (e.g.
688     * due to completion of sample playback).
689     *
690 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
691 schoenebeck 271 * @param itNoteOffEvent - key, velocity and time stamp of the event
692 schoenebeck 53 */
693 schoenebeck 411 void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {
694 iliev 716 #if !CONFIG_PROCESS_MUTED_CHANNELS
695 schoenebeck 705 if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
696 iliev 716 #endif
697 schoenebeck 705
698 schoenebeck 829 const int iKey = itNoteOffEvent->Param.Note.Key;
699     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[iKey];
700 schoenebeck 53 pKey->KeyPressed = false; // the MIDI key was now released
701    
702 schoenebeck 829 // move event to the key's own event list
703     RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
704 schoenebeck 242
705 schoenebeck 829 bool bShouldRelease = pKey->Active && ShouldReleaseVoice(pEngineChannel, itNoteOffEventOnKeyList->Param.Note.Key);
706 schoenebeck 271
707 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)
708     if (pEngineChannel->SoloMode) { //TODO: this feels like too much code just for handling solo mode :P
709     bool bOtherKeysPressed = false;
710     if (iKey == pEngineChannel->SoloKey) {
711     pEngineChannel->SoloKey = -1;
712     // if there's still a key pressed down, respawn a voice (group) on the highest key
713     for (int i = 127; i > 0; i--) {
714     midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[i];
715     if (pOtherKey->KeyPressed) {
716     bOtherKeysPressed = true;
717     // make the other key the new 'currently active solo key'
718     pEngineChannel->SoloKey = i;
719     // get final portamento position of currently active voice
720     if (pEngineChannel->PortamentoMode) {
721     RTList<Voice>::Iterator itVoice = pKey->pActiveVoices->first();
722     if (itVoice) itVoice->UpdatePortamentoPos(itNoteOffEventOnKeyList);
723     }
724     // create a pseudo note on event
725     RTList<Event>::Iterator itPseudoNoteOnEvent = pOtherKey->pEvents->allocAppend();
726     if (itPseudoNoteOnEvent) {
727     // copy event
728     *itPseudoNoteOnEvent = *itNoteOffEventOnKeyList;
729     // transform event to a note on event
730     itPseudoNoteOnEvent->Type = Event::type_note_on;
731     itPseudoNoteOnEvent->Param.Note.Key = i;
732     itPseudoNoteOnEvent->Param.Note.Velocity = pOtherKey->Velocity;
733     // allocate and trigger new voice(s) for the other key
734     {
735     // first, get total amount of required voices (dependant on amount of layers)
736     ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(i);
737     if (pRegion) {
738     int voicesRequired = pRegion->Layers;
739     // now launch the required amount of voices
740     for (int iLayer = 0; iLayer < voicesRequired; iLayer++)
741     LaunchVoice(pEngineChannel, itPseudoNoteOnEvent, iLayer, false, true, false);
742     }
743     }
744     // if neither a voice was spawned or postponed then remove note on event from key again
745     if (!pOtherKey->Active && !pOtherKey->VoiceTheftsQueued)
746     pOtherKey->pEvents->free(itPseudoNoteOnEvent);
747    
748     } else dmsg(1,("Could not respawn voice, no free event left\n"));
749     break; // done
750     }
751     }
752     }
753     if (bOtherKeysPressed) {
754     if (pKey->Active) { // kill all voices on this key
755     bShouldRelease = false; // no need to release, as we kill it here
756     RTList<Voice>::Iterator itVoiceToBeKilled = pKey->pActiveVoices->first();
757     RTList<Voice>::Iterator end = pKey->pActiveVoices->end();
758     for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
759     if (itVoiceToBeKilled->Type != Voice::type_release_trigger)
760     itVoiceToBeKilled->Kill(itNoteOffEventOnKeyList);
761     }
762     }
763     } else pEngineChannel->PortamentoPos = -1.0f;
764     }
765    
766     // if no solo mode (the usual case) or if solo mode and no other key pressed, then release voices on this key if needed
767     if (bShouldRelease) {
768     itNoteOffEventOnKeyList->Type = Event::type_release; // transform event type
769    
770 persson 497 // spawn release triggered voice(s) if needed
771 persson 630 if (pKey->ReleaseTrigger) {
772 persson 497 // first, get total amount of required voices (dependant on amount of layers)
773     ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOffEventOnKeyList->Param.Note.Key);
774     if (pRegion) {
775     int voicesRequired = pRegion->Layers;
776 persson 630
777     // MIDI note-on velocity is used instead of note-off velocity
778     itNoteOffEventOnKeyList->Param.Note.Velocity = pKey->Velocity;
779    
780 persson 497 // now launch the required amount of voices
781     for (int i = 0; i < voicesRequired; i++)
782 schoenebeck 668 LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, i, true, false, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
783 persson 497 }
784     pKey->ReleaseTrigger = false;
785 schoenebeck 460 }
786 schoenebeck 829 }
787 persson 497
788 schoenebeck 829 // if neither a voice was spawned or postponed on this key then remove note off event from key again
789     if (!pKey->Active && !pKey->VoiceTheftsQueued)
790     pKey->pEvents->free(itNoteOffEventOnKeyList);
791 schoenebeck 53 }
792    
793     /**
794 schoenebeck 738 * Moves pitchbend event from the general (input) event list to the engine
795     * channel's event list. It will actually processed later by the
796     * respective voice.
797 schoenebeck 53 *
798 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
799 schoenebeck 271 * @param itPitchbendEvent - absolute pitch value and time stamp of the event
800 schoenebeck 53 */
801 schoenebeck 411 void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {
802     pEngineChannel->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value
803 schoenebeck 53 }
804    
805     /**
806 schoenebeck 233 * Allocates and triggers a new voice. This method will usually be
807     * called by the ProcessNoteOn() method and by the voices itself
808     * (e.g. to spawn further voices on the same key for layered sounds).
809     *
810 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
811 schoenebeck 271 * @param itNoteOnEvent - key, velocity and time stamp of the event
812 schoenebeck 242 * @param iLayer - layer index for the new voice (optional - only
813     * in case of layered sounds of course)
814     * @param ReleaseTriggerVoice - if new voice is a release triggered voice
815     * (optional, default = false)
816 schoenebeck 250 * @param VoiceStealing - if voice stealing should be performed
817     * when there is no free voice
818     * (optional, default = true)
819 schoenebeck 668 * @param HandleKeyGroupConflicts - if voices should be killed due to a
820     * key group conflict
821 schoenebeck 250 * @returns pointer to new voice or NULL if there was no free voice or
822 schoenebeck 354 * if the voice wasn't triggered (for example when no region is
823     * defined for the given key).
824 schoenebeck 233 */
825 schoenebeck 668 Pool<Voice>::Iterator Engine::LaunchVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing, bool HandleKeyGroupConflicts) {
826 schoenebeck 669 int MIDIKey = itNoteOnEvent->Param.Note.Key;
827     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[MIDIKey];
828     ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(MIDIKey);
829 schoenebeck 233
830 schoenebeck 668 // if nothing defined for this key
831     if (!pRegion) return Pool<Voice>::Iterator(); // nothing to do
832    
833 schoenebeck 669 // only mark the first voice of a layered voice (group) to be in a
834     // key group, so the layered voices won't kill each other
835     int iKeyGroup = (iLayer == 0 && !ReleaseTriggerVoice) ? pRegion->KeyGroup : 0;
836    
837 schoenebeck 668 // handle key group (a.k.a. exclusive group) conflicts
838     if (HandleKeyGroupConflicts) {
839     if (iKeyGroup) { // if this voice / key belongs to a key group
840     uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[iKeyGroup];
841     if (*ppKeyGroup) { // if there's already an active key in that key group
842     midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[**ppKeyGroup];
843     // kill all voices on the (other) key
844     RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
845     RTList<Voice>::Iterator end = pOtherKey->pActiveVoices->end();
846     for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
847     if (itVoiceToBeKilled->Type != Voice::type_release_trigger) {
848     itVoiceToBeKilled->Kill(itNoteOnEvent);
849     --VoiceSpawnsLeft; //FIXME: just a hack, we should better check in StealVoice() if the voice was killed due to key conflict
850     }
851     }
852     }
853     }
854     }
855    
856 schoenebeck 669 Voice::type_t VoiceType = Voice::type_normal;
857    
858     // get current dimension values to select the right dimension region
859     //TODO: for stolen voices this dimension region selection block is processed twice, this should be changed
860     //FIXME: controller values for selecting the dimension region here are currently not sample accurate
861     uint DimValues[8] = { 0 };
862     for (int i = pRegion->Dimensions - 1; i >= 0; i--) {
863     switch (pRegion->pDimensionDefinitions[i].dimension) {
864     case ::gig::dimension_samplechannel:
865     DimValues[i] = 0; //TODO: we currently ignore this dimension
866     break;
867     case ::gig::dimension_layer:
868     DimValues[i] = iLayer;
869     break;
870     case ::gig::dimension_velocity:
871     DimValues[i] = itNoteOnEvent->Param.Note.Velocity;
872     break;
873     case ::gig::dimension_channelaftertouch:
874 persson 903 DimValues[i] = pEngineChannel->ControllerTable[128];
875 schoenebeck 669 break;
876     case ::gig::dimension_releasetrigger:
877     VoiceType = (ReleaseTriggerVoice) ? Voice::type_release_trigger : (!iLayer) ? Voice::type_release_trigger_required : Voice::type_normal;
878     DimValues[i] = (uint) ReleaseTriggerVoice;
879     break;
880     case ::gig::dimension_keyboard:
881 persson 865 DimValues[i] = (uint) (pEngineChannel->CurrentKeyDimension * pRegion->pDimensionDefinitions[i].zones);
882 schoenebeck 669 break;
883     case ::gig::dimension_roundrobin:
884     DimValues[i] = (uint) pEngineChannel->pMIDIKeyInfo[MIDIKey].RoundRobinIndex; // incremented for each note on
885     break;
886     case ::gig::dimension_random:
887     RandomSeed = RandomSeed * 1103515245 + 12345; // classic pseudo random number generator
888     DimValues[i] = (uint) RandomSeed >> (32 - pRegion->pDimensionDefinitions[i].bits); // highest bits are most random
889     break;
890     case ::gig::dimension_modwheel:
891     DimValues[i] = pEngineChannel->ControllerTable[1];
892     break;
893     case ::gig::dimension_breath:
894     DimValues[i] = pEngineChannel->ControllerTable[2];
895     break;
896     case ::gig::dimension_foot:
897     DimValues[i] = pEngineChannel->ControllerTable[4];
898     break;
899     case ::gig::dimension_portamentotime:
900     DimValues[i] = pEngineChannel->ControllerTable[5];
901     break;
902     case ::gig::dimension_effect1:
903     DimValues[i] = pEngineChannel->ControllerTable[12];
904     break;
905     case ::gig::dimension_effect2:
906     DimValues[i] = pEngineChannel->ControllerTable[13];
907     break;
908     case ::gig::dimension_genpurpose1:
909     DimValues[i] = pEngineChannel->ControllerTable[16];
910     break;
911     case ::gig::dimension_genpurpose2:
912     DimValues[i] = pEngineChannel->ControllerTable[17];
913     break;
914     case ::gig::dimension_genpurpose3:
915     DimValues[i] = pEngineChannel->ControllerTable[18];
916     break;
917     case ::gig::dimension_genpurpose4:
918     DimValues[i] = pEngineChannel->ControllerTable[19];
919     break;
920     case ::gig::dimension_sustainpedal:
921     DimValues[i] = pEngineChannel->ControllerTable[64];
922     break;
923     case ::gig::dimension_portamento:
924     DimValues[i] = pEngineChannel->ControllerTable[65];
925     break;
926     case ::gig::dimension_sostenutopedal:
927     DimValues[i] = pEngineChannel->ControllerTable[66];
928     break;
929     case ::gig::dimension_softpedal:
930     DimValues[i] = pEngineChannel->ControllerTable[67];
931     break;
932     case ::gig::dimension_genpurpose5:
933     DimValues[i] = pEngineChannel->ControllerTable[80];
934     break;
935     case ::gig::dimension_genpurpose6:
936     DimValues[i] = pEngineChannel->ControllerTable[81];
937     break;
938     case ::gig::dimension_genpurpose7:
939     DimValues[i] = pEngineChannel->ControllerTable[82];
940     break;
941     case ::gig::dimension_genpurpose8:
942     DimValues[i] = pEngineChannel->ControllerTable[83];
943     break;
944     case ::gig::dimension_effect1depth:
945     DimValues[i] = pEngineChannel->ControllerTable[91];
946     break;
947     case ::gig::dimension_effect2depth:
948     DimValues[i] = pEngineChannel->ControllerTable[92];
949     break;
950     case ::gig::dimension_effect3depth:
951     DimValues[i] = pEngineChannel->ControllerTable[93];
952     break;
953     case ::gig::dimension_effect4depth:
954     DimValues[i] = pEngineChannel->ControllerTable[94];
955     break;
956     case ::gig::dimension_effect5depth:
957     DimValues[i] = pEngineChannel->ControllerTable[95];
958     break;
959     case ::gig::dimension_none:
960     std::cerr << "gig::Engine::LaunchVoice() Error: dimension=none\n" << std::flush;
961     break;
962     default:
963     std::cerr << "gig::Engine::LaunchVoice() Error: Unknown dimension\n" << std::flush;
964     }
965     }
966     ::gig::DimensionRegion* pDimRgn = pRegion->GetDimensionRegionByValue(DimValues);
967    
968     // no need to continue if sample is silent
969     if (!pDimRgn->pSample || !pDimRgn->pSample->SamplesTotal) return Pool<Voice>::Iterator();
970    
971 schoenebeck 233 // allocate a new voice for the key
972 schoenebeck 271 Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
973     if (itNewVoice) {
974 schoenebeck 233 // launch the new voice
975 schoenebeck 669 if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pDimRgn, VoiceType, iKeyGroup) < 0) {
976 schoenebeck 354 dmsg(4,("Voice not triggered\n"));
977 schoenebeck 271 pKey->pActiveVoices->free(itNewVoice);
978 schoenebeck 233 }
979 schoenebeck 239 else { // on success
980 schoenebeck 663 --VoiceSpawnsLeft;
981 schoenebeck 239 if (!pKey->Active) { // mark as active key
982     pKey->Active = true;
983 schoenebeck 411 pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();
984 schoenebeck 271 *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
985 schoenebeck 239 }
986 schoenebeck 271 if (itNewVoice->KeyGroup) {
987 schoenebeck 668 uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup];
988 schoenebeck 271 *ppKeyGroup = &*pKey->itSelf; // put key as the (new) active key to its key group
989 schoenebeck 239 }
990 schoenebeck 271 if (itNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)
991     return itNewVoice; // success
992 schoenebeck 233 }
993     }
994 schoenebeck 285 else if (VoiceStealing) {
995 schoenebeck 460 // try to steal one voice
996 schoenebeck 473 int result = StealVoice(pEngineChannel, itNoteOnEvent);
997     if (!result) { // voice stolen successfully
998     // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died
999     RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();
1000     if (itStealEvent) {
1001     *itStealEvent = *itNoteOnEvent; // copy event
1002     itStealEvent->Param.Note.Layer = iLayer;
1003     itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;
1004     pKey->VoiceTheftsQueued++;
1005     }
1006     else dmsg(1,("Voice stealing queue full!\n"));
1007 schoenebeck 285 }
1008     }
1009    
1010 schoenebeck 271 return Pool<Voice>::Iterator(); // no free voice or error
1011 schoenebeck 233 }
1012    
1013     /**
1014 schoenebeck 250 * Will be called by LaunchVoice() method in case there are no free
1015     * voices left. This method will select and kill one old voice for
1016     * voice stealing and postpone the note-on event until the selected
1017     * voice actually died.
1018     *
1019 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
1020 schoenebeck 285 * @param itNoteOnEvent - key, velocity and time stamp of the event
1021 schoenebeck 473 * @returns 0 on success, a value < 0 if no active voice could be picked for voice stealing
1022 schoenebeck 250 */
1023 schoenebeck 473 int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
1024 schoenebeck 663 if (VoiceSpawnsLeft <= 0) {
1025 schoenebeck 554 dmsg(1,("Max. voice thefts per audio fragment reached (you may raise CONFIG_MAX_VOICES).\n"));
1026 schoenebeck 473 return -1;
1027 schoenebeck 460 }
1028 schoenebeck 271 if (!pEventPool->poolIsEmpty()) {
1029 schoenebeck 250
1030 schoenebeck 460 RTList<Voice>::Iterator itSelectedVoice;
1031 schoenebeck 250
1032     // Select one voice for voice stealing
1033 schoenebeck 554 switch (CONFIG_VOICE_STEAL_ALGO) {
1034 schoenebeck 250
1035     // try to pick the oldest voice on the key where the new
1036     // voice should be spawned, if there is no voice on that
1037 schoenebeck 563 // key, or no voice left to kill, then procceed with
1038 schoenebeck 250 // 'oldestkey' algorithm
1039 schoenebeck 460 case voice_steal_algo_oldestvoiceonkey: {
1040     midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
1041 schoenebeck 563 itSelectedVoice = pSelectedKey->pActiveVoices->first();
1042     // proceed iterating if voice was created in this fragment cycle
1043 schoenebeck 663 while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1044 schoenebeck 563 // if we haven't found a voice then proceed with algorithm 'oldestkey'
1045 schoenebeck 663 if (itSelectedVoice && itSelectedVoice->IsStealable()) break;
1046 schoenebeck 250 } // no break - intentional !
1047    
1048     // try to pick the oldest voice on the oldest active key
1049 schoenebeck 563 // from the same engine channel
1050 schoenebeck 460 // (caution: must stay after 'oldestvoiceonkey' algorithm !)
1051 schoenebeck 250 case voice_steal_algo_oldestkey: {
1052 schoenebeck 649 // if we already stole in this fragment, try to proceed on same key
1053 schoenebeck 460 if (this->itLastStolenVoice) {
1054     itSelectedVoice = this->itLastStolenVoice;
1055 schoenebeck 649 do {
1056     ++itSelectedVoice;
1057 schoenebeck 663 } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1058 schoenebeck 649 // found a "stealable" voice ?
1059 schoenebeck 663 if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1060 schoenebeck 649 // remember which voice we stole, so we can simply proceed on next voice stealing
1061     this->itLastStolenVoice = itSelectedVoice;
1062 schoenebeck 460 break; // selection succeeded
1063 schoenebeck 250 }
1064     }
1065 schoenebeck 649 // get (next) oldest key
1066     RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKey) ? ++this->iuiLastStolenKey : pEngineChannel->pActiveKeys->first();
1067     while (iuiSelectedKey) {
1068     midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];
1069 schoenebeck 659 itSelectedVoice = pSelectedKey->pActiveVoices->first();
1070 schoenebeck 649 // proceed iterating if voice was created in this fragment cycle
1071 schoenebeck 663 while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1072 schoenebeck 649 // found a "stealable" voice ?
1073 schoenebeck 663 if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1074 schoenebeck 649 // remember which voice on which key we stole, so we can simply proceed on next voice stealing
1075     this->iuiLastStolenKey = iuiSelectedKey;
1076     this->itLastStolenVoice = itSelectedVoice;
1077     break; // selection succeeded
1078     }
1079     ++iuiSelectedKey; // get next oldest key
1080     }
1081 schoenebeck 250 break;
1082     }
1083    
1084     // don't steal anything
1085     case voice_steal_algo_none:
1086     default: {
1087     dmsg(1,("No free voice (voice stealing disabled)!\n"));
1088 schoenebeck 473 return -1;
1089 schoenebeck 250 }
1090     }
1091    
1092 schoenebeck 563 // if we couldn't steal a voice from the same engine channel then
1093     // steal oldest voice on the oldest key from any other engine channel
1094 schoenebeck 649 // (the smaller engine channel number, the higher priority)
1095 schoenebeck 663 if (!itSelectedVoice || !itSelectedVoice->IsStealable()) {
1096 schoenebeck 649 EngineChannel* pSelectedChannel;
1097     int iChannelIndex;
1098     // select engine channel
1099     if (pLastStolenChannel) {
1100     pSelectedChannel = pLastStolenChannel;
1101     iChannelIndex = pSelectedChannel->iEngineIndexSelf;
1102     } else { // pick the engine channel followed by this engine channel
1103     iChannelIndex = (pEngineChannel->iEngineIndexSelf + 1) % engineChannels.size();
1104     pSelectedChannel = engineChannels[iChannelIndex];
1105     }
1106 schoenebeck 663
1107     // if we already stole in this fragment, try to proceed on same key
1108     if (this->itLastStolenVoiceGlobally) {
1109     itSelectedVoice = this->itLastStolenVoiceGlobally;
1110     do {
1111     ++itSelectedVoice;
1112     } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1113     }
1114    
1115     #if CONFIG_DEVMODE
1116     EngineChannel* pBegin = pSelectedChannel; // to detect endless loop
1117     #endif // CONFIG_DEVMODE
1118    
1119     // did we find a 'stealable' voice?
1120     if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1121     // remember which voice we stole, so we can simply proceed on next voice stealing
1122     this->itLastStolenVoiceGlobally = itSelectedVoice;
1123     } else while (true) { // iterate through engine channels
1124 schoenebeck 649 // get (next) oldest key
1125 schoenebeck 663 RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKeyGlobally) ? ++this->iuiLastStolenKeyGlobally : pSelectedChannel->pActiveKeys->first();
1126     this->iuiLastStolenKeyGlobally = RTList<uint>::Iterator(); // to prevent endless loop (see line above)
1127 schoenebeck 649 while (iuiSelectedKey) {
1128 schoenebeck 663 midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];
1129 schoenebeck 649 itSelectedVoice = pSelectedKey->pActiveVoices->first();
1130     // proceed iterating if voice was created in this fragment cycle
1131 schoenebeck 663 while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1132 schoenebeck 649 // found a "stealable" voice ?
1133 schoenebeck 663 if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1134 schoenebeck 649 // remember which voice on which key on which engine channel we stole, so we can simply proceed on next voice stealing
1135     this->iuiLastStolenKeyGlobally = iuiSelectedKey;
1136     this->itLastStolenVoiceGlobally = itSelectedVoice;
1137     this->pLastStolenChannel = pSelectedChannel;
1138 schoenebeck 665 goto stealable_voice_found; // selection succeeded
1139 schoenebeck 649 }
1140     ++iuiSelectedKey; // get next key on current engine channel
1141     }
1142     // get next engine channel
1143 schoenebeck 460 iChannelIndex = (iChannelIndex + 1) % engineChannels.size();
1144 schoenebeck 649 pSelectedChannel = engineChannels[iChannelIndex];
1145 schoenebeck 663
1146     #if CONFIG_DEVMODE
1147     if (pSelectedChannel == pBegin) {
1148     dmsg(1,("FATAL ERROR: voice stealing endless loop!\n"));
1149     dmsg(1,("VoiceSpawnsLeft=%d.\n", VoiceSpawnsLeft));
1150     dmsg(1,("Exiting.\n"));
1151     exit(-1);
1152     }
1153     #endif // CONFIG_DEVMODE
1154 schoenebeck 460 }
1155     }
1156    
1157 schoenebeck 665 // jump point if a 'stealable' voice was found
1158     stealable_voice_found:
1159    
1160 schoenebeck 563 #if CONFIG_DEVMODE
1161 schoenebeck 473 if (!itSelectedVoice->IsActive()) {
1162     dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
1163     return -1;
1164     }
1165 schoenebeck 563 #endif // CONFIG_DEVMODE
1166 schoenebeck 287
1167 schoenebeck 250 // now kill the selected voice
1168 schoenebeck 659 itSelectedVoice->Kill(itNoteOnEvent);
1169 schoenebeck 460
1170 schoenebeck 663 --VoiceSpawnsLeft;
1171 schoenebeck 473
1172     return 0; // success
1173 schoenebeck 250 }
1174 schoenebeck 473 else {
1175     dmsg(1,("Event pool emtpy!\n"));
1176     return -1;
1177     }
1178 schoenebeck 250 }
1179    
1180     /**
1181 schoenebeck 285 * Removes the given voice from the MIDI key's list of active voices.
1182     * This method will be called when a voice went inactive, e.g. because
1183     * it finished to playback its sample, finished its release stage or
1184     * just was killed.
1185 schoenebeck 53 *
1186 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
1187 schoenebeck 285 * @param itVoice - points to the voice to be freed
1188 schoenebeck 53 */
1189 schoenebeck 411 void Engine::FreeVoice(EngineChannel* pEngineChannel, Pool<Voice>::Iterator& itVoice) {
1190 schoenebeck 271 if (itVoice) {
1191 schoenebeck 411 midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itVoice->MIDIKey];
1192 schoenebeck 53
1193 schoenebeck 271 uint keygroup = itVoice->KeyGroup;
1194    
1195 schoenebeck 53 // free the voice object
1196 schoenebeck 271 pVoicePool->free(itVoice);
1197 schoenebeck 53
1198 schoenebeck 287 // if no other voices left and member of a key group, remove from key group
1199     if (pKey->pActiveVoices->isEmpty() && keygroup) {
1200 schoenebeck 411 uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[keygroup];
1201 schoenebeck 287 if (*ppKeyGroup == &*pKey->itSelf) *ppKeyGroup = NULL; // remove key from key group
1202 schoenebeck 53 }
1203     }
1204 schoenebeck 285 else std::cerr << "Couldn't release voice! (!itVoice)\n" << std::flush;
1205 schoenebeck 53 }
1206    
1207     /**
1208 schoenebeck 287 * Called when there's no more voice left on a key, this call will
1209     * update the key info respectively.
1210     *
1211 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
1212 schoenebeck 287 * @param pKey - key which is now inactive
1213     */
1214 schoenebeck 411 void Engine::FreeKey(EngineChannel* pEngineChannel, midi_key_info_t* pKey) {
1215 schoenebeck 287 if (pKey->pActiveVoices->isEmpty()) {
1216     pKey->Active = false;
1217 schoenebeck 411 pEngineChannel->pActiveKeys->free(pKey->itSelf); // remove key from list of active keys
1218 schoenebeck 287 pKey->itSelf = RTList<uint>::Iterator();
1219     pKey->ReleaseTrigger = false;
1220     pKey->pEvents->clear();
1221     dmsg(3,("Key has no more voices now\n"));
1222     }
1223     else dmsg(1,("gig::Engine: Oops, tried to free a key which contains voices.\n"));
1224     }
1225    
1226     /**
1227 schoenebeck 53 * Reacts on supported control change commands (e.g. pitch bend wheel,
1228     * modulation wheel, aftertouch).
1229     *
1230 schoenebeck 411 * @param pEngineChannel - engine channel on which this event occured on
1231 schoenebeck 271 * @param itControlChangeEvent - controller, value and time stamp of the event
1232 schoenebeck 53 */
1233 schoenebeck 411 void Engine::ProcessControlChange(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itControlChangeEvent) {
1234 schoenebeck 271 dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", itControlChangeEvent->Param.CC.Controller, itControlChangeEvent->Param.CC.Value));
1235 schoenebeck 53
1236 schoenebeck 473 // update controller value in the engine channel's controller table
1237     pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
1238    
1239 schoenebeck 769 switch (itControlChangeEvent->Param.CC.Controller) {
1240 schoenebeck 829 case 5: { // portamento time
1241     pEngineChannel->PortamentoTime = (float) itControlChangeEvent->Param.CC.Value / 127.0f * (float) CONFIG_PORTAMENTO_TIME_MAX + (float) CONFIG_PORTAMENTO_TIME_MIN;
1242     break;
1243     }
1244 schoenebeck 424 case 7: { // volume
1245     //TODO: not sample accurate yet
1246 persson 831 pEngineChannel->GlobalVolume = VolumeCurve[itControlChangeEvent->Param.CC.Value] * CONFIG_GLOBAL_ATTENUATION;
1247 schoenebeck 660 pEngineChannel->bStatusChanged = true; // engine channel status has changed, so set notify flag
1248 schoenebeck 424 break;
1249     }
1250     case 10: { // panpot
1251     //TODO: not sample accurate yet
1252 persson 831 pEngineChannel->GlobalPanLeft = PanCurve[128 - itControlChangeEvent->Param.CC.Value];
1253     pEngineChannel->GlobalPanRight = PanCurve[itControlChangeEvent->Param.CC.Value];
1254 schoenebeck 424 break;
1255     }
1256     case 64: { // sustain
1257 schoenebeck 769 if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {
1258 iliev 776 dmsg(4,("DAMPER (RIGHT) PEDAL DOWN\n"));
1259 schoenebeck 411 pEngineChannel->SustainPedal = true;
1260 schoenebeck 53
1261 iliev 716 #if !CONFIG_PROCESS_MUTED_CHANNELS
1262 schoenebeck 705 if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1263 iliev 716 #endif
1264 schoenebeck 705
1265 schoenebeck 53 // cancel release process of voices if necessary
1266 schoenebeck 411 RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1267 schoenebeck 473 for (; iuiKey; ++iuiKey) {
1268     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1269     if (!pKey->KeyPressed) {
1270     RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1271     if (itNewEvent) {
1272 schoenebeck 769 *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1273 schoenebeck 473 itNewEvent->Type = Event::type_cancel_release; // transform event type
1274 schoenebeck 53 }
1275 schoenebeck 473 else dmsg(1,("Event pool emtpy!\n"));
1276 schoenebeck 53 }
1277     }
1278     }
1279 schoenebeck 769 if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {
1280 iliev 776 dmsg(4,("DAMPER (RIGHT) PEDAL UP\n"));
1281 schoenebeck 411 pEngineChannel->SustainPedal = false;
1282 schoenebeck 53
1283 iliev 716 #if !CONFIG_PROCESS_MUTED_CHANNELS
1284 schoenebeck 705 if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1285 iliev 716 #endif
1286 schoenebeck 705
1287 schoenebeck 53 // release voices if their respective key is not pressed
1288 schoenebeck 411 RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1289 schoenebeck 473 for (; iuiKey; ++iuiKey) {
1290     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1291 iliev 776 if (!pKey->KeyPressed && ShouldReleaseVoice(pEngineChannel, *iuiKey)) {
1292 schoenebeck 473 RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1293     if (itNewEvent) {
1294 schoenebeck 769 *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1295 schoenebeck 473 itNewEvent->Type = Event::type_release; // transform event type
1296 schoenebeck 53 }
1297 schoenebeck 473 else dmsg(1,("Event pool emtpy!\n"));
1298 schoenebeck 53 }
1299     }
1300     }
1301     break;
1302     }
1303 schoenebeck 829 case 65: { // portamento on / off
1304     KillAllVoices(pEngineChannel, itControlChangeEvent);
1305     pEngineChannel->PortamentoMode = itControlChangeEvent->Param.CC.Value >= 64;
1306     break;
1307     }
1308 iliev 776 case 66: { // sostenuto
1309     if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SostenutoPedal) {
1310     dmsg(4,("SOSTENUTO (CENTER) PEDAL DOWN\n"));
1311     pEngineChannel->SostenutoPedal = true;
1312 schoenebeck 53
1313 iliev 776 #if !CONFIG_PROCESS_MUTED_CHANNELS
1314     if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1315     #endif
1316 schoenebeck 53
1317 iliev 776 SostenutoKeyCount = 0;
1318     // Remeber the pressed keys
1319     RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1320     for (; iuiKey; ++iuiKey) {
1321     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1322     if (pKey->KeyPressed && SostenutoKeyCount < 128) SostenutoKeys[SostenutoKeyCount++] = *iuiKey;
1323     }
1324     }
1325     if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SostenutoPedal) {
1326     dmsg(4,("SOSTENUTO (CENTER) PEDAL UP\n"));
1327     pEngineChannel->SostenutoPedal = false;
1328    
1329     #if !CONFIG_PROCESS_MUTED_CHANNELS
1330     if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1331     #endif
1332    
1333     // release voices if the damper pedal is up and their respective key is not pressed
1334     for (int i = 0; i < SostenutoKeyCount; i++) {
1335     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[SostenutoKeys[i]];
1336     if (!pKey->KeyPressed && !pEngineChannel->SustainPedal) {
1337     RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1338     if (itNewEvent) {
1339     *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1340     itNewEvent->Type = Event::type_release; // transform event type
1341     }
1342     else dmsg(1,("Event pool emtpy!\n"));
1343     }
1344     }
1345     }
1346     break;
1347     }
1348    
1349    
1350 schoenebeck 473 // Channel Mode Messages
1351    
1352     case 120: { // all sound off
1353 schoenebeck 769 KillAllVoices(pEngineChannel, itControlChangeEvent);
1354 schoenebeck 473 break;
1355     }
1356     case 121: { // reset all controllers
1357     pEngineChannel->ResetControllers();
1358     break;
1359     }
1360     case 123: { // all notes off
1361 schoenebeck 849 #if CONFIG_PROCESS_ALL_NOTES_OFF
1362 schoenebeck 769 ReleaseAllVoices(pEngineChannel, itControlChangeEvent);
1363 schoenebeck 849 #endif // CONFIG_PROCESS_ALL_NOTES_OFF
1364 schoenebeck 473 break;
1365     }
1366 schoenebeck 829 case 126: { // mono mode on
1367     KillAllVoices(pEngineChannel, itControlChangeEvent);
1368     pEngineChannel->SoloMode = true;
1369     break;
1370     }
1371     case 127: { // poly mode on
1372     KillAllVoices(pEngineChannel, itControlChangeEvent);
1373     pEngineChannel->SoloMode = false;
1374     break;
1375     }
1376 schoenebeck 473 }
1377 schoenebeck 53 }
1378    
1379     /**
1380 schoenebeck 244 * Reacts on MIDI system exclusive messages.
1381     *
1382 schoenebeck 271 * @param itSysexEvent - sysex data size and time stamp of the sysex event
1383 schoenebeck 244 */
1384 schoenebeck 271 void Engine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) {
1385 schoenebeck 244 RingBuffer<uint8_t>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();
1386    
1387     uint8_t exclusive_status, id;
1388     if (!reader.pop(&exclusive_status)) goto free_sysex_data;
1389     if (!reader.pop(&id)) goto free_sysex_data;
1390     if (exclusive_status != 0xF0) goto free_sysex_data;
1391    
1392     switch (id) {
1393     case 0x41: { // Roland
1394 schoenebeck 493 dmsg(3,("Roland Sysex\n"));
1395 schoenebeck 244 uint8_t device_id, model_id, cmd_id;
1396     if (!reader.pop(&device_id)) goto free_sysex_data;
1397     if (!reader.pop(&model_id)) goto free_sysex_data;
1398     if (!reader.pop(&cmd_id)) goto free_sysex_data;
1399     if (model_id != 0x42 /*GS*/) goto free_sysex_data;
1400     if (cmd_id != 0x12 /*DT1*/) goto free_sysex_data;
1401    
1402     // command address
1403     uint8_t addr[3]; // 2 byte addr MSB, followed by 1 byte addr LSB)
1404     const RingBuffer<uint8_t>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later
1405     if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;
1406     if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters
1407 schoenebeck 493 dmsg(3,("\tSystem Parameter\n"));
1408 schoenebeck 244 }
1409     else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters
1410 schoenebeck 493 dmsg(3,("\tCommon Parameter\n"));
1411 schoenebeck 244 }
1412     else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)
1413 schoenebeck 493 dmsg(3,("\tPart Parameter\n"));
1414     switch (addr[2]) {
1415 schoenebeck 244 case 0x40: { // scale tuning
1416 schoenebeck 493 dmsg(3,("\t\tScale Tuning\n"));
1417 schoenebeck 244 uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave
1418     if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;
1419     uint8_t checksum;
1420 schoenebeck 493 if (!reader.pop(&checksum)) goto free_sysex_data;
1421 schoenebeck 563 #if CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1422     if (GSCheckSum(checksum_reader, 12)) goto free_sysex_data;
1423     #endif // CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1424 schoenebeck 244 for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;
1425     AdjustScale((int8_t*) scale_tunes);
1426 schoenebeck 493 dmsg(3,("\t\t\tNew scale applied.\n"));
1427 schoenebeck 244 break;
1428     }
1429     }
1430     }
1431     else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x20) { // Part Parameters (2)
1432     }
1433     else if (addr[0] == 0x41) { // Drum Setup Parameters
1434     }
1435     break;
1436     }
1437     }
1438    
1439     free_sysex_data: // finally free sysex data
1440 schoenebeck 271 pSysexBuffer->increment_read_ptr(itSysexEvent->Param.Sysex.Size);
1441 schoenebeck 244 }
1442    
1443     /**
1444     * Calculates the Roland GS sysex check sum.
1445     *
1446     * @param AddrReader - reader which currently points to the first GS
1447     * command address byte of the GS sysex message in
1448     * question
1449     * @param DataSize - size of the GS message data (in bytes)
1450     */
1451     uint8_t Engine::GSCheckSum(const RingBuffer<uint8_t>::NonVolatileReader AddrReader, uint DataSize) {
1452     RingBuffer<uint8_t>::NonVolatileReader reader = AddrReader;
1453     uint bytes = 3 /*addr*/ + DataSize;
1454     uint8_t addr_and_data[bytes];
1455     reader.read(&addr_and_data[0], bytes);
1456     uint8_t sum = 0;
1457     for (uint i = 0; i < bytes; i++) sum += addr_and_data[i];
1458     return 128 - sum % 128;
1459     }
1460    
1461     /**
1462     * Allows to tune each of the twelve semitones of an octave.
1463     *
1464     * @param ScaleTunes - detuning of all twelve semitones (in cents)
1465     */
1466     void Engine::AdjustScale(int8_t ScaleTunes[12]) {
1467     memcpy(&this->ScaleTuning[0], &ScaleTunes[0], 12); //TODO: currently not sample accurate
1468     }
1469    
1470     /**
1471 schoenebeck 473 * Releases all voices on an engine channel. All voices will go into
1472     * the release stage and thus it might take some time (e.g. dependant to
1473     * their envelope release time) until they actually die.
1474     *
1475     * @param pEngineChannel - engine channel on which all voices should be released
1476     * @param itReleaseEvent - event which caused this releasing of all voices
1477     */
1478     void Engine::ReleaseAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itReleaseEvent) {
1479     RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1480     while (iuiKey) {
1481     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1482     ++iuiKey;
1483     // append a 'release' event to the key's own event list
1484     RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1485     if (itNewEvent) {
1486     *itNewEvent = *itReleaseEvent; // copy original event (to the key's event list)
1487     itNewEvent->Type = Event::type_release; // transform event type
1488     }
1489     else dmsg(1,("Event pool emtpy!\n"));
1490     }
1491     }
1492    
1493     /**
1494     * Kills all voices on an engine channel as soon as possible. Voices
1495     * won't get into release state, their volume level will be ramped down
1496     * as fast as possible.
1497     *
1498     * @param pEngineChannel - engine channel on which all voices should be killed
1499     * @param itKillEvent - event which caused this killing of all voices
1500     */
1501     void Engine::KillAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itKillEvent) {
1502     RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1503     RTList<uint>::Iterator end = pEngineChannel->pActiveKeys->end();
1504     while (iuiKey != end) { // iterate through all active keys
1505     midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1506     ++iuiKey;
1507     RTList<Voice>::Iterator itVoice = pKey->pActiveVoices->first();
1508     RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
1509     for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
1510     itVoice->Kill(itKillEvent);
1511 schoenebeck 663 --VoiceSpawnsLeft; //FIXME: just a temporary workaround, we should check the cause in StealVoice() instead
1512 schoenebeck 473 }
1513     }
1514     }
1515    
1516 iliev 776 /**
1517     * Determines whether the specified voice should be released.
1518     *
1519     * @param pEngineChannel - The engine channel on which the voice should be checked
1520     * @param Key - The key number
1521     * @returns true if the specified should be released, false otherwise.
1522     */
1523     bool Engine::ShouldReleaseVoice(EngineChannel* pEngineChannel, int Key) {
1524     if (pEngineChannel->SustainPedal) return false;
1525    
1526     if (pEngineChannel->SostenutoPedal) {
1527     for (int i = 0; i < SostenutoKeyCount; i++)
1528     if (Key == SostenutoKeys[i]) return false;
1529     }
1530    
1531     return true;
1532     }
1533    
1534 schoenebeck 53 uint Engine::VoiceCount() {
1535     return ActiveVoiceCount;
1536     }
1537    
1538     uint Engine::VoiceCountMax() {
1539     return ActiveVoiceCountMax;
1540     }
1541    
1542     bool Engine::DiskStreamSupported() {
1543     return true;
1544     }
1545    
1546     uint Engine::DiskStreamCount() {
1547     return (pDiskThread) ? pDiskThread->ActiveStreamCount : 0;
1548     }
1549    
1550     uint Engine::DiskStreamCountMax() {
1551     return (pDiskThread) ? pDiskThread->ActiveStreamCountMax : 0;
1552     }
1553    
1554     String Engine::DiskStreamBufferFillBytes() {
1555     return pDiskThread->GetBufferFillBytes();
1556     }
1557    
1558     String Engine::DiskStreamBufferFillPercentage() {
1559     return pDiskThread->GetBufferFillPercentage();
1560     }
1561    
1562 senkov 112 String Engine::EngineName() {
1563 schoenebeck 475 return LS_GIG_ENGINE_NAME;
1564 senkov 112 }
1565    
1566 schoenebeck 53 String Engine::Description() {
1567     return "Gigasampler Engine";
1568     }
1569    
1570     String Engine::Version() {
1571 schoenebeck 924 String s = "$Revision: 1.65 $";
1572 schoenebeck 123 return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword
1573 schoenebeck 53 }
1574    
1575 persson 831 // static constant initializers
1576     const float* Engine::VolumeCurve(InitVolumeCurve());
1577     const float* Engine::PanCurve(InitPanCurve());
1578 persson 832 const float* Engine::CrossfadeCurve(InitCrossfadeCurve());
1579 persson 831
1580     float* Engine::InitVolumeCurve() {
1581     // line-segment approximation
1582     const float segments[] = {
1583     0, 0, 2, 0.0046, 16, 0.016, 31, 0.051, 45, 0.115, 54.5, 0.2,
1584     64.5, 0.39, 74, 0.74, 92, 1.03, 114, 1.94, 119.2, 2.2, 127, 2.2
1585     };
1586     return InitCurve(segments);
1587     }
1588    
1589     float* Engine::InitPanCurve() {
1590     // line-segment approximation
1591     const float segments[] = {
1592     0, 0, 1, 0,
1593     2, 0.05, 31.5, 0.7, 51, 0.851, 74.5, 1.12,
1594     127, 1.41, 128, 1.41
1595     };
1596     return InitCurve(segments, 129);
1597     }
1598    
1599 persson 832 float* Engine::InitCrossfadeCurve() {
1600     // line-segment approximation
1601     const float segments[] = {
1602     0, 0, 1, 0.03, 10, 0.1, 51, 0.58, 127, 1
1603     };
1604     return InitCurve(segments);
1605     }
1606    
1607 persson 831 float* Engine::InitCurve(const float* segments, int size) {
1608     float* y = new float[size];
1609     for (int x = 0 ; x < size ; x++) {
1610     if (x > segments[2]) segments += 2;
1611     y[x] = segments[1] + (x - segments[0]) *
1612     (segments[3] - segments[1]) / (segments[2] - segments[0]);
1613     }
1614     return y;
1615     }
1616    
1617 schoenebeck 53 }} // namespace LinuxSampler::gig

  ViewVC Help
Powered by ViewVC