/[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 329 - (hide annotations) (download)
Tue Dec 28 09:43:04 2004 UTC (19 years, 3 months ago) by senkov
File size: 50429 byte(s)
* Fixes for engine reloading. Fixed streaming bugs in some
 cases only, most probably not all yet.

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

  ViewVC Help
Powered by ViewVC