/[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 1038 - (hide annotations) (download)
Sat Feb 3 15:33:00 2007 UTC (17 years, 2 months ago) by persson
File size: 85165 byte(s)
* playback is no longer disabled during instrument loading
* all notes playing on a channel that changes its instrument keep
  playing with the old instrument until they get a note off command
* new thread safety fix for lscp "load engine" and "set channel audio
  output device"

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

  ViewVC Help
Powered by ViewVC