/[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 829 - (hide annotations) (download)
Sat Jan 14 14:07:47 2006 UTC (13 years, 9 months ago) by schoenebeck
File size: 76130 byte(s)
* implemented portamento mode and solo mode (a.k.a 'mono mode'):
  all modes can be altered via standard GM messages, that is CC5 for
  altering portamento time, CC65 for enabling / disabling portamento
  mode, CC126 for enabling solo mode and CC127 for disabling solo mode
* fixed EG3 (pitch envelope) synthesis which was neutral all the time
* configure.in: do not automatically pick optimized gcc flags if the user
  already provided some on his own (as CXXFLAGS)

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

  ViewVC Help
Powered by ViewVC