/[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 354 - (hide annotations) (download)
Sat Jan 29 15:17:59 2005 UTC (19 years, 2 months ago) by schoenebeck
File size: 50954 byte(s)
* support for keyswitching
* ignore if no sample was defined for region(s) or dimension region(s)
(patch by Andreas Persson)

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

  ViewVC Help
Powered by ViewVC