1 |
/*************************************************************************** |
2 |
* * |
3 |
* LinuxSampler - modular, streaming capable sampler * |
4 |
* * |
5 |
* Copyright (C) 2003,2004 by Benno Senoner and Christian Schoenebeck * |
6 |
* Copyright (C) 2005-2007 Christian Schoenebeck * |
7 |
* * |
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 |
#include "EGADSR.h" |
28 |
#include "../EngineFactory.h" |
29 |
|
30 |
#include "Engine.h" |
31 |
|
32 |
namespace LinuxSampler { namespace gig { |
33 |
|
34 |
InstrumentResourceManager Engine::instruments; |
35 |
|
36 |
std::map<AudioOutputDevice*,Engine*> Engine::engines; |
37 |
|
38 |
/** |
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 |
Engine* Engine::AcquireEngine(LinuxSampler::gig::EngineChannel* pChannel, AudioOutputDevice* pDevice) { |
49 |
Engine* pEngine = NULL; |
50 |
// check if there's already an engine for the given audio output device |
51 |
if (engines.count(pDevice)) { |
52 |
dmsg(4,("Using existing gig::Engine.\n")); |
53 |
pEngine = engines[pDevice]; |
54 |
} else { // create a new engine (and disk thread) instance for the given audio output device |
55 |
dmsg(4,("Creating new gig::Engine.\n")); |
56 |
pEngine = (Engine*) EngineFactory::Create("gig"); |
57 |
pEngine->Connect(pDevice); |
58 |
engines[pDevice] = pEngine; |
59 |
} |
60 |
|
61 |
// register engine channel to the engine instance |
62 |
|
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 |
pEngine->engineChannels.add(pChannel); |
69 |
// remember index in the ArrayList |
70 |
pChannel->iEngineIndexSelf = pEngine->engineChannels.size() - 1; |
71 |
dmsg(4,("This gig::Engine has now %d EngineChannels.\n",pEngine->engineChannels.size())); |
72 |
return pEngine; |
73 |
} |
74 |
|
75 |
/** |
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 |
void Engine::FreeEngine(LinuxSampler::gig::EngineChannel* pChannel, AudioOutputDevice* pDevice) { |
86 |
dmsg(4,("Disconnecting EngineChannel from gig::Engine.\n")); |
87 |
Engine* pEngine = engines[pDevice]; |
88 |
// 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 |
} |
99 |
|
100 |
/** |
101 |
* Constructor |
102 |
*/ |
103 |
Engine::Engine() { |
104 |
pAudioOutputDevice = NULL; |
105 |
pDiskThread = NULL; |
106 |
pEventGenerator = NULL; |
107 |
pSysexBuffer = new RingBuffer<uint8_t,false>(CONFIG_SYSEX_BUFFER_SIZE, 0); |
108 |
pEventQueue = new RingBuffer<Event,false>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0); |
109 |
pEventPool = new Pool<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT); |
110 |
pVoicePool = new Pool<Voice>(CONFIG_MAX_VOICES); |
111 |
pDimRegionsInUse = new ::gig::DimensionRegion*[CONFIG_MAX_VOICES + 1]; |
112 |
pVoiceStealingQueue = new RTList<Event>(pEventPool); |
113 |
pGlobalEvents = new RTList<Event>(pEventPool); |
114 |
InstrumentChangeQueue = new RingBuffer<instrument_change_command_t,false>(1, 0); |
115 |
InstrumentChangeReplyQueue = new RingBuffer<instrument_change_reply_t,false>(1, 0); |
116 |
|
117 |
for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) { |
118 |
iterVoice->SetEngine(this); |
119 |
} |
120 |
pVoicePool->clear(); |
121 |
|
122 |
ResetInternal(); |
123 |
ResetScaleTuning(); |
124 |
} |
125 |
|
126 |
/** |
127 |
* Destructor |
128 |
*/ |
129 |
Engine::~Engine() { |
130 |
MidiInputPort::RemoveSysexListener(this); |
131 |
if (pDiskThread) { |
132 |
dmsg(1,("Stopping disk thread...")); |
133 |
pDiskThread->StopThread(); |
134 |
delete pDiskThread; |
135 |
dmsg(1,("OK\n")); |
136 |
} |
137 |
if (pEventQueue) delete pEventQueue; |
138 |
if (pEventPool) delete pEventPool; |
139 |
if (pVoicePool) { |
140 |
pVoicePool->clear(); |
141 |
delete pVoicePool; |
142 |
} |
143 |
if (pEventGenerator) delete pEventGenerator; |
144 |
if (pVoiceStealingQueue) delete pVoiceStealingQueue; |
145 |
if (pSysexBuffer) delete pSysexBuffer; |
146 |
Unregister(); |
147 |
} |
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 |
dmsg(3,("gig::Engine: enabled (val=%d)\n", EngineDisabled.GetUnsafe())); |
153 |
} |
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 |
ResetScaleTuning(); |
175 |
Enable(); |
176 |
} |
177 |
|
178 |
/** |
179 |
* Reset all voices and disk thread and clear input event queue and all |
180 |
* control and status variables. This method is protected by a mutex. |
181 |
*/ |
182 |
void Engine::ResetInternal() { |
183 |
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 |
ActiveVoiceCount = 0; |
189 |
ActiveVoiceCountMax = 0; |
190 |
|
191 |
// reset voice stealing parameters |
192 |
pVoiceStealingQueue->clear(); |
193 |
itLastStolenVoice = RTList<Voice>::Iterator(); |
194 |
itLastStolenVoiceGlobally = RTList<Voice>::Iterator(); |
195 |
iuiLastStolenKey = RTList<uint>::Iterator(); |
196 |
iuiLastStolenKeyGlobally = RTList<uint>::Iterator(); |
197 |
pLastStolenChannel = NULL; |
198 |
|
199 |
// reset all voices |
200 |
for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) { |
201 |
iterVoice->Reset(); |
202 |
} |
203 |
pVoicePool->clear(); |
204 |
|
205 |
// reset disk thread |
206 |
if (pDiskThread) pDiskThread->Reset(); |
207 |
|
208 |
// delete all input events |
209 |
pEventQueue->init(); |
210 |
pSysexBuffer->init(); |
211 |
if (sysexDisabled) MidiInputPort::AddSysexListener(this); |
212 |
ResetInternalMutex.Unlock(); |
213 |
} |
214 |
|
215 |
/** |
216 |
* Reset to normal, chromatic scale (means equal tempered). |
217 |
*/ |
218 |
void Engine::ResetScaleTuning() { |
219 |
memset(&ScaleTuning[0], 0x00, 12); |
220 |
} |
221 |
|
222 |
/** |
223 |
* 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 |
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 |
throw Exception(msg); |
243 |
} |
244 |
|
245 |
this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle(); |
246 |
this->SampleRate = pAudioOutputDevice->SampleRate(); |
247 |
|
248 |
// FIXME: audio drivers with varying fragment sizes might be a problem here |
249 |
MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * CONFIG_EG_MIN_RELEASE_TIME) - 1; |
250 |
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 |
<< "May lead to click sounds if voice stealing chimes in!\n" << std::flush; |
254 |
// 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 |
iterVoice->EG1.CalculateFadeOutCoeff(minReleaseTime, SampleRate); |
260 |
} |
261 |
pVoicePool->clear(); |
262 |
} |
263 |
|
264 |
// (re)create disk thread |
265 |
if (this->pDiskThread) { |
266 |
dmsg(1,("Stopping disk thread...")); |
267 |
this->pDiskThread->StopThread(); |
268 |
delete this->pDiskThread; |
269 |
dmsg(1,("OK\n")); |
270 |
} |
271 |
this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << CONFIG_MAX_PITCH) << 1) + 6, //FIXME: assuming stereo |
272 |
&instruments); |
273 |
if (!pDiskThread) { |
274 |
dmsg(0,("gig::Engine new diskthread = NULL\n")); |
275 |
exit(EXIT_FAILURE); |
276 |
} |
277 |
|
278 |
for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) { |
279 |
iterVoice->pDiskThread = this->pDiskThread; |
280 |
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 |
for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) { |
293 |
if (!iterVoice->pDiskThread) { |
294 |
dmsg(0,("Engine -> voice::trigger: !pDiskThread\n")); |
295 |
exit(EXIT_FAILURE); |
296 |
} |
297 |
} |
298 |
} |
299 |
|
300 |
/** |
301 |
* Clear all engine global event lists. |
302 |
*/ |
303 |
void Engine::ClearEventLists() { |
304 |
pGlobalEvents->clear(); |
305 |
} |
306 |
|
307 |
/** |
308 |
* 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 |
* |
317 |
* @param Samples - number of sample points to be processed in the |
318 |
* current audio cycle |
319 |
*/ |
320 |
void Engine::ImportEvents(uint Samples) { |
321 |
RingBuffer<Event,false>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader(); |
322 |
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 |
if (pGlobalEvents->poolIsEmpty()) { |
335 |
dmsg(1,("Event pool emtpy!\n")); |
336 |
break; |
337 |
} |
338 |
*pGlobalEvents->allocAppend() = *pEvent; |
339 |
} |
340 |
eventQueueReader.free(); // free all copied events from input queue |
341 |
} |
342 |
|
343 |
/** |
344 |
* 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 |
* |
351 |
* @param Samples - number of sample points to be rendered |
352 |
* @returns 0 on success |
353 |
*/ |
354 |
int Engine::RenderAudio(uint Samples) { |
355 |
dmsg(7,("RenderAudio(Samples=%d)\n", Samples)); |
356 |
|
357 |
// return if engine disabled |
358 |
if (EngineDisabled.Pop()) { |
359 |
dmsg(5,("gig::Engine: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe())); |
360 |
return 0; |
361 |
} |
362 |
|
363 |
// update time of start and end of this audio fragment (as events' time stamps relate to this) |
364 |
pEventGenerator->UpdateFragmentTime(Samples); |
365 |
|
366 |
// 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 |
// 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 |
ImportEvents(Samples); |
374 |
|
375 |
// process engine global events (these are currently only MIDI System Exclusive messages) |
376 |
{ |
377 |
RTList<Event>::Iterator itEvent = pGlobalEvents->first(); |
378 |
RTList<Event>::Iterator end = pGlobalEvents->end(); |
379 |
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 |
} |
388 |
|
389 |
// reset internal voice counter (just for statistic of active voices) |
390 |
ActiveVoiceCountTemp = 0; |
391 |
|
392 |
// 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 |
// handle events on all engine channels |
426 |
for (int i = 0; i < engineChannels.size(); i++) { |
427 |
ProcessEvents(engineChannels[i], Samples); |
428 |
} |
429 |
|
430 |
// render all 'normal', active voices on all engine channels |
431 |
for (int i = 0; i < engineChannels.size(); i++) { |
432 |
RenderActiveVoices(engineChannels[i], Samples); |
433 |
} |
434 |
|
435 |
// now that all ordinary voices on ALL engine channels are rendered, render new stolen voices |
436 |
RenderStolenVoices(Samples); |
437 |
|
438 |
// 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 |
// 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 |
// just some statistics about this engine instance |
457 |
ActiveVoiceCount = ActiveVoiceCountTemp; |
458 |
if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount; |
459 |
|
460 |
FrameTime += Samples; |
461 |
|
462 |
return 0; |
463 |
} |
464 |
|
465 |
/** |
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 |
void Engine::ProcessEvents(EngineChannel* pEngineChannel, uint Samples) { |
475 |
// 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 |
pEngineChannel->ImportEvents(Samples); |
478 |
|
479 |
// process events |
480 |
{ |
481 |
RTList<Event>::Iterator itEvent = pEngineChannel->pEvents->first(); |
482 |
RTList<Event>::Iterator end = pEngineChannel->pEvents->end(); |
483 |
for (; itEvent != end; ++itEvent) { |
484 |
switch (itEvent->Type) { |
485 |
case Event::type_note_on: |
486 |
dmsg(5,("Engine: Note on received\n")); |
487 |
ProcessNoteOn((EngineChannel*)itEvent->pEngineChannel, itEvent); |
488 |
break; |
489 |
case Event::type_note_off: |
490 |
dmsg(5,("Engine: Note off received\n")); |
491 |
ProcessNoteOff((EngineChannel*)itEvent->pEngineChannel, itEvent); |
492 |
break; |
493 |
case Event::type_control_change: |
494 |
dmsg(5,("Engine: MIDI CC received\n")); |
495 |
ProcessControlChange((EngineChannel*)itEvent->pEngineChannel, itEvent); |
496 |
break; |
497 |
case Event::type_pitchbend: |
498 |
dmsg(5,("Engine: Pitchbend received\n")); |
499 |
ProcessPitchbend((EngineChannel*)itEvent->pEngineChannel, itEvent); |
500 |
break; |
501 |
} |
502 |
} |
503 |
} |
504 |
|
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 |
} |
512 |
|
513 |
/** |
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 |
void Engine::RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) { |
523 |
#if !CONFIG_PROCESS_MUTED_CHANNELS |
524 |
if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted |
525 |
#endif |
526 |
|
527 |
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 |
|
533 |
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 |
} |
542 |
} |
543 |
} |
544 |
} |
545 |
|
546 |
/** |
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 |
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 |
if (!pEngineChannel->pInstrument) continue; // ignore if no instrument loaded |
565 |
Pool<Voice>::Iterator itNewVoice = |
566 |
LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false, false); |
567 |
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 |
} |
573 |
} |
574 |
else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n")); |
575 |
|
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 |
} |
581 |
} |
582 |
|
583 |
/** |
584 |
* 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 |
pEngineChannel->pChannelLeft->MixTo(pDstL, Samples); |
602 |
pEngineChannel->pChannelRight->MixTo(pDstR, Samples); |
603 |
} |
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 |
} else pEngineChannel->pChannelLeft->MixTo(pDstL, Samples, pFxSend->Level()); |
617 |
} |
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 |
} else pEngineChannel->pChannelRight->MixTo(pDstR, Samples, pFxSend->Level()); |
627 |
} |
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 |
* 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 |
void Engine::PostProcess(EngineChannel* pEngineChannel) { |
643 |
// free all keys which have no active voices left |
644 |
{ |
645 |
RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first(); |
646 |
RTList<uint>::Iterator end = pEngineChannel->pActiveKeys->end(); |
647 |
while (iuiKey != end) { // iterate through all active keys |
648 |
midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey]; |
649 |
++iuiKey; |
650 |
if (pKey->pActiveVoices->isEmpty()) FreeKey(pEngineChannel, pKey); |
651 |
#if CONFIG_DEVMODE |
652 |
else { // just a sanity check for debugging |
653 |
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 |
#endif // CONFIG_DEVMODE |
662 |
} |
663 |
} |
664 |
|
665 |
// empty the engine channel's own event lists |
666 |
pEngineChannel->ClearEventLists(); |
667 |
} |
668 |
|
669 |
/** |
670 |
* 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 |
Event event = pEventGenerator->CreateEvent(); |
678 |
event.Type = Event::type_sysex; |
679 |
event.Param.Sysex.Size = Size; |
680 |
event.pEngineChannel = NULL; // as Engine global event |
681 |
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 |
else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,CONFIG_SYSEX_BUFFER_SIZE)); |
697 |
} |
698 |
else dmsg(1,("Engine: Input event queue full!")); |
699 |
} |
700 |
|
701 |
/** |
702 |
* Assigns and triggers a new voice for the respective MIDI key. |
703 |
* |
704 |
* @param pEngineChannel - engine channel on which this event occured on |
705 |
* @param itNoteOnEvent - key, velocity and time stamp of the event |
706 |
*/ |
707 |
void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) { |
708 |
#if !CONFIG_PROCESS_MUTED_CHANNELS |
709 |
if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted |
710 |
#endif |
711 |
|
712 |
if (!pEngineChannel->pInstrument) return; // ignore if no instrument loaded |
713 |
|
714 |
const int key = itNoteOnEvent->Param.Note.Key; |
715 |
midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key]; |
716 |
|
717 |
// 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 |
// Change key dimension value if key is in keyswitching area |
746 |
{ |
747 |
const ::gig::Instrument* pInstrument = pEngineChannel->pInstrument; |
748 |
if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high) |
749 |
pEngineChannel->CurrentKeyDimension = float(key - pInstrument->DimensionKeyRange.low) / |
750 |
(pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1); |
751 |
} |
752 |
|
753 |
pKey->KeyPressed = true; // the MIDI key was now pressed down |
754 |
pKey->Velocity = itNoteOnEventOnKeyList->Param.Note.Velocity; |
755 |
pKey->NoteOnTime = FrameTime + itNoteOnEventOnKeyList->FragmentPos(); // will be used to calculate note length |
756 |
|
757 |
// cancel release process of voices on this key if needed |
758 |
if (pKey->Active && !pEngineChannel->SustainPedal) { |
759 |
RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend(); |
760 |
if (itCancelReleaseEvent) { |
761 |
*itCancelReleaseEvent = *itNoteOnEventOnKeyList; // copy event |
762 |
itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type |
763 |
} |
764 |
else dmsg(1,("Event pool emtpy!\n")); |
765 |
} |
766 |
|
767 |
// 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 |
LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true, true); |
776 |
} |
777 |
} |
778 |
|
779 |
// 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 |
if (!pEngineChannel->SoloMode || pEngineChannel->PortamentoPos < 0.0f) pEngineChannel->PortamentoPos = (float) key; |
784 |
pKey->RoundRobinIndex++; |
785 |
} |
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 |
* @param pEngineChannel - engine channel on which this event occured on |
794 |
* @param itNoteOffEvent - key, velocity and time stamp of the event |
795 |
*/ |
796 |
void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) { |
797 |
#if !CONFIG_PROCESS_MUTED_CHANNELS |
798 |
if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted |
799 |
#endif |
800 |
|
801 |
const int iKey = itNoteOffEvent->Param.Note.Key; |
802 |
midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[iKey]; |
803 |
pKey->KeyPressed = false; // the MIDI key was now released |
804 |
|
805 |
// move event to the key's own event list |
806 |
RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents); |
807 |
|
808 |
bool bShouldRelease = pKey->Active && ShouldReleaseVoice(pEngineChannel, itNoteOffEventOnKeyList->Param.Note.Key); |
809 |
|
810 |
// in case Solo Mode is enabled, kill all voices on this key and respawn a voice on the highest pressed key (if any) |
811 |
if (pEngineChannel->SoloMode && pEngineChannel->pInstrument) { //TODO: this feels like too much code just for handling solo mode :P |
812 |
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 |
// spawn release triggered voice(s) if needed |
874 |
if (pKey->ReleaseTrigger && pEngineChannel->pInstrument) { |
875 |
// 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 |
|
880 |
// MIDI note-on velocity is used instead of note-off velocity |
881 |
itNoteOffEventOnKeyList->Param.Note.Velocity = pKey->Velocity; |
882 |
|
883 |
// now launch the required amount of voices |
884 |
for (int i = 0; i < voicesRequired; i++) |
885 |
LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, i, true, false, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples |
886 |
} |
887 |
pKey->ReleaseTrigger = false; |
888 |
} |
889 |
} |
890 |
|
891 |
// 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 |
} |
895 |
|
896 |
/** |
897 |
* 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 |
* |
901 |
* @param pEngineChannel - engine channel on which this event occured on |
902 |
* @param itPitchbendEvent - absolute pitch value and time stamp of the event |
903 |
*/ |
904 |
void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) { |
905 |
pEngineChannel->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value |
906 |
} |
907 |
|
908 |
/** |
909 |
* 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 |
* @param pEngineChannel - engine channel on which this event occured on |
914 |
* @param itNoteOnEvent - key, velocity and time stamp of the event |
915 |
* @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 |
* @param VoiceStealing - if voice stealing should be performed |
920 |
* when there is no free voice |
921 |
* (optional, default = true) |
922 |
* @param HandleKeyGroupConflicts - if voices should be killed due to a |
923 |
* key group conflict |
924 |
* @returns pointer to new voice or NULL if there was no free voice or |
925 |
* if the voice wasn't triggered (for example when no region is |
926 |
* defined for the given key). |
927 |
*/ |
928 |
Pool<Voice>::Iterator Engine::LaunchVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing, bool HandleKeyGroupConflicts) { |
929 |
int MIDIKey = itNoteOnEvent->Param.Note.Key; |
930 |
midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[MIDIKey]; |
931 |
::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(MIDIKey); |
932 |
|
933 |
// if nothing defined for this key |
934 |
if (!pRegion) return Pool<Voice>::Iterator(); // nothing to do |
935 |
|
936 |
// 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 |
// 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 |
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 |
DimValues[i] = pEngineChannel->ControllerTable[128]; |
978 |
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 |
DimValues[i] = (uint) (pEngineChannel->CurrentKeyDimension * pRegion->pDimensionDefinitions[i].zones); |
985 |
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 |
|
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 |
::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 |
// allocate a new voice for the key |
1081 |
Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend(); |
1082 |
if (itNewVoice) { |
1083 |
// launch the new voice |
1084 |
if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pDimRgn, VoiceType, iKeyGroup) < 0) { |
1085 |
dmsg(4,("Voice not triggered\n")); |
1086 |
pKey->pActiveVoices->free(itNewVoice); |
1087 |
} |
1088 |
else { // on success |
1089 |
--VoiceSpawnsLeft; |
1090 |
if (!pKey->Active) { // mark as active key |
1091 |
pKey->Active = true; |
1092 |
pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend(); |
1093 |
*pKey->itSelf = itNoteOnEvent->Param.Note.Key; |
1094 |
} |
1095 |
if (itNewVoice->KeyGroup) { |
1096 |
uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup]; |
1097 |
*ppKeyGroup = &*pKey->itSelf; // put key as the (new) active key to its key group |
1098 |
} |
1099 |
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 |
} |
1102 |
} |
1103 |
else if (VoiceStealing) { |
1104 |
// try to steal one voice |
1105 |
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 |
} |
1117 |
} |
1118 |
|
1119 |
return Pool<Voice>::Iterator(); // no free voice or error |
1120 |
} |
1121 |
|
1122 |
/** |
1123 |
* 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 |
* @param pEngineChannel - engine channel on which this event occured on |
1129 |
* @param itNoteOnEvent - key, velocity and time stamp of the event |
1130 |
* @returns 0 on success, a value < 0 if no active voice could be picked for voice stealing |
1131 |
*/ |
1132 |
int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) { |
1133 |
if (VoiceSpawnsLeft <= 0) { |
1134 |
dmsg(1,("Max. voice thefts per audio fragment reached (you may raise CONFIG_MAX_VOICES).\n")); |
1135 |
return -1; |
1136 |
} |
1137 |
if (!pEventPool->poolIsEmpty()) { |
1138 |
|
1139 |
RTList<Voice>::Iterator itSelectedVoice; |
1140 |
|
1141 |
// Select one voice for voice stealing |
1142 |
switch (CONFIG_VOICE_STEAL_ALGO) { |
1143 |
|
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 |
// key, or no voice left to kill, then procceed with |
1147 |
// 'oldestkey' algorithm |
1148 |
case voice_steal_algo_oldestvoiceonkey: { |
1149 |
midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key]; |
1150 |
itSelectedVoice = pSelectedKey->pActiveVoices->first(); |
1151 |
// proceed iterating if voice was created in this fragment cycle |
1152 |
while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice; |
1153 |
// if we haven't found a voice then proceed with algorithm 'oldestkey' |
1154 |
if (itSelectedVoice && itSelectedVoice->IsStealable()) break; |
1155 |
} // no break - intentional ! |
1156 |
|
1157 |
// try to pick the oldest voice on the oldest active key |
1158 |
// from the same engine channel |
1159 |
// (caution: must stay after 'oldestvoiceonkey' algorithm !) |
1160 |
case voice_steal_algo_oldestkey: { |
1161 |
// if we already stole in this fragment, try to proceed on same key |
1162 |
if (this->itLastStolenVoice) { |
1163 |
itSelectedVoice = this->itLastStolenVoice; |
1164 |
do { |
1165 |
++itSelectedVoice; |
1166 |
} while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle |
1167 |
// found a "stealable" voice ? |
1168 |
if (itSelectedVoice && itSelectedVoice->IsStealable()) { |
1169 |
// remember which voice we stole, so we can simply proceed on next voice stealing |
1170 |
this->itLastStolenVoice = itSelectedVoice; |
1171 |
break; // selection succeeded |
1172 |
} |
1173 |
} |
1174 |
// 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 |
itSelectedVoice = pSelectedKey->pActiveVoices->first(); |
1179 |
// proceed iterating if voice was created in this fragment cycle |
1180 |
while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice; |
1181 |
// found a "stealable" voice ? |
1182 |
if (itSelectedVoice && itSelectedVoice->IsStealable()) { |
1183 |
// 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 |
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 |
return -1; |
1198 |
} |
1199 |
} |
1200 |
|
1201 |
// 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 |
// (the smaller engine channel number, the higher priority) |
1204 |
if (!itSelectedVoice || !itSelectedVoice->IsStealable()) { |
1205 |
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 |
|
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 |
// get (next) oldest key |
1234 |
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 |
while (iuiSelectedKey) { |
1237 |
midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey]; |
1238 |
itSelectedVoice = pSelectedKey->pActiveVoices->first(); |
1239 |
// proceed iterating if voice was created in this fragment cycle |
1240 |
while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice; |
1241 |
// found a "stealable" voice ? |
1242 |
if (itSelectedVoice && itSelectedVoice->IsStealable()) { |
1243 |
// 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 |
goto stealable_voice_found; // selection succeeded |
1248 |
} |
1249 |
++iuiSelectedKey; // get next key on current engine channel |
1250 |
} |
1251 |
// get next engine channel |
1252 |
iChannelIndex = (iChannelIndex + 1) % engineChannels.size(); |
1253 |
pSelectedChannel = engineChannels[iChannelIndex]; |
1254 |
|
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 |
} |
1264 |
} |
1265 |
|
1266 |
// jump point if a 'stealable' voice was found |
1267 |
stealable_voice_found: |
1268 |
|
1269 |
#if CONFIG_DEVMODE |
1270 |
if (!itSelectedVoice->IsActive()) { |
1271 |
dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n")); |
1272 |
return -1; |
1273 |
} |
1274 |
#endif // CONFIG_DEVMODE |
1275 |
|
1276 |
// now kill the selected voice |
1277 |
itSelectedVoice->Kill(itNoteOnEvent); |
1278 |
|
1279 |
--VoiceSpawnsLeft; |
1280 |
|
1281 |
return 0; // success |
1282 |
} |
1283 |
else { |
1284 |
dmsg(1,("Event pool emtpy!\n")); |
1285 |
return -1; |
1286 |
} |
1287 |
} |
1288 |
|
1289 |
/** |
1290 |
* 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 |
* |
1295 |
* @param pEngineChannel - engine channel on which this event occured on |
1296 |
* @param itVoice - points to the voice to be freed |
1297 |
*/ |
1298 |
void Engine::FreeVoice(EngineChannel* pEngineChannel, Pool<Voice>::Iterator& itVoice) { |
1299 |
if (itVoice) { |
1300 |
midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itVoice->MIDIKey]; |
1301 |
|
1302 |
uint keygroup = itVoice->KeyGroup; |
1303 |
|
1304 |
// 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 |
// free the voice object |
1312 |
pVoicePool->free(itVoice); |
1313 |
|
1314 |
// if no other voices left and member of a key group, remove from key group |
1315 |
if (pKey->pActiveVoices->isEmpty() && keygroup) { |
1316 |
uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[keygroup]; |
1317 |
if (*ppKeyGroup == &*pKey->itSelf) *ppKeyGroup = NULL; // remove key from key group |
1318 |
} |
1319 |
} |
1320 |
else std::cerr << "Couldn't release voice! (!itVoice)\n" << std::flush; |
1321 |
} |
1322 |
|
1323 |
/** |
1324 |
* Called when there's no more voice left on a key, this call will |
1325 |
* update the key info respectively. |
1326 |
* |
1327 |
* @param pEngineChannel - engine channel on which this event occured on |
1328 |
* @param pKey - key which is now inactive |
1329 |
*/ |
1330 |
void Engine::FreeKey(EngineChannel* pEngineChannel, midi_key_info_t* pKey) { |
1331 |
if (pKey->pActiveVoices->isEmpty()) { |
1332 |
pKey->Active = false; |
1333 |
pEngineChannel->pActiveKeys->free(pKey->itSelf); // remove key from list of active keys |
1334 |
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 |
* Reacts on supported control change commands (e.g. pitch bend wheel, |
1344 |
* modulation wheel, aftertouch). |
1345 |
* |
1346 |
* @param pEngineChannel - engine channel on which this event occured on |
1347 |
* @param itControlChangeEvent - controller, value and time stamp of the event |
1348 |
*/ |
1349 |
void Engine::ProcessControlChange(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itControlChangeEvent) { |
1350 |
dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", itControlChangeEvent->Param.CC.Controller, itControlChangeEvent->Param.CC.Value)); |
1351 |
|
1352 |
// update controller value in the engine channel's controller table |
1353 |
pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value; |
1354 |
|
1355 |
// handle hard coded MIDI controllers |
1356 |
switch (itControlChangeEvent->Param.CC.Controller) { |
1357 |
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 |
case 7: { // volume |
1362 |
//TODO: not sample accurate yet |
1363 |
pEngineChannel->MidiVolume = VolumeCurve[itControlChangeEvent->Param.CC.Value]; |
1364 |
pEngineChannel->bStatusChanged = true; // engine channel status has changed, so set notify flag |
1365 |
break; |
1366 |
} |
1367 |
case 10: { // panpot |
1368 |
//TODO: not sample accurate yet |
1369 |
pEngineChannel->GlobalPanLeft = PanCurve[128 - itControlChangeEvent->Param.CC.Value]; |
1370 |
pEngineChannel->GlobalPanRight = PanCurve[itControlChangeEvent->Param.CC.Value]; |
1371 |
break; |
1372 |
} |
1373 |
case 64: { // sustain |
1374 |
if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) { |
1375 |
dmsg(4,("DAMPER (RIGHT) PEDAL DOWN\n")); |
1376 |
pEngineChannel->SustainPedal = true; |
1377 |
|
1378 |
#if !CONFIG_PROCESS_MUTED_CHANNELS |
1379 |
if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted |
1380 |
#endif |
1381 |
|
1382 |
// cancel release process of voices if necessary |
1383 |
RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first(); |
1384 |
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 |
*itNewEvent = *itControlChangeEvent; // copy event to the key's own event list |
1390 |
itNewEvent->Type = Event::type_cancel_release; // transform event type |
1391 |
} |
1392 |
else dmsg(1,("Event pool emtpy!\n")); |
1393 |
} |
1394 |
} |
1395 |
} |
1396 |
if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SustainPedal) { |
1397 |
dmsg(4,("DAMPER (RIGHT) PEDAL UP\n")); |
1398 |
pEngineChannel->SustainPedal = false; |
1399 |
|
1400 |
#if !CONFIG_PROCESS_MUTED_CHANNELS |
1401 |
if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted |
1402 |
#endif |
1403 |
|
1404 |
// release voices if their respective key is not pressed |
1405 |
RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first(); |
1406 |
for (; iuiKey; ++iuiKey) { |
1407 |
midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey]; |
1408 |
if (!pKey->KeyPressed && ShouldReleaseVoice(pEngineChannel, *iuiKey)) { |
1409 |
RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend(); |
1410 |
if (itNewEvent) { |
1411 |
*itNewEvent = *itControlChangeEvent; // copy event to the key's own event list |
1412 |
itNewEvent->Type = Event::type_release; // transform event type |
1413 |
} |
1414 |
else dmsg(1,("Event pool emtpy!\n")); |
1415 |
} |
1416 |
} |
1417 |
} |
1418 |
break; |
1419 |
} |
1420 |
case 65: { // portamento on / off |
1421 |
KillAllVoices(pEngineChannel, itControlChangeEvent); |
1422 |
pEngineChannel->PortamentoMode = itControlChangeEvent->Param.CC.Value >= 64; |
1423 |
break; |
1424 |
} |
1425 |
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 |
|
1430 |
#if !CONFIG_PROCESS_MUTED_CHANNELS |
1431 |
if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted |
1432 |
#endif |
1433 |
|
1434 |
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 |
// Channel Mode Messages |
1468 |
|
1469 |
case 120: { // all sound off |
1470 |
KillAllVoices(pEngineChannel, itControlChangeEvent); |
1471 |
break; |
1472 |
} |
1473 |
case 121: { // reset all controllers |
1474 |
pEngineChannel->ResetControllers(); |
1475 |
break; |
1476 |
} |
1477 |
case 123: { // all notes off |
1478 |
#if CONFIG_PROCESS_ALL_NOTES_OFF |
1479 |
ReleaseAllVoices(pEngineChannel, itControlChangeEvent); |
1480 |
#endif // CONFIG_PROCESS_ALL_NOTES_OFF |
1481 |
break; |
1482 |
} |
1483 |
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 |
} |
1494 |
|
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 |
} |
1504 |
|
1505 |
/** |
1506 |
* Reacts on MIDI system exclusive messages. |
1507 |
* |
1508 |
* @param itSysexEvent - sysex data size and time stamp of the sysex event |
1509 |
*/ |
1510 |
void Engine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) { |
1511 |
RingBuffer<uint8_t,false>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader(); |
1512 |
|
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 |
dmsg(3,("Roland Sysex\n")); |
1521 |
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 |
const RingBuffer<uint8_t,false>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later |
1531 |
if (reader.read(&addr[0], 3) != 3) goto free_sysex_data; |
1532 |
if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters |
1533 |
dmsg(3,("\tSystem Parameter\n")); |
1534 |
} |
1535 |
else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters |
1536 |
dmsg(3,("\tCommon Parameter\n")); |
1537 |
} |
1538 |
else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1) |
1539 |
dmsg(3,("\tPart Parameter\n")); |
1540 |
switch (addr[2]) { |
1541 |
case 0x40: { // scale tuning |
1542 |
dmsg(3,("\t\tScale Tuning\n")); |
1543 |
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 |
if (!reader.pop(&checksum)) goto free_sysex_data; |
1547 |
#if CONFIG_ASSERT_GS_SYSEX_CHECKSUM |
1548 |
if (GSCheckSum(checksum_reader, 12)) goto free_sysex_data; |
1549 |
#endif // CONFIG_ASSERT_GS_SYSEX_CHECKSUM |
1550 |
for (int i = 0; i < 12; i++) scale_tunes[i] -= 64; |
1551 |
AdjustScale((int8_t*) scale_tunes); |
1552 |
dmsg(3,("\t\t\tNew scale applied.\n")); |
1553 |
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 |
pSysexBuffer->increment_read_ptr(itSysexEvent->Param.Sysex.Size); |
1567 |
} |
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 |
uint8_t Engine::GSCheckSum(const RingBuffer<uint8_t,false>::NonVolatileReader AddrReader, uint DataSize) { |
1578 |
RingBuffer<uint8_t,false>::NonVolatileReader reader = AddrReader; |
1579 |
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 |
* 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 |
--VoiceSpawnsLeft; //FIXME: just a temporary workaround, we should check the cause in StealVoice() instead |
1638 |
} |
1639 |
} |
1640 |
} |
1641 |
|
1642 |
/** |
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 |
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 |
String Engine::EngineName() { |
1689 |
return LS_GIG_ENGINE_NAME; |
1690 |
} |
1691 |
|
1692 |
String Engine::Description() { |
1693 |
return "Gigasampler Engine"; |
1694 |
} |
1695 |
|
1696 |
String Engine::Version() { |
1697 |
String s = "$Revision: 1.71 $"; |
1698 |
return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword |
1699 |
} |
1700 |
|
1701 |
InstrumentManager* Engine::GetInstrumentManager() { |
1702 |
return &instruments; |
1703 |
} |
1704 |
|
1705 |
// static constant initializers |
1706 |
const float* Engine::VolumeCurve(InitVolumeCurve()); |
1707 |
const float* Engine::PanCurve(InitPanCurve()); |
1708 |
const float* Engine::CrossfadeCurve(InitCrossfadeCurve()); |
1709 |
|
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 |
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 |
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 |
/** |
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 |
}} // namespace LinuxSampler::gig |