/[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 392 - (hide annotations) (download)
Sat Feb 19 02:40:24 2005 UTC (19 years, 1 month ago) by schoenebeck
File size: 51927 byte(s)
* fixed possibility that memory got not locked
* immediately set instrument status when calling LOAD INSTUMENT NON_MODAL

1 schoenebeck 53 /***************************************************************************
2     * *
3     * LinuxSampler - modular, streaming capable sampler *
4     * *
5 schoenebeck 56 * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck *
6 schoenebeck 53 * *
7     * This program is free software; you can redistribute it and/or modify *
8     * it under the terms of the GNU General Public License as published by *
9     * the Free Software Foundation; either version 2 of the License, or *
10     * (at your option) any later version. *
11     * *
12     * This program is distributed in the hope that it will be useful, *
13     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15     * GNU General Public License for more details. *
16     * *
17     * You should have received a copy of the GNU General Public License *
18     * along with this program; if not, write to the Free Software *
19     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
20     * MA 02111-1307 USA *
21     ***************************************************************************/
22    
23     #include <sstream>
24     #include "DiskThread.h"
25     #include "Voice.h"
26 schoenebeck 285 #include "EGADSR.h"
27 schoenebeck 53
28     #include "Engine.h"
29    
30 schoenebeck 361 #if defined(__APPLE__)
31     # include <stdlib.h>
32     #else
33     # include <malloc.h>
34     #endif
35    
36 schoenebeck 53 namespace LinuxSampler { namespace gig {
37    
38     InstrumentResourceManager Engine::Instruments;
39    
40     Engine::Engine() {
41     pRIFF = NULL;
42     pGig = NULL;
43     pInstrument = NULL;
44     pAudioOutputDevice = NULL;
45     pDiskThread = NULL;
46     pEventGenerator = NULL;
47 schoenebeck 244 pSysexBuffer = new RingBuffer<uint8_t>(SYSEX_BUFFER_SIZE, 0);
48     pEventQueue = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT, 0);
49 schoenebeck 271 pEventPool = new Pool<Event>(MAX_EVENTS_PER_FRAGMENT);
50     pVoicePool = new Pool<Voice>(MAX_AUDIO_VOICES);
51     pActiveKeys = new Pool<uint>(128);
52     pVoiceStealingQueue = new RTList<Event>(pEventPool);
53     pEvents = new RTList<Event>(pEventPool);
54     pCCEvents = new RTList<Event>(pEventPool);
55 schoenebeck 53 for (uint i = 0; i < Event::destination_count; i++) {
56 schoenebeck 271 pSynthesisEvents[i] = new RTList<Event>(pEventPool);
57 schoenebeck 53 }
58     for (uint i = 0; i < 128; i++) {
59 schoenebeck 271 pMIDIKeyInfo[i].pActiveVoices = new RTList<Voice>(pVoicePool);
60 schoenebeck 242 pMIDIKeyInfo[i].KeyPressed = false;
61     pMIDIKeyInfo[i].Active = false;
62     pMIDIKeyInfo[i].ReleaseTrigger = false;
63 schoenebeck 271 pMIDIKeyInfo[i].pEvents = new RTList<Event>(pEventPool);
64 schoenebeck 53 }
65 schoenebeck 271 for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
66     iterVoice->SetEngine(this);
67 schoenebeck 53 }
68     pVoicePool->clear();
69    
70     pSynthesisParameters[0] = NULL; // we allocate when an audio device is connected
71 schoenebeck 80 pBasicFilterParameters = NULL;
72     pMainFilterParameters = NULL;
73 schoenebeck 123
74 senkov 112 InstrumentIdx = -1;
75 capela 133 InstrumentStat = -1;
76 schoenebeck 53
77 schoenebeck 225 AudioDeviceChannelLeft = -1;
78     AudioDeviceChannelRight = -1;
79    
80 schoenebeck 53 ResetInternal();
81     }
82    
83     Engine::~Engine() {
84     if (pDiskThread) {
85 senkov 329 dmsg(1,("Stopping disk thread..."));
86 schoenebeck 53 pDiskThread->StopThread();
87     delete pDiskThread;
88 senkov 329 dmsg(1,("OK\n"));
89 schoenebeck 53 }
90 schoenebeck 351
91     if (pInstrument) Instruments.HandBack(pInstrument, this);
92    
93 schoenebeck 53 if (pGig) delete pGig;
94     if (pRIFF) delete pRIFF;
95     for (uint i = 0; i < 128; i++) {
96     if (pMIDIKeyInfo[i].pActiveVoices) delete pMIDIKeyInfo[i].pActiveVoices;
97     if (pMIDIKeyInfo[i].pEvents) delete pMIDIKeyInfo[i].pEvents;
98     }
99     for (uint i = 0; i < Event::destination_count; i++) {
100     if (pSynthesisEvents[i]) delete pSynthesisEvents[i];
101     }
102     if (pEvents) delete pEvents;
103     if (pCCEvents) delete pCCEvents;
104     if (pEventQueue) delete pEventQueue;
105     if (pEventPool) delete pEventPool;
106 senkov 329 if (pVoicePool) {
107     pVoicePool->clear();
108     delete pVoicePool;
109     }
110 schoenebeck 53 if (pActiveKeys) delete pActiveKeys;
111 schoenebeck 244 if (pSysexBuffer) delete pSysexBuffer;
112 schoenebeck 53 if (pEventGenerator) delete pEventGenerator;
113 schoenebeck 80 if (pMainFilterParameters) delete[] pMainFilterParameters;
114     if (pBasicFilterParameters) delete[] pBasicFilterParameters;
115 schoenebeck 319 if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
116 schoenebeck 250 if (pVoiceStealingQueue) delete pVoiceStealingQueue;
117 schoenebeck 53 }
118    
119     void Engine::Enable() {
120     dmsg(3,("gig::Engine: enabling\n"));
121     EngineDisabled.PushAndUnlock(false, 2); // set condition object 'EngineDisabled' to false (wait max. 2s)
122 schoenebeck 64 dmsg(3,("gig::Engine: enabled (val=%d)\n", EngineDisabled.GetUnsafe()));
123 schoenebeck 53 }
124    
125     void Engine::Disable() {
126     dmsg(3,("gig::Engine: disabling\n"));
127     bool* pWasDisabled = EngineDisabled.PushAndUnlock(true, 2); // wait max. 2s
128     if (!pWasDisabled) dmsg(3,("gig::Engine warning: Timeout waiting to disable engine.\n"));
129     }
130    
131     void Engine::DisableAndLock() {
132     dmsg(3,("gig::Engine: disabling\n"));
133     bool* pWasDisabled = EngineDisabled.Push(true, 2); // wait max. 2s
134     if (!pWasDisabled) dmsg(3,("gig::Engine warning: Timeout waiting to disable engine.\n"));
135     }
136    
137     /**
138     * Reset all voices and disk thread and clear input event queue and all
139     * control and status variables.
140     */
141     void Engine::Reset() {
142     DisableAndLock();
143    
144     //if (pAudioOutputDevice->IsPlaying()) { // if already running
145     /*
146     // signal audio thread not to enter render part anymore
147     SuspensionRequested = true;
148     // sleep until wakened by audio thread
149     pthread_mutex_lock(&__render_state_mutex);
150     pthread_cond_wait(&__render_exit_condition, &__render_state_mutex);
151     pthread_mutex_unlock(&__render_state_mutex);
152     */
153     //}
154    
155     //if (wasplaying) pAudioOutputDevice->Stop();
156    
157     ResetInternal();
158    
159     // signal audio thread to continue with rendering
160     //SuspensionRequested = false;
161     Enable();
162     }
163    
164     /**
165     * Reset all voices and disk thread and clear input event queue and all
166     * control and status variables. This method is not thread safe!
167     */
168     void Engine::ResetInternal() {
169     Pitch = 0;
170     SustainPedal = false;
171     ActiveVoiceCount = 0;
172     ActiveVoiceCountMax = 0;
173 schoenebeck 225 GlobalVolume = 1.0;
174 schoenebeck 354 CurrentKeyDimension = 0;
175 schoenebeck 53
176 schoenebeck 250 // reset voice stealing parameters
177 schoenebeck 271 itLastStolenVoice = RTList<Voice>::Iterator();
178     iuiLastStolenKey = RTList<uint>::Iterator();
179 schoenebeck 250 pVoiceStealingQueue->clear();
180    
181 schoenebeck 244 // reset to normal chromatic scale (means equal temper)
182     memset(&ScaleTuning[0], 0x00, 12);
183    
184 schoenebeck 53 // set all MIDI controller values to zero
185     memset(ControllerTable, 0x00, 128);
186    
187     // reset key info
188     for (uint i = 0; i < 128; i++) {
189     pMIDIKeyInfo[i].pActiveVoices->clear();
190     pMIDIKeyInfo[i].pEvents->clear();
191 schoenebeck 242 pMIDIKeyInfo[i].KeyPressed = false;
192     pMIDIKeyInfo[i].Active = false;
193     pMIDIKeyInfo[i].ReleaseTrigger = false;
194 schoenebeck 271 pMIDIKeyInfo[i].itSelf = Pool<uint>::Iterator();
195 schoenebeck 53 }
196    
197 schoenebeck 239 // reset all key groups
198     map<uint,uint*>::iterator iter = ActiveKeyGroups.begin();
199     for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;
200    
201 schoenebeck 53 // reset all voices
202 schoenebeck 271 for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
203     iterVoice->Reset();
204 schoenebeck 53 }
205     pVoicePool->clear();
206    
207     // free all active keys
208     pActiveKeys->clear();
209    
210     // reset disk thread
211     if (pDiskThread) pDiskThread->Reset();
212    
213     // delete all input events
214     pEventQueue->init();
215     }
216    
217     /**
218 schoenebeck 392 * More or less a workaround to set the instrument name, index and load
219     * status variable to zero percent immediately, that is without blocking
220     * the calling thread. It might be used in future for other preparations
221     * as well though.
222 schoenebeck 53 *
223 schoenebeck 392 * @param FileName - file name of the Gigasampler instrument file
224     * @param Instrument - index of the instrument in the .gig file
225     * @see LoadInstrument()
226 schoenebeck 53 */
227 schoenebeck 392 void Engine::PrepareLoadInstrument(const char* FileName, uint Instrument) {
228     InstrumentFile = FileName;
229     InstrumentIdx = Instrument;
230     InstrumentStat = 0;
231     }
232 schoenebeck 53
233 schoenebeck 392 /**
234     * Load an instrument from a .gig file. PrepareLoadInstrument() has to
235     * be called first to provide the information which instrument to load.
236     * This method will then actually start to load the instrument and block
237     * the calling thread until loading was completed.
238     *
239     * @returns detailed description of the method call result
240     * @see PrepareLoadInstrument()
241     */
242     void Engine::LoadInstrument() {
243    
244 schoenebeck 53 DisableAndLock();
245    
246     ResetInternal(); // reset engine
247    
248     // free old instrument
249     if (pInstrument) {
250     // give old instrument back to instrument manager
251     Instruments.HandBack(pInstrument, this);
252     }
253    
254 schoenebeck 239 // delete all key groups
255     ActiveKeyGroups.clear();
256    
257 schoenebeck 53 // request gig instrument from instrument manager
258     try {
259     instrument_id_t instrid;
260 schoenebeck 392 instrid.FileName = InstrumentFile;
261     instrid.iInstrument = InstrumentIdx;
262 schoenebeck 53 pInstrument = Instruments.Borrow(instrid, this);
263     if (!pInstrument) {
264 capela 133 InstrumentStat = -1;
265 schoenebeck 53 dmsg(1,("no instrument loaded!!!\n"));
266     exit(EXIT_FAILURE);
267     }
268     }
269     catch (RIFF::Exception e) {
270 capela 133 InstrumentStat = -2;
271 schoenebeck 53 String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;
272     throw LinuxSamplerException(msg);
273     }
274     catch (InstrumentResourceManagerException e) {
275 capela 133 InstrumentStat = -3;
276 schoenebeck 53 String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();
277     throw LinuxSamplerException(msg);
278     }
279     catch (...) {
280 capela 133 InstrumentStat = -4;
281 schoenebeck 53 throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");
282     }
283    
284 schoenebeck 239 // rebuild ActiveKeyGroups map with key groups of current instrument
285     for (::gig::Region* pRegion = pInstrument->GetFirstRegion(); pRegion; pRegion = pInstrument->GetNextRegion())
286     if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL;
287    
288 senkov 376 InstrumentIdxName = pInstrument->pInfo->Name;
289 capela 133 InstrumentStat = 100;
290 senkov 112
291 schoenebeck 53 // inform audio driver for the need of two channels
292     try {
293     if (pAudioOutputDevice) pAudioOutputDevice->AcquireChannels(2); // gig Engine only stereo
294     }
295     catch (AudioOutputException e) {
296     String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();
297     throw LinuxSamplerException(msg);
298     }
299    
300     Enable();
301     }
302    
303     /**
304     * Will be called by the InstrumentResourceManager when the instrument
305     * we are currently using in this engine is going to be updated, so we
306     * can stop playback before that happens.
307     */
308     void Engine::ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {
309     dmsg(3,("gig::Engine: Received instrument update message.\n"));
310     DisableAndLock();
311     ResetInternal();
312     this->pInstrument = NULL;
313     }
314    
315     /**
316     * Will be called by the InstrumentResourceManager when the instrument
317     * update process was completed, so we can continue with playback.
318     */
319     void Engine::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {
320 schoenebeck 239 this->pInstrument = pNewResource; //TODO: there are couple of engine parameters we should update here as well if the instrument was updated (see LoadInstrument())
321 schoenebeck 53 Enable();
322     }
323    
324     void Engine::Connect(AudioOutputDevice* pAudioOut) {
325     pAudioOutputDevice = pAudioOut;
326    
327     ResetInternal();
328    
329     // inform audio driver for the need of two channels
330     try {
331     pAudioOutputDevice->AcquireChannels(2); // gig engine only stereo
332     }
333     catch (AudioOutputException e) {
334     String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();
335     throw LinuxSamplerException(msg);
336     }
337    
338 schoenebeck 225 this->AudioDeviceChannelLeft = 0;
339     this->AudioDeviceChannelRight = 1;
340     this->pOutputLeft = pAudioOutputDevice->Channel(0)->Buffer();
341     this->pOutputRight = pAudioOutputDevice->Channel(1)->Buffer();
342     this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle();
343     this->SampleRate = pAudioOutputDevice->SampleRate();
344    
345 schoenebeck 285 // FIXME: audio drivers with varying fragment sizes might be a problem here
346     MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * EG_MIN_RELEASE_TIME) - 1;
347     if (MaxFadeOutPos < 0)
348     throw LinuxSamplerException("EG_MIN_RELEASE_TIME in EGADSR.h to big for current audio fragment size / sampling rate!");
349    
350 schoenebeck 53 // (re)create disk thread
351     if (this->pDiskThread) {
352 senkov 329 dmsg(1,("Stopping disk thread..."));
353 schoenebeck 53 this->pDiskThread->StopThread();
354     delete this->pDiskThread;
355 senkov 329 dmsg(1,("OK\n"));
356 schoenebeck 53 }
357     this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo
358     if (!pDiskThread) {
359     dmsg(0,("gig::Engine new diskthread = NULL\n"));
360     exit(EXIT_FAILURE);
361     }
362    
363 schoenebeck 271 for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
364     iterVoice->pDiskThread = this->pDiskThread;
365 schoenebeck 53 dmsg(3,("d"));
366     }
367     pVoicePool->clear();
368    
369     // (re)create event generator
370     if (pEventGenerator) delete pEventGenerator;
371     pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
372    
373     // (re)allocate synthesis parameter matrix
374 schoenebeck 319 if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
375 schoenebeck 361
376     #if defined(__APPLE__)
377     pSynthesisParameters[0] = (float *) malloc(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle());
378     #else
379 schoenebeck 319 pSynthesisParameters[0] = (float *) memalign(16,(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle()));
380 schoenebeck 361 #endif
381 schoenebeck 53 for (int dst = 1; dst < Event::destination_count; dst++)
382     pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();
383    
384 schoenebeck 80 // (re)allocate biquad filter parameter sequence
385     if (pBasicFilterParameters) delete[] pBasicFilterParameters;
386     if (pMainFilterParameters) delete[] pMainFilterParameters;
387     pBasicFilterParameters = new biquad_param_t[pAudioOut->MaxSamplesPerCycle()];
388     pMainFilterParameters = new biquad_param_t[pAudioOut->MaxSamplesPerCycle()];
389    
390 schoenebeck 53 dmsg(1,("Starting disk thread..."));
391     pDiskThread->StartThread();
392     dmsg(1,("OK\n"));
393    
394 schoenebeck 271 for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
395     if (!iterVoice->pDiskThread) {
396 schoenebeck 53 dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));
397     exit(EXIT_FAILURE);
398     }
399     }
400     }
401    
402     void Engine::DisconnectAudioOutputDevice() {
403     if (pAudioOutputDevice) { // if clause to prevent disconnect loops
404     AudioOutputDevice* olddevice = pAudioOutputDevice;
405     pAudioOutputDevice = NULL;
406     olddevice->Disconnect(this);
407 schoenebeck 225 AudioDeviceChannelLeft = -1;
408     AudioDeviceChannelRight = -1;
409 schoenebeck 53 }
410     }
411    
412     /**
413     * Let this engine proceed to render the given amount of sample points. The
414     * calculated audio data of all voices of this engine will be placed into
415     * the engine's audio sum buffer which has to be copied and eventually be
416     * converted to the appropriate value range by the audio output class (e.g.
417     * AlsaIO or JackIO) right after.
418     *
419     * @param Samples - number of sample points to be rendered
420     * @returns 0 on success
421     */
422     int Engine::RenderAudio(uint Samples) {
423     dmsg(5,("RenderAudio(Samples=%d)\n", Samples));
424    
425     // return if no instrument loaded or engine disabled
426     if (EngineDisabled.Pop()) {
427     dmsg(5,("gig::Engine: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));
428     return 0;
429     }
430     if (!pInstrument) {
431     dmsg(5,("gig::Engine: no instrument loaded\n"));
432     return 0;
433     }
434    
435    
436 schoenebeck 293 // update time of start and end of this audio fragment (as events' time stamps relate to this)
437     pEventGenerator->UpdateFragmentTime(Samples);
438    
439    
440 schoenebeck 53 // empty the event lists for the new fragment
441     pEvents->clear();
442     pCCEvents->clear();
443     for (uint i = 0; i < Event::destination_count; i++) {
444     pSynthesisEvents[i]->clear();
445     }
446 schoenebeck 271 {
447     RTList<uint>::Iterator iuiKey = pActiveKeys->first();
448     RTList<uint>::Iterator end = pActiveKeys->end();
449     for(; iuiKey != end; ++iuiKey) {
450     pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key
451     }
452 schoenebeck 250 }
453 schoenebeck 53
454 schoenebeck 293
455     // get all events from the input event queue which belong to the current fragment
456     {
457     RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
458     Event* pEvent;
459     while (true) {
460     // get next event from input event queue
461     if (!(pEvent = eventQueueReader.pop())) break;
462     // if younger event reached, ignore that and all subsequent ones for now
463     if (pEvent->FragmentPos() >= Samples) {
464     eventQueueReader--;
465     dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
466     pEvent->ResetFragmentPos();
467     break;
468     }
469     // copy event to internal event list
470     if (pEvents->poolIsEmpty()) {
471     dmsg(1,("Event pool emtpy!\n"));
472     break;
473     }
474     *pEvents->allocAppend() = *pEvent;
475     }
476     eventQueueReader.free(); // free all copied events from input queue
477 schoenebeck 53 }
478    
479    
480     // process events
481 schoenebeck 271 {
482     RTList<Event>::Iterator itEvent = pEvents->first();
483     RTList<Event>::Iterator end = pEvents->end();
484     for (; itEvent != end; ++itEvent) {
485     switch (itEvent->Type) {
486     case Event::type_note_on:
487     dmsg(5,("Engine: Note on received\n"));
488     ProcessNoteOn(itEvent);
489     break;
490     case Event::type_note_off:
491     dmsg(5,("Engine: Note off received\n"));
492     ProcessNoteOff(itEvent);
493     break;
494     case Event::type_control_change:
495     dmsg(5,("Engine: MIDI CC received\n"));
496     ProcessControlChange(itEvent);
497     break;
498     case Event::type_pitchbend:
499     dmsg(5,("Engine: Pitchbend received\n"));
500     ProcessPitchbend(itEvent);
501     break;
502     case Event::type_sysex:
503     dmsg(5,("Engine: Sysex received\n"));
504     ProcessSysex(itEvent);
505     break;
506     }
507 schoenebeck 53 }
508     }
509    
510    
511     int active_voices = 0;
512    
513 schoenebeck 271 // render audio from all active voices
514     {
515     RTList<uint>::Iterator iuiKey = pActiveKeys->first();
516     RTList<uint>::Iterator end = pActiveKeys->end();
517     while (iuiKey != end) { // iterate through all active keys
518     midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
519     ++iuiKey;
520 schoenebeck 53
521 schoenebeck 271 RTList<Voice>::Iterator itVoice = pKey->pActiveVoices->first();
522     RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
523     for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
524     // now render current voice
525     itVoice->Render(Samples);
526     if (itVoice->IsActive()) active_voices++; // still active
527     else { // voice reached end, is now inactive
528 schoenebeck 285 FreeVoice(itVoice); // remove voice from the list of active voices
529 schoenebeck 271 }
530 schoenebeck 53 }
531     }
532     }
533    
534    
535 schoenebeck 250 // now render all postponed voices from voice stealing
536 schoenebeck 271 {
537     RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();
538     RTList<Event>::Iterator end = pVoiceStealingQueue->end();
539     for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
540     Pool<Voice>::Iterator itNewVoice = LaunchVoice(itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false);
541     if (itNewVoice) {
542 schoenebeck 285 for (; itNewVoice; itNewVoice = itNewVoice->itChildVoice) {
543     itNewVoice->Render(Samples);
544     if (itNewVoice->IsActive()) active_voices++; // still active
545     else { // voice reached end, is now inactive
546     FreeVoice(itNewVoice); // remove voice from the list of active voices
547     }
548 schoenebeck 271 }
549 schoenebeck 250 }
550 schoenebeck 287 else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));
551 schoenebeck 250 }
552     }
553     // reset voice stealing for the new fragment
554     pVoiceStealingQueue->clear();
555 schoenebeck 271 itLastStolenVoice = RTList<Voice>::Iterator();
556     iuiLastStolenKey = RTList<uint>::Iterator();
557 schoenebeck 250
558    
559 schoenebeck 287 // free all keys which have no active voices left
560     {
561     RTList<uint>::Iterator iuiKey = pActiveKeys->first();
562     RTList<uint>::Iterator end = pActiveKeys->end();
563     while (iuiKey != end) { // iterate through all active keys
564     midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
565     ++iuiKey;
566     if (pKey->pActiveVoices->isEmpty()) FreeKey(pKey);
567     #if DEVMODE
568     else { // FIXME: should be removed before the final release (purpose: just a sanity check for debugging)
569     RTList<Voice>::Iterator itVoice = pKey->pActiveVoices->first();
570     RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
571     for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
572     if (itVoice->itKillEvent) {
573     dmsg(1,("gig::Engine: ERROR, killed voice survived !!!\n"));
574     }
575     }
576     }
577     #endif // DEVMODE
578     }
579     }
580    
581    
582 schoenebeck 53 // write that to the disk thread class so that it can print it
583     // on the console for debugging purposes
584     ActiveVoiceCount = active_voices;
585     if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;
586    
587    
588     return 0;
589     }
590    
591     /**
592     * Will be called by the MIDIIn Thread to let the audio thread trigger a new
593     * voice for the given key.
594     *
595     * @param Key - MIDI key number of the triggered key
596     * @param Velocity - MIDI velocity value of the triggered key
597     */
598     void Engine::SendNoteOn(uint8_t Key, uint8_t Velocity) {
599 schoenebeck 246 Event event = pEventGenerator->CreateEvent();
600     event.Type = Event::type_note_on;
601     event.Param.Note.Key = Key;
602     event.Param.Note.Velocity = Velocity;
603 schoenebeck 53 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
604     else dmsg(1,("Engine: Input event queue full!"));
605     }
606    
607     /**
608     * Will be called by the MIDIIn Thread to signal the audio thread to release
609     * voice(s) on the given key.
610     *
611     * @param Key - MIDI key number of the released key
612     * @param Velocity - MIDI release velocity value of the released key
613     */
614     void Engine::SendNoteOff(uint8_t Key, uint8_t Velocity) {
615 schoenebeck 246 Event event = pEventGenerator->CreateEvent();
616     event.Type = Event::type_note_off;
617     event.Param.Note.Key = Key;
618     event.Param.Note.Velocity = Velocity;
619 schoenebeck 53 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
620     else dmsg(1,("Engine: Input event queue full!"));
621     }
622    
623     /**
624     * Will be called by the MIDIIn Thread to signal the audio thread to change
625     * the pitch value for all voices.
626     *
627     * @param Pitch - MIDI pitch value (-8192 ... +8191)
628     */
629     void Engine::SendPitchbend(int Pitch) {
630 schoenebeck 246 Event event = pEventGenerator->CreateEvent();
631     event.Type = Event::type_pitchbend;
632     event.Param.Pitch.Pitch = Pitch;
633 schoenebeck 53 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
634     else dmsg(1,("Engine: Input event queue full!"));
635     }
636    
637     /**
638     * Will be called by the MIDIIn Thread to signal the audio thread that a
639     * continuous controller value has changed.
640     *
641     * @param Controller - MIDI controller number of the occured control change
642     * @param Value - value of the control change
643     */
644     void Engine::SendControlChange(uint8_t Controller, uint8_t Value) {
645 schoenebeck 246 Event event = pEventGenerator->CreateEvent();
646     event.Type = Event::type_control_change;
647     event.Param.CC.Controller = Controller;
648     event.Param.CC.Value = Value;
649 schoenebeck 53 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
650     else dmsg(1,("Engine: Input event queue full!"));
651     }
652    
653     /**
654 schoenebeck 244 * Will be called by the MIDI input device whenever a MIDI system
655     * exclusive message has arrived.
656     *
657     * @param pData - pointer to sysex data
658     * @param Size - lenght of sysex data (in bytes)
659     */
660     void Engine::SendSysex(void* pData, uint Size) {
661 schoenebeck 246 Event event = pEventGenerator->CreateEvent();
662     event.Type = Event::type_sysex;
663     event.Param.Sysex.Size = Size;
664 schoenebeck 244 if (pEventQueue->write_space() > 0) {
665     if (pSysexBuffer->write_space() >= Size) {
666     // copy sysex data to input buffer
667     uint toWrite = Size;
668     uint8_t* pPos = (uint8_t*) pData;
669     while (toWrite) {
670     const uint writeNow = RTMath::Min(toWrite, pSysexBuffer->write_space_to_end());
671     pSysexBuffer->write(pPos, writeNow);
672     toWrite -= writeNow;
673     pPos += writeNow;
674    
675     }
676     // finally place sysex event into input event queue
677     pEventQueue->push(&event);
678     }
679     else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,SYSEX_BUFFER_SIZE));
680     }
681     else dmsg(1,("Engine: Input event queue full!"));
682     }
683    
684     /**
685 schoenebeck 53 * Assigns and triggers a new voice for the respective MIDI key.
686     *
687 schoenebeck 271 * @param itNoteOnEvent - key, velocity and time stamp of the event
688 schoenebeck 53 */
689 schoenebeck 271 void Engine::ProcessNoteOn(Pool<Event>::Iterator& itNoteOnEvent) {
690 schoenebeck 53
691 schoenebeck 354 const int key = itNoteOnEvent->Param.Note.Key;
692    
693     // Change key dimension value if key is in keyswitching area
694     if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high)
695     CurrentKeyDimension = ((key - pInstrument->DimensionKeyRange.low) * 128) /
696     (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);
697    
698     midi_key_info_t* pKey = &pMIDIKeyInfo[key];
699    
700 schoenebeck 53 pKey->KeyPressed = true; // the MIDI key was now pressed down
701    
702     // cancel release process of voices on this key if needed
703     if (pKey->Active && !SustainPedal) {
704 schoenebeck 271 RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
705     if (itCancelReleaseEvent) {
706     *itCancelReleaseEvent = *itNoteOnEvent; // copy event
707     itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type
708 schoenebeck 239 }
709     else dmsg(1,("Event pool emtpy!\n"));
710 schoenebeck 53 }
711    
712 schoenebeck 271 // move note on event to the key's own event list
713     RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
714    
715 schoenebeck 233 // allocate and trigger a new voice for the key
716 schoenebeck 287 LaunchVoice(itNoteOnEventOnKeyList, 0, false, true);
717 schoenebeck 53 }
718    
719     /**
720     * Releases the voices on the given key if sustain pedal is not pressed.
721     * If sustain is pressed, the release of the note will be postponed until
722     * sustain pedal will be released or voice turned inactive by itself (e.g.
723     * due to completion of sample playback).
724     *
725 schoenebeck 271 * @param itNoteOffEvent - key, velocity and time stamp of the event
726 schoenebeck 53 */
727 schoenebeck 271 void Engine::ProcessNoteOff(Pool<Event>::Iterator& itNoteOffEvent) {
728     midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];
729 schoenebeck 53
730     pKey->KeyPressed = false; // the MIDI key was now released
731    
732     // release voices on this key if needed
733     if (pKey->Active && !SustainPedal) {
734 schoenebeck 271 itNoteOffEvent->Type = Event::type_release; // transform event type
735 schoenebeck 53 }
736 schoenebeck 242
737 schoenebeck 271 // move event to the key's own event list
738     RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
739    
740 schoenebeck 242 // spawn release triggered voice(s) if needed
741     if (pKey->ReleaseTrigger) {
742 schoenebeck 287 LaunchVoice(itNoteOffEventOnKeyList, 0, true, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
743 schoenebeck 242 pKey->ReleaseTrigger = false;
744     }
745 schoenebeck 53 }
746    
747     /**
748     * Moves pitchbend event from the general (input) event list to the pitch
749     * event list.
750     *
751 schoenebeck 271 * @param itPitchbendEvent - absolute pitch value and time stamp of the event
752 schoenebeck 53 */
753 schoenebeck 271 void Engine::ProcessPitchbend(Pool<Event>::Iterator& itPitchbendEvent) {
754     this->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value
755     itPitchbendEvent.moveToEndOf(pSynthesisEvents[Event::destination_vco]);
756 schoenebeck 53 }
757    
758     /**
759 schoenebeck 233 * Allocates and triggers a new voice. This method will usually be
760     * called by the ProcessNoteOn() method and by the voices itself
761     * (e.g. to spawn further voices on the same key for layered sounds).
762     *
763 schoenebeck 271 * @param itNoteOnEvent - key, velocity and time stamp of the event
764 schoenebeck 242 * @param iLayer - layer index for the new voice (optional - only
765     * in case of layered sounds of course)
766     * @param ReleaseTriggerVoice - if new voice is a release triggered voice
767     * (optional, default = false)
768 schoenebeck 250 * @param VoiceStealing - if voice stealing should be performed
769     * when there is no free voice
770     * (optional, default = true)
771     * @returns pointer to new voice or NULL if there was no free voice or
772 schoenebeck 354 * if the voice wasn't triggered (for example when no region is
773     * defined for the given key).
774 schoenebeck 233 */
775 schoenebeck 271 Pool<Voice>::Iterator Engine::LaunchVoice(Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing) {
776     midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
777 schoenebeck 233
778     // allocate a new voice for the key
779 schoenebeck 271 Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
780     if (itNewVoice) {
781 schoenebeck 233 // launch the new voice
782 schoenebeck 287 if (itNewVoice->Trigger(itNoteOnEvent, this->Pitch, this->pInstrument, iLayer, ReleaseTriggerVoice, VoiceStealing) < 0) {
783 schoenebeck 354 dmsg(4,("Voice not triggered\n"));
784 schoenebeck 271 pKey->pActiveVoices->free(itNewVoice);
785 schoenebeck 233 }
786 schoenebeck 239 else { // on success
787     uint** ppKeyGroup = NULL;
788 schoenebeck 271 if (itNewVoice->KeyGroup) { // if this voice / key belongs to a key group
789     ppKeyGroup = &ActiveKeyGroups[itNewVoice->KeyGroup];
790 schoenebeck 239 if (*ppKeyGroup) { // if there's already an active key in that key group
791     midi_key_info_t* pOtherKey = &pMIDIKeyInfo[**ppKeyGroup];
792     // kill all voices on the (other) key
793 schoenebeck 271 RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
794     RTList<Voice>::Iterator end = pOtherKey->pActiveVoices->end();
795     for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
796     if (itVoiceToBeKilled->Type != Voice::type_release_trigger) itVoiceToBeKilled->Kill(itNoteOnEvent);
797 schoenebeck 242 }
798 schoenebeck 239 }
799     }
800     if (!pKey->Active) { // mark as active key
801     pKey->Active = true;
802 schoenebeck 271 pKey->itSelf = pActiveKeys->allocAppend();
803     *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
804 schoenebeck 239 }
805 schoenebeck 271 if (itNewVoice->KeyGroup) {
806     *ppKeyGroup = &*pKey->itSelf; // put key as the (new) active key to its key group
807 schoenebeck 239 }
808 schoenebeck 271 if (itNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)
809     return itNewVoice; // success
810 schoenebeck 233 }
811     }
812 schoenebeck 285 else if (VoiceStealing) {
813     // first, get total amount of required voices (dependant on amount of layers)
814     ::gig::Region* pRegion = pInstrument->GetRegion(itNoteOnEvent->Param.Note.Key);
815     if (!pRegion) return Pool<Voice>::Iterator(); // nothing defined for this MIDI key, so no voice needed
816     int voicesRequired = pRegion->Layers;
817 schoenebeck 250
818 schoenebeck 285 // now steal the (remaining) amount of voices
819     for (int i = iLayer; i < voicesRequired; i++)
820     StealVoice(itNoteOnEvent);
821    
822     // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died
823     RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();
824     if (itStealEvent) {
825     *itStealEvent = *itNoteOnEvent; // copy event
826     itStealEvent->Param.Note.Layer = iLayer;
827     itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;
828     }
829     else dmsg(1,("Voice stealing queue full!\n"));
830     }
831    
832 schoenebeck 271 return Pool<Voice>::Iterator(); // no free voice or error
833 schoenebeck 233 }
834    
835     /**
836 schoenebeck 250 * Will be called by LaunchVoice() method in case there are no free
837     * voices left. This method will select and kill one old voice for
838     * voice stealing and postpone the note-on event until the selected
839     * voice actually died.
840     *
841 schoenebeck 285 * @param itNoteOnEvent - key, velocity and time stamp of the event
842 schoenebeck 250 */
843 schoenebeck 285 void Engine::StealVoice(Pool<Event>::Iterator& itNoteOnEvent) {
844 schoenebeck 271 if (!pEventPool->poolIsEmpty()) {
845 schoenebeck 250
846 schoenebeck 271 RTList<uint>::Iterator iuiOldestKey;
847     RTList<Voice>::Iterator itOldestVoice;
848 schoenebeck 250
849     // Select one voice for voice stealing
850     switch (VOICE_STEAL_ALGORITHM) {
851    
852     // try to pick the oldest voice on the key where the new
853     // voice should be spawned, if there is no voice on that
854     // key, or no voice left to kill there, then procceed with
855     // 'oldestkey' algorithm
856     case voice_steal_algo_keymask: {
857 schoenebeck 271 midi_key_info_t* pOldestKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
858     if (itLastStolenVoice) {
859     itOldestVoice = itLastStolenVoice;
860     ++itOldestVoice;
861 schoenebeck 250 }
862     else { // no voice stolen in this audio fragment cycle yet
863 schoenebeck 271 itOldestVoice = pOldestKey->pActiveVoices->first();
864 schoenebeck 250 }
865 schoenebeck 271 if (itOldestVoice) {
866     iuiOldestKey = pOldestKey->itSelf;
867 schoenebeck 250 break; // selection succeeded
868     }
869     } // no break - intentional !
870    
871     // try to pick the oldest voice on the oldest active key
872     // (caution: must stay after 'keymask' algorithm !)
873     case voice_steal_algo_oldestkey: {
874 schoenebeck 271 if (itLastStolenVoice) {
875     midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiLastStolenKey];
876     itOldestVoice = itLastStolenVoice;
877     ++itOldestVoice;
878     if (!itOldestVoice) {
879     iuiOldestKey = iuiLastStolenKey;
880     ++iuiOldestKey;
881     if (iuiOldestKey) {
882     midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiOldestKey];
883     itOldestVoice = pOldestKey->pActiveVoices->first();
884 schoenebeck 250 }
885 schoenebeck 285 else {
886     dmsg(1,("gig::Engine: Warning, too less voices, even for voice stealing! - Better recompile with higher MAX_AUDIO_VOICES.\n"));
887 schoenebeck 250 return;
888     }
889     }
890 schoenebeck 271 else iuiOldestKey = iuiLastStolenKey;
891 schoenebeck 250 }
892     else { // no voice stolen in this audio fragment cycle yet
893 schoenebeck 271 iuiOldestKey = pActiveKeys->first();
894     midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiOldestKey];
895     itOldestVoice = pOldestKey->pActiveVoices->first();
896 schoenebeck 250 }
897     break;
898     }
899    
900     // don't steal anything
901     case voice_steal_algo_none:
902     default: {
903     dmsg(1,("No free voice (voice stealing disabled)!\n"));
904     return;
905     }
906     }
907    
908 schoenebeck 287 //FIXME: can be removed, just a sanity check for debugging
909     if (!itOldestVoice->IsActive()) dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
910    
911 schoenebeck 250 // now kill the selected voice
912 schoenebeck 271 itOldestVoice->Kill(itNoteOnEvent);
913 schoenebeck 250 // remember which voice on which key we stole, so we can simply proceed for the next voice stealing
914 schoenebeck 271 this->itLastStolenVoice = itOldestVoice;
915     this->iuiLastStolenKey = iuiOldestKey;
916 schoenebeck 250 }
917     else dmsg(1,("Event pool emtpy!\n"));
918     }
919    
920     /**
921 schoenebeck 285 * Removes the given voice from the MIDI key's list of active voices.
922     * This method will be called when a voice went inactive, e.g. because
923     * it finished to playback its sample, finished its release stage or
924     * just was killed.
925 schoenebeck 53 *
926 schoenebeck 285 * @param itVoice - points to the voice to be freed
927 schoenebeck 53 */
928 schoenebeck 285 void Engine::FreeVoice(Pool<Voice>::Iterator& itVoice) {
929 schoenebeck 271 if (itVoice) {
930     midi_key_info_t* pKey = &pMIDIKeyInfo[itVoice->MIDIKey];
931 schoenebeck 53
932 schoenebeck 271 uint keygroup = itVoice->KeyGroup;
933    
934 schoenebeck 53 // free the voice object
935 schoenebeck 271 pVoicePool->free(itVoice);
936 schoenebeck 53
937 schoenebeck 287 // if no other voices left and member of a key group, remove from key group
938     if (pKey->pActiveVoices->isEmpty() && keygroup) {
939     uint** ppKeyGroup = &ActiveKeyGroups[keygroup];
940     if (*ppKeyGroup == &*pKey->itSelf) *ppKeyGroup = NULL; // remove key from key group
941 schoenebeck 53 }
942     }
943 schoenebeck 285 else std::cerr << "Couldn't release voice! (!itVoice)\n" << std::flush;
944 schoenebeck 53 }
945    
946     /**
947 schoenebeck 287 * Called when there's no more voice left on a key, this call will
948     * update the key info respectively.
949     *
950     * @param pKey - key which is now inactive
951     */
952     void Engine::FreeKey(midi_key_info_t* pKey) {
953     if (pKey->pActiveVoices->isEmpty()) {
954     pKey->Active = false;
955     pActiveKeys->free(pKey->itSelf); // remove key from list of active keys
956     pKey->itSelf = RTList<uint>::Iterator();
957     pKey->ReleaseTrigger = false;
958     pKey->pEvents->clear();
959     dmsg(3,("Key has no more voices now\n"));
960     }
961     else dmsg(1,("gig::Engine: Oops, tried to free a key which contains voices.\n"));
962     }
963    
964     /**
965 schoenebeck 53 * Reacts on supported control change commands (e.g. pitch bend wheel,
966     * modulation wheel, aftertouch).
967     *
968 schoenebeck 271 * @param itControlChangeEvent - controller, value and time stamp of the event
969 schoenebeck 53 */
970 schoenebeck 271 void Engine::ProcessControlChange(Pool<Event>::Iterator& itControlChangeEvent) {
971     dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", itControlChangeEvent->Param.CC.Controller, itControlChangeEvent->Param.CC.Value));
972 schoenebeck 53
973 schoenebeck 271 switch (itControlChangeEvent->Param.CC.Controller) {
974 schoenebeck 53 case 64: {
975 schoenebeck 271 if (itControlChangeEvent->Param.CC.Value >= 64 && !SustainPedal) {
976 schoenebeck 53 dmsg(4,("PEDAL DOWN\n"));
977     SustainPedal = true;
978    
979     // cancel release process of voices if necessary
980 schoenebeck 271 RTList<uint>::Iterator iuiKey = pActiveKeys->first();
981     if (iuiKey) {
982     itControlChangeEvent->Type = Event::type_cancel_release; // transform event type
983     while (iuiKey) {
984     midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
985     ++iuiKey;
986 schoenebeck 53 if (!pKey->KeyPressed) {
987 schoenebeck 271 RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
988     if (itNewEvent) *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
989 schoenebeck 53 else dmsg(1,("Event pool emtpy!\n"));
990     }
991     }
992     }
993     }
994 schoenebeck 271 if (itControlChangeEvent->Param.CC.Value < 64 && SustainPedal) {
995 schoenebeck 53 dmsg(4,("PEDAL UP\n"));
996     SustainPedal = false;
997    
998     // release voices if their respective key is not pressed
999 schoenebeck 271 RTList<uint>::Iterator iuiKey = pActiveKeys->first();
1000     if (iuiKey) {
1001     itControlChangeEvent->Type = Event::type_release; // transform event type
1002     while (iuiKey) {
1003     midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
1004     ++iuiKey;
1005 schoenebeck 53 if (!pKey->KeyPressed) {
1006 schoenebeck 271 RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1007     if (itNewEvent) *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1008 schoenebeck 53 else dmsg(1,("Event pool emtpy!\n"));
1009     }
1010     }
1011     }
1012     }
1013     break;
1014     }
1015     }
1016    
1017     // update controller value in the engine's controller table
1018 schoenebeck 271 ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
1019 schoenebeck 53
1020     // move event from the unsorted event list to the control change event list
1021 schoenebeck 271 itControlChangeEvent.moveToEndOf(pCCEvents);
1022 schoenebeck 53 }
1023    
1024     /**
1025 schoenebeck 244 * Reacts on MIDI system exclusive messages.
1026     *
1027 schoenebeck 271 * @param itSysexEvent - sysex data size and time stamp of the sysex event
1028 schoenebeck 244 */
1029 schoenebeck 271 void Engine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) {
1030 schoenebeck 244 RingBuffer<uint8_t>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();
1031    
1032     uint8_t exclusive_status, id;
1033     if (!reader.pop(&exclusive_status)) goto free_sysex_data;
1034     if (!reader.pop(&id)) goto free_sysex_data;
1035     if (exclusive_status != 0xF0) goto free_sysex_data;
1036    
1037     switch (id) {
1038     case 0x41: { // Roland
1039     uint8_t device_id, model_id, cmd_id;
1040     if (!reader.pop(&device_id)) goto free_sysex_data;
1041     if (!reader.pop(&model_id)) goto free_sysex_data;
1042     if (!reader.pop(&cmd_id)) goto free_sysex_data;
1043     if (model_id != 0x42 /*GS*/) goto free_sysex_data;
1044     if (cmd_id != 0x12 /*DT1*/) goto free_sysex_data;
1045    
1046     // command address
1047     uint8_t addr[3]; // 2 byte addr MSB, followed by 1 byte addr LSB)
1048     const RingBuffer<uint8_t>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later
1049     if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;
1050     if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters
1051     }
1052     else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters
1053     }
1054     else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)
1055     switch (addr[3]) {
1056     case 0x40: { // scale tuning
1057     uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave
1058     if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;
1059     uint8_t checksum;
1060     if (!reader.pop(&checksum)) goto free_sysex_data;
1061     if (GSCheckSum(checksum_reader, 12) != checksum) goto free_sysex_data;
1062     for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;
1063     AdjustScale((int8_t*) scale_tunes);
1064     break;
1065     }
1066     }
1067     }
1068     else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x20) { // Part Parameters (2)
1069     }
1070     else if (addr[0] == 0x41) { // Drum Setup Parameters
1071     }
1072     break;
1073     }
1074     }
1075    
1076     free_sysex_data: // finally free sysex data
1077 schoenebeck 271 pSysexBuffer->increment_read_ptr(itSysexEvent->Param.Sysex.Size);
1078 schoenebeck 244 }
1079    
1080     /**
1081     * Calculates the Roland GS sysex check sum.
1082     *
1083     * @param AddrReader - reader which currently points to the first GS
1084     * command address byte of the GS sysex message in
1085     * question
1086     * @param DataSize - size of the GS message data (in bytes)
1087     */
1088     uint8_t Engine::GSCheckSum(const RingBuffer<uint8_t>::NonVolatileReader AddrReader, uint DataSize) {
1089     RingBuffer<uint8_t>::NonVolatileReader reader = AddrReader;
1090     uint bytes = 3 /*addr*/ + DataSize;
1091     uint8_t addr_and_data[bytes];
1092     reader.read(&addr_and_data[0], bytes);
1093     uint8_t sum = 0;
1094     for (uint i = 0; i < bytes; i++) sum += addr_and_data[i];
1095     return 128 - sum % 128;
1096     }
1097    
1098     /**
1099     * Allows to tune each of the twelve semitones of an octave.
1100     *
1101     * @param ScaleTunes - detuning of all twelve semitones (in cents)
1102     */
1103     void Engine::AdjustScale(int8_t ScaleTunes[12]) {
1104     memcpy(&this->ScaleTuning[0], &ScaleTunes[0], 12); //TODO: currently not sample accurate
1105     }
1106    
1107     /**
1108 schoenebeck 53 * Initialize the parameter sequence for the modulation destination given by
1109     * by 'dst' with the constant value given by val.
1110     */
1111     void Engine::ResetSynthesisParameters(Event::destination_t dst, float val) {
1112     int maxsamples = pAudioOutputDevice->MaxSamplesPerCycle();
1113 schoenebeck 80 float* m = &pSynthesisParameters[dst][0];
1114     for (int i = 0; i < maxsamples; i += 4) {
1115     m[i] = val;
1116     m[i+1] = val;
1117     m[i+2] = val;
1118     m[i+3] = val;
1119     }
1120 schoenebeck 53 }
1121    
1122     float Engine::Volume() {
1123     return GlobalVolume;
1124     }
1125    
1126     void Engine::Volume(float f) {
1127     GlobalVolume = f;
1128     }
1129    
1130 schoenebeck 225 uint Engine::Channels() {
1131     return 2;
1132     }
1133    
1134     void Engine::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) {
1135     AudioChannel* pChannel = pAudioOutputDevice->Channel(AudioDeviceChannel);
1136     if (!pChannel) throw AudioOutputException("Invalid audio output device channel " + ToString(AudioDeviceChannel));
1137     switch (EngineAudioChannel) {
1138     case 0: // left output channel
1139     pOutputLeft = pChannel->Buffer();
1140     AudioDeviceChannelLeft = AudioDeviceChannel;
1141     break;
1142     case 1: // right output channel
1143     pOutputRight = pChannel->Buffer();
1144     AudioDeviceChannelRight = AudioDeviceChannel;
1145     break;
1146     default:
1147     throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));
1148     }
1149     }
1150    
1151     int Engine::OutputChannel(uint EngineAudioChannel) {
1152     switch (EngineAudioChannel) {
1153     case 0: // left channel
1154     return AudioDeviceChannelLeft;
1155     case 1: // right channel
1156     return AudioDeviceChannelRight;
1157     default:
1158     throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));
1159     }
1160     }
1161    
1162 schoenebeck 53 uint Engine::VoiceCount() {
1163     return ActiveVoiceCount;
1164     }
1165    
1166     uint Engine::VoiceCountMax() {
1167     return ActiveVoiceCountMax;
1168     }
1169    
1170     bool Engine::DiskStreamSupported() {
1171     return true;
1172     }
1173    
1174     uint Engine::DiskStreamCount() {
1175     return (pDiskThread) ? pDiskThread->ActiveStreamCount : 0;
1176     }
1177    
1178     uint Engine::DiskStreamCountMax() {
1179     return (pDiskThread) ? pDiskThread->ActiveStreamCountMax : 0;
1180     }
1181    
1182     String Engine::DiskStreamBufferFillBytes() {
1183     return pDiskThread->GetBufferFillBytes();
1184     }
1185    
1186     String Engine::DiskStreamBufferFillPercentage() {
1187     return pDiskThread->GetBufferFillPercentage();
1188     }
1189    
1190 senkov 112 String Engine::EngineName() {
1191     return "GigEngine";
1192     }
1193    
1194     String Engine::InstrumentFileName() {
1195     return InstrumentFile;
1196     }
1197    
1198 senkov 376 String Engine::InstrumentName() {
1199     return InstrumentIdxName;
1200     }
1201    
1202 senkov 112 int Engine::InstrumentIndex() {
1203     return InstrumentIdx;
1204     }
1205    
1206 capela 133 int Engine::InstrumentStatus() {
1207     return InstrumentStat;
1208     }
1209    
1210 schoenebeck 53 String Engine::Description() {
1211     return "Gigasampler Engine";
1212     }
1213    
1214     String Engine::Version() {
1215 schoenebeck 392 String s = "$Revision: 1.25 $";
1216 schoenebeck 123 return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword
1217 schoenebeck 53 }
1218    
1219     }} // namespace LinuxSampler::gig

  ViewVC Help
Powered by ViewVC