/[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 293 - (hide annotations) (download)
Mon Oct 25 15:14:27 2004 UTC (19 years, 5 months ago) by schoenebeck
File size: 50240 byte(s)
* gig::Engine: changed way how events make it from the input event queue
  into the engine's process chain (fixes forced segfault in EGADSR)
* Event.h: using signed type for fragment position for easier
  differentiation if event might happened before or after current fragment

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

  ViewVC Help
Powered by ViewVC