/[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 351 - (hide annotations) (download)
Tue Jan 25 22:11:43 2005 UTC (19 years, 2 months ago) by schoenebeck
File size: 50497 byte(s)
* fixed some memory leaks (patch by Gene Anders)

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

  ViewVC Help
Powered by ViewVC