/[svn]/linuxsampler/trunk/src/engines/gig/Engine.cpp
ViewVC logotype

Diff of /linuxsampler/trunk/src/engines/gig/Engine.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 80 by schoenebeck, Sun May 23 19:16:33 2004 UTC revision 329 by senkov, Tue Dec 28 09:43:04 2004 UTC
# Line 23  Line 23 
23  #include <sstream>  #include <sstream>
24  #include "DiskThread.h"  #include "DiskThread.h"
25  #include "Voice.h"  #include "Voice.h"
26    #include "EGADSR.h"
27    
28  #include "Engine.h"  #include "Engine.h"
29    #include <malloc.h>
30    
31  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
32    
# Line 37  namespace LinuxSampler { namespace gig { Line 39  namespace LinuxSampler { namespace gig {
39          pAudioOutputDevice = NULL;          pAudioOutputDevice = NULL;
40          pDiskThread        = NULL;          pDiskThread        = NULL;
41          pEventGenerator    = NULL;          pEventGenerator    = NULL;
42          pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT);          pSysexBuffer       = new RingBuffer<uint8_t>(SYSEX_BUFFER_SIZE, 0);
43          pEventPool         = new RTELMemoryPool<Event>(MAX_EVENTS_PER_FRAGMENT);          pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT, 0);
44          pVoicePool         = new RTELMemoryPool<Voice>(MAX_AUDIO_VOICES);          pEventPool         = new Pool<Event>(MAX_EVENTS_PER_FRAGMENT);
45          pActiveKeys        = new RTELMemoryPool<uint>(128);          pVoicePool         = new Pool<Voice>(MAX_AUDIO_VOICES);
46          pEvents            = new RTEList<Event>(pEventPool);          pActiveKeys        = new Pool<uint>(128);
47          pCCEvents          = new RTEList<Event>(pEventPool);          pVoiceStealingQueue = new RTList<Event>(pEventPool);
48            pEvents            = new RTList<Event>(pEventPool);
49            pCCEvents          = new RTList<Event>(pEventPool);
50          for (uint i = 0; i < Event::destination_count; i++) {          for (uint i = 0; i < Event::destination_count; i++) {
51              pSynthesisEvents[i] = new RTEList<Event>(pEventPool);              pSynthesisEvents[i] = new RTList<Event>(pEventPool);
52          }          }
53          for (uint i = 0; i < 128; i++) {          for (uint i = 0; i < 128; i++) {
54              pMIDIKeyInfo[i].pActiveVoices = new RTEList<Voice>(pVoicePool);              pMIDIKeyInfo[i].pActiveVoices  = new RTList<Voice>(pVoicePool);
55              pMIDIKeyInfo[i].KeyPressed    = false;              pMIDIKeyInfo[i].KeyPressed     = false;
56              pMIDIKeyInfo[i].Active        = false;              pMIDIKeyInfo[i].Active         = false;
57              pMIDIKeyInfo[i].pSelf         = NULL;              pMIDIKeyInfo[i].ReleaseTrigger = false;
58              pMIDIKeyInfo[i].pEvents       = new RTEList<Event>(pEventPool);              pMIDIKeyInfo[i].pEvents        = new RTList<Event>(pEventPool);
59          }          }
60          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
61              pVoice->SetEngine(this);              iterVoice->SetEngine(this);
62          }          }
63          pVoicePool->clear();          pVoicePool->clear();
64    
# Line 62  namespace LinuxSampler { namespace gig { Line 66  namespace LinuxSampler { namespace gig {
66          pBasicFilterParameters  = NULL;          pBasicFilterParameters  = NULL;
67          pMainFilterParameters   = NULL;          pMainFilterParameters   = NULL;
68    
69            InstrumentIdx = -1;
70            InstrumentStat = -1;
71    
72            AudioDeviceChannelLeft  = -1;
73            AudioDeviceChannelRight = -1;
74    
75          ResetInternal();          ResetInternal();
76      }      }
77    
78      Engine::~Engine() {      Engine::~Engine() {
79          if (pDiskThread) {          if (pDiskThread) {
80                dmsg(1,("Stopping disk thread..."));
81              pDiskThread->StopThread();              pDiskThread->StopThread();
82              delete pDiskThread;              delete pDiskThread;
83                dmsg(1,("OK\n"));
84          }          }
85          if (pGig)  delete pGig;          if (pGig)  delete pGig;
86          if (pRIFF) delete pRIFF;          if (pRIFF) delete pRIFF;
# Line 79  namespace LinuxSampler { namespace gig { Line 91  namespace LinuxSampler { namespace gig {
91          for (uint i = 0; i < Event::destination_count; i++) {          for (uint i = 0; i < Event::destination_count; i++) {
92              if (pSynthesisEvents[i]) delete pSynthesisEvents[i];              if (pSynthesisEvents[i]) delete pSynthesisEvents[i];
93          }          }
         delete[] pSynthesisEvents;  
94          if (pEvents)     delete pEvents;          if (pEvents)     delete pEvents;
95          if (pCCEvents)   delete pCCEvents;          if (pCCEvents)   delete pCCEvents;
96          if (pEventQueue) delete pEventQueue;          if (pEventQueue) delete pEventQueue;
97          if (pEventPool)  delete pEventPool;          if (pEventPool)  delete pEventPool;
98          if (pVoicePool)  delete pVoicePool;          if (pVoicePool) {
99                    pVoicePool->clear();
100                    delete pVoicePool;
101            }
102          if (pActiveKeys) delete pActiveKeys;          if (pActiveKeys) delete pActiveKeys;
103            if (pSysexBuffer) delete pSysexBuffer;
104          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
105          if (pMainFilterParameters) delete[] pMainFilterParameters;          if (pMainFilterParameters) delete[] pMainFilterParameters;
106          if (pBasicFilterParameters) delete[] pBasicFilterParameters;          if (pBasicFilterParameters) delete[] pBasicFilterParameters;
107          if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];          if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
108            if (pVoiceStealingQueue) delete pVoiceStealingQueue;
109      }      }
110    
111      void Engine::Enable() {      void Engine::Enable() {
# Line 146  namespace LinuxSampler { namespace gig { Line 162  namespace LinuxSampler { namespace gig {
162          SustainPedal        = false;          SustainPedal        = false;
163          ActiveVoiceCount    = 0;          ActiveVoiceCount    = 0;
164          ActiveVoiceCountMax = 0;          ActiveVoiceCountMax = 0;
165            GlobalVolume        = 1.0;
166    
167            // reset voice stealing parameters
168            itLastStolenVoice = RTList<Voice>::Iterator();
169            iuiLastStolenKey  = RTList<uint>::Iterator();
170            pVoiceStealingQueue->clear();
171    
172            // reset to normal chromatic scale (means equal temper)
173            memset(&ScaleTuning[0], 0x00, 12);
174    
175          // set all MIDI controller values to zero          // set all MIDI controller values to zero
176          memset(ControllerTable, 0x00, 128);          memset(ControllerTable, 0x00, 128);
# Line 154  namespace LinuxSampler { namespace gig { Line 179  namespace LinuxSampler { namespace gig {
179          for (uint i = 0; i < 128; i++) {          for (uint i = 0; i < 128; i++) {
180              pMIDIKeyInfo[i].pActiveVoices->clear();              pMIDIKeyInfo[i].pActiveVoices->clear();
181              pMIDIKeyInfo[i].pEvents->clear();              pMIDIKeyInfo[i].pEvents->clear();
182              pMIDIKeyInfo[i].KeyPressed = false;              pMIDIKeyInfo[i].KeyPressed     = false;
183              pMIDIKeyInfo[i].Active     = false;              pMIDIKeyInfo[i].Active         = false;
184              pMIDIKeyInfo[i].pSelf      = NULL;              pMIDIKeyInfo[i].ReleaseTrigger = false;
185                pMIDIKeyInfo[i].itSelf         = Pool<uint>::Iterator();
186          }          }
187    
188            // reset all key groups
189            map<uint,uint*>::iterator iter = ActiveKeyGroups.begin();
190            for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;
191    
192          // reset all voices          // reset all voices
193          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
194              pVoice->Reset();              iterVoice->Reset();
195          }          }
196          pVoicePool->clear();          pVoicePool->clear();
197    
# Line 195  namespace LinuxSampler { namespace gig { Line 225  namespace LinuxSampler { namespace gig {
225              Instruments.HandBack(pInstrument, this);              Instruments.HandBack(pInstrument, this);
226          }          }
227    
228            InstrumentFile = FileName;
229            InstrumentIdx = Instrument;
230            InstrumentStat = 0;
231    
232            // delete all key groups
233            ActiveKeyGroups.clear();
234    
235          // request gig instrument from instrument manager          // request gig instrument from instrument manager
236          try {          try {
237              instrument_id_t instrid;              instrument_id_t instrid;
# Line 202  namespace LinuxSampler { namespace gig { Line 239  namespace LinuxSampler { namespace gig {
239              instrid.iInstrument = Instrument;              instrid.iInstrument = Instrument;
240              pInstrument = Instruments.Borrow(instrid, this);              pInstrument = Instruments.Borrow(instrid, this);
241              if (!pInstrument) {              if (!pInstrument) {
242                    InstrumentStat = -1;
243                  dmsg(1,("no instrument loaded!!!\n"));                  dmsg(1,("no instrument loaded!!!\n"));
244                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
245              }              }
246          }          }
247          catch (RIFF::Exception e) {          catch (RIFF::Exception e) {
248                InstrumentStat = -2;
249              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;
250              throw LinuxSamplerException(msg);              throw LinuxSamplerException(msg);
251          }          }
252          catch (InstrumentResourceManagerException e) {          catch (InstrumentResourceManagerException e) {
253                InstrumentStat = -3;
254              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();
255              throw LinuxSamplerException(msg);              throw LinuxSamplerException(msg);
256          }          }
257          catch (...) {          catch (...) {
258                InstrumentStat = -4;
259              throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");              throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");
260          }          }
261    
262            // 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            InstrumentStat = 100;
267    
268          // inform audio driver for the need of two channels          // inform audio driver for the need of two channels
269          try {          try {
270              if (pAudioOutputDevice) pAudioOutputDevice->AcquireChannels(2); // gig Engine only stereo              if (pAudioOutputDevice) pAudioOutputDevice->AcquireChannels(2); // gig Engine only stereo
# Line 247  namespace LinuxSampler { namespace gig { Line 294  namespace LinuxSampler { namespace gig {
294       * update process was completed, so we can continue with playback.       * update process was completed, so we can continue with playback.
295       */       */
296      void Engine::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {      void Engine::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {
297          this->pInstrument = pNewResource;          this->pInstrument = pNewResource; //TODO: there are couple of engine parameters we should update here as well if the instrument was updated (see LoadInstrument())
298          Enable();          Enable();
299      }      }
300    
# Line 265  namespace LinuxSampler { namespace gig { Line 312  namespace LinuxSampler { namespace gig {
312              throw LinuxSamplerException(msg);              throw LinuxSamplerException(msg);
313          }          }
314    
315            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            // 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          // (re)create disk thread          // (re)create disk thread
328          if (this->pDiskThread) {          if (this->pDiskThread) {
329                dmsg(1,("Stopping disk thread..."));
330              this->pDiskThread->StopThread();              this->pDiskThread->StopThread();
331              delete this->pDiskThread;              delete this->pDiskThread;
332                dmsg(1,("OK\n"));
333          }          }
334          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo
335          if (!pDiskThread) {          if (!pDiskThread) {
# Line 276  namespace LinuxSampler { namespace gig { Line 337  namespace LinuxSampler { namespace gig {
337              exit(EXIT_FAILURE);              exit(EXIT_FAILURE);
338          }          }
339    
340          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
341              pVoice->pDiskThread = this->pDiskThread;              iterVoice->pDiskThread = this->pDiskThread;
             pVoice->SetOutput(pAudioOut);  
342              dmsg(3,("d"));              dmsg(3,("d"));
343          }          }
344          pVoicePool->clear();          pVoicePool->clear();
# Line 288  namespace LinuxSampler { namespace gig { Line 348  namespace LinuxSampler { namespace gig {
348          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
349    
350          // (re)allocate synthesis parameter matrix          // (re)allocate synthesis parameter matrix
351          if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];          if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
352          pSynthesisParameters[0] = new float[Event::destination_count * pAudioOut->MaxSamplesPerCycle()];          pSynthesisParameters[0] = (float *) memalign(16,(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle()));
353          for (int dst = 1; dst < Event::destination_count; dst++)          for (int dst = 1; dst < Event::destination_count; dst++)
354              pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();              pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();
355    
# Line 303  namespace LinuxSampler { namespace gig { Line 363  namespace LinuxSampler { namespace gig {
363          pDiskThread->StartThread();          pDiskThread->StartThread();
364          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
365    
366          for (Voice* pVoice = pVoicePool->first(); pVoice; pVoice = pVoicePool->next()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
367              if (!pVoice->pDiskThread) {              if (!iterVoice->pDiskThread) {
368                  dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));                  dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));
369                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
370              }              }
# Line 316  namespace LinuxSampler { namespace gig { Line 376  namespace LinuxSampler { namespace gig {
376              AudioOutputDevice* olddevice = pAudioOutputDevice;              AudioOutputDevice* olddevice = pAudioOutputDevice;
377              pAudioOutputDevice = NULL;              pAudioOutputDevice = NULL;
378              olddevice->Disconnect(this);              olddevice->Disconnect(this);
379                AudioDeviceChannelLeft  = -1;
380                AudioDeviceChannelRight = -1;
381          }          }
382      }      }
383    
# Line 343  namespace LinuxSampler { namespace gig { Line 405  namespace LinuxSampler { namespace gig {
405          }          }
406    
407    
408            // update time of start and end of this audio fragment (as events' time stamps relate to this)
409            pEventGenerator->UpdateFragmentTime(Samples);
410    
411    
412          // empty the event lists for the new fragment          // empty the event lists for the new fragment
413          pEvents->clear();          pEvents->clear();
414          pCCEvents->clear();          pCCEvents->clear();
415          for (uint i = 0; i < Event::destination_count; i++) {          for (uint i = 0; i < Event::destination_count; i++) {
416              pSynthesisEvents[i]->clear();              pSynthesisEvents[i]->clear();
417          }          }
418            {
419          // read and copy events from input queue              RTList<uint>::Iterator iuiKey = pActiveKeys->first();
420          Event event = pEventGenerator->CreateEvent();              RTList<uint>::Iterator end    = pActiveKeys->end();
421          while (true) {              for(; iuiKey != end; ++iuiKey) {
422              if (!pEventQueue->pop(&event)) break;                  pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key
423              pEvents->alloc_assign(event);              }
424          }          }
425    
426    
427          // update time of start and end of this audio fragment (as events' time stamps relate to this)          // get all events from the input event queue which belong to the current fragment
428          pEventGenerator->UpdateFragmentTime(Samples);          {
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            }
450    
451    
452          // process events          // process events
453          Event* pNextEvent = pEvents->first();          {
454          while (pNextEvent) {              RTList<Event>::Iterator itEvent = pEvents->first();
455              Event* pEvent = pNextEvent;              RTList<Event>::Iterator end     = pEvents->end();
456              pEvents->set_current(pEvent);              for (; itEvent != end; ++itEvent) {
457              pNextEvent = pEvents->next();                  switch (itEvent->Type) {
458              switch (pEvent->Type) {                      case Event::type_note_on:
459                  case Event::type_note_on:                          dmsg(5,("Engine: Note on received\n"));
460                      dmsg(5,("Audio Thread: Note on received\n"));                          ProcessNoteOn(itEvent);
461                      ProcessNoteOn(pEvent);                          break;
462                      break;                      case Event::type_note_off:
463                  case Event::type_note_off:                          dmsg(5,("Engine: Note off received\n"));
464                      dmsg(5,("Audio Thread: Note off received\n"));                          ProcessNoteOff(itEvent);
465                      ProcessNoteOff(pEvent);                          break;
466                      break;                      case Event::type_control_change:
467                  case Event::type_control_change:                          dmsg(5,("Engine: MIDI CC received\n"));
468                      dmsg(5,("Audio Thread: MIDI CC received\n"));                          ProcessControlChange(itEvent);
469                      ProcessControlChange(pEvent);                          break;
470                      break;                      case Event::type_pitchbend:
471                  case Event::type_pitchbend:                          dmsg(5,("Engine: Pitchbend received\n"));
472                      dmsg(5,("Audio Thread: Pitchbend received\n"));                          ProcessPitchbend(itEvent);
473                      ProcessPitchbend(pEvent);                          break;
474                      break;                      case Event::type_sysex:
475                            dmsg(5,("Engine: Sysex received\n"));
476                            ProcessSysex(itEvent);
477                            break;
478                    }
479              }              }
480          }          }
481    
482    
         // render audio from all active voices  
483          int active_voices = 0;          int active_voices = 0;
484          uint* piKey = pActiveKeys->first();  
485          while (piKey) { // iterate through all active keys          // render audio from all active voices
486              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];          {
487              pActiveKeys->set_current(piKey);              RTList<uint>::Iterator iuiKey = pActiveKeys->first();
488              piKey = pActiveKeys->next();              RTList<uint>::Iterator end    = pActiveKeys->end();
489                while (iuiKey != end) { // iterate through all active keys
490              Voice* pVoiceNext = pKey->pActiveVoices->first();                  midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
491              while (pVoiceNext) { // iterate through all voices on this key                  ++iuiKey;
492                  // already get next voice on key  
493                  Voice* pVoice = pVoiceNext;                  RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
494                  pKey->pActiveVoices->set_current(pVoice);                  RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
495                  pVoiceNext = pKey->pActiveVoices->next();                  for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
496                        // now render current voice
497                  // now render current voice                      itVoice->Render(Samples);
498                  pVoice->Render(Samples);                      if (itVoice->IsActive()) active_voices++; // still active
499                  if (pVoice->IsActive()) active_voices++; // still active                      else { // voice reached end, is now inactive
500                  else { // voice reached end, is now inactive                          FreeVoice(itVoice); // remove voice from the list of active voices
501                      KillVoice(pVoice); // remove voice from the list of active voices                      }
502                  }                  }
503              }              }
504              pKey->pEvents->clear(); // free all events on the key          }
505    
506    
507            // now render all postponed voices from voice stealing
508            {
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                        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                        }
521                    }
522                    else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));
523                }
524            }
525            // reset voice stealing for the new fragment
526            pVoiceStealingQueue->clear();
527            itLastStolenVoice = RTList<Voice>::Iterator();
528            iuiLastStolenKey  = RTList<uint>::Iterator();
529    
530    
531            // 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    
# Line 432  namespace LinuxSampler { namespace gig { Line 568  namespace LinuxSampler { namespace gig {
568       *  @param Velocity - MIDI velocity value of the triggered key       *  @param Velocity - MIDI velocity value of the triggered key
569       */       */
570      void Engine::SendNoteOn(uint8_t Key, uint8_t Velocity) {      void Engine::SendNoteOn(uint8_t Key, uint8_t Velocity) {
571          Event event    = pEventGenerator->CreateEvent();          Event event               = pEventGenerator->CreateEvent();
572          event.Type     = Event::type_note_on;          event.Type                = Event::type_note_on;
573          event.Key      = Key;          event.Param.Note.Key      = Key;
574          event.Velocity = Velocity;          event.Param.Note.Velocity = Velocity;
575          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
576          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
577      }      }
# Line 448  namespace LinuxSampler { namespace gig { Line 584  namespace LinuxSampler { namespace gig {
584       *  @param Velocity - MIDI release velocity value of the released key       *  @param Velocity - MIDI release velocity value of the released key
585       */       */
586      void Engine::SendNoteOff(uint8_t Key, uint8_t Velocity) {      void Engine::SendNoteOff(uint8_t Key, uint8_t Velocity) {
587          Event event    = pEventGenerator->CreateEvent();          Event event               = pEventGenerator->CreateEvent();
588          event.Type     = Event::type_note_off;          event.Type                = Event::type_note_off;
589          event.Key      = Key;          event.Param.Note.Key      = Key;
590          event.Velocity = Velocity;          event.Param.Note.Velocity = Velocity;
591          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
592          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
593      }      }
# Line 463  namespace LinuxSampler { namespace gig { Line 599  namespace LinuxSampler { namespace gig {
599       *  @param Pitch - MIDI pitch value (-8192 ... +8191)       *  @param Pitch - MIDI pitch value (-8192 ... +8191)
600       */       */
601      void Engine::SendPitchbend(int Pitch) {      void Engine::SendPitchbend(int Pitch) {
602          Event event = pEventGenerator->CreateEvent();          Event event             = pEventGenerator->CreateEvent();
603          event.Type  = Event::type_pitchbend;          event.Type              = Event::type_pitchbend;
604          event.Pitch = Pitch;          event.Param.Pitch.Pitch = Pitch;
605          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
606          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
607      }      }
# Line 478  namespace LinuxSampler { namespace gig { Line 614  namespace LinuxSampler { namespace gig {
614       *  @param Value      - value of the control change       *  @param Value      - value of the control change
615       */       */
616      void Engine::SendControlChange(uint8_t Controller, uint8_t Value) {      void Engine::SendControlChange(uint8_t Controller, uint8_t Value) {
617          Event event      = pEventGenerator->CreateEvent();          Event event               = pEventGenerator->CreateEvent();
618          event.Type       = Event::type_control_change;          event.Type                = Event::type_control_change;
619          event.Controller = Controller;          event.Param.CC.Controller = Controller;
620          event.Value      = Value;          event.Param.CC.Value      = Value;
621          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
622          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
623      }      }
624    
625      /**      /**
626         *  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            Event event             = pEventGenerator->CreateEvent();
634            event.Type              = Event::type_sysex;
635            event.Param.Sysex.Size  = Size;
636            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       *  Assigns and triggers a new voice for the respective MIDI key.       *  Assigns and triggers a new voice for the respective MIDI key.
658       *       *
659       *  @param pNoteOnEvent - key, velocity and time stamp of the event       *  @param itNoteOnEvent - key, velocity and time stamp of the event
660       */       */
661      void Engine::ProcessNoteOn(Event* pNoteOnEvent) {      void Engine::ProcessNoteOn(Pool<Event>::Iterator& itNoteOnEvent) {
662          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Key];          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
663    
664          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
665    
666          // cancel release process of voices on this key if needed          // cancel release process of voices on this key if needed
667          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !SustainPedal) {
668              pNoteOnEvent->Type = Event::type_cancel_release; // transform event type              RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
669              pEvents->move(pNoteOnEvent, pKey->pEvents); // move event to the key's own event list              if (itCancelReleaseEvent) {
670          }                  *itCancelReleaseEvent = *itNoteOnEvent;                  // copy event
671                    itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type
         // allocate a new voice for the key  
         Voice* pNewVoice = pKey->pActiveVoices->alloc();  
         if (pNewVoice) {  
             // launch the new voice  
             if (pNewVoice->Trigger(pNoteOnEvent, this->Pitch, this->pInstrument) < 0) {  
                 dmsg(1,("Triggering new voice failed!\n"));  
                 pKey->pActiveVoices->free(pNewVoice);  
             }  
             else if (!pKey->Active) { // mark as active key  
                 pKey->Active = true;  
                 pKey->pSelf  = pActiveKeys->alloc();  
                 *pKey->pSelf = pNoteOnEvent->Key;  
672              }              }
673                else dmsg(1,("Event pool emtpy!\n"));
674          }          }
675          else std::cerr << "No free voice!" << std::endl << std::flush;  
676            // move note on event to the key's own event list
677            RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
678    
679            // allocate and trigger a new voice for the key
680            LaunchVoice(itNoteOnEventOnKeyList, 0, false, true);
681      }      }
682    
683      /**      /**
# Line 525  namespace LinuxSampler { namespace gig { Line 686  namespace LinuxSampler { namespace gig {
686       *  sustain pedal will be released or voice turned inactive by itself (e.g.       *  sustain pedal will be released or voice turned inactive by itself (e.g.
687       *  due to completion of sample playback).       *  due to completion of sample playback).
688       *       *
689       *  @param pNoteOffEvent - key, velocity and time stamp of the event       *  @param itNoteOffEvent - key, velocity and time stamp of the event
690       */       */
691      void Engine::ProcessNoteOff(Event* pNoteOffEvent) {      void Engine::ProcessNoteOff(Pool<Event>::Iterator& itNoteOffEvent) {
692          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOffEvent->Key];          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];
693    
694          pKey->KeyPressed = false; // the MIDI key was now released          pKey->KeyPressed = false; // the MIDI key was now released
695    
696          // release voices on this key if needed          // release voices on this key if needed
697          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !SustainPedal) {
698              pNoteOffEvent->Type = Event::type_release; // transform event type              itNoteOffEvent->Type = Event::type_release; // transform event type
699              pEvents->move(pNoteOffEvent, pKey->pEvents); // move event to the key's own event list          }
700    
701            // move event to the key's own event list
702            RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
703    
704            // spawn release triggered voice(s) if needed
705            if (pKey->ReleaseTrigger) {
706                LaunchVoice(itNoteOffEventOnKeyList, 0, true, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
707                pKey->ReleaseTrigger = false;
708          }          }
709      }      }
710    
# Line 543  namespace LinuxSampler { namespace gig { Line 712  namespace LinuxSampler { namespace gig {
712       *  Moves pitchbend event from the general (input) event list to the pitch       *  Moves pitchbend event from the general (input) event list to the pitch
713       *  event list.       *  event list.
714       *       *
715       *  @param pPitchbendEvent - absolute pitch value and time stamp of the event       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event
716         */
717        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        }
721    
722        /**
723         *  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         *  @param itNoteOnEvent       - key, velocity and time stamp of the event
728         *  @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         *  @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         */
738        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    
741            // allocate a new voice for the key
742            Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
743            if (itNewVoice) {
744                // launch the new voice
745                if (itNewVoice->Trigger(itNoteOnEvent, this->Pitch, this->pInstrument, iLayer, ReleaseTriggerVoice, VoiceStealing) < 0) {
746                    dmsg(1,("Triggering new voice failed!\n"));
747                    pKey->pActiveVoices->free(itNewVoice);
748                }
749                else { // on success
750                    uint** ppKeyGroup = NULL;
751                    if (itNewVoice->KeyGroup) { // if this voice / key belongs to a key group
752                        ppKeyGroup = &ActiveKeyGroups[itNewVoice->KeyGroup];
753                        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                            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                            }
761                        }
762                    }
763                    if (!pKey->Active) { // mark as active key
764                        pKey->Active = true;
765                        pKey->itSelf = pActiveKeys->allocAppend();
766                        *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
767                    }
768                    if (itNewVoice->KeyGroup) {
769                        *ppKeyGroup = &*pKey->itSelf; // put key as the (new) active key to its key group
770                    }
771                    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                }
774            }
775            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    
781                // 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            return Pool<Voice>::Iterator(); // no free voice or error
796        }
797    
798        /**
799         *  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         *  @param itNoteOnEvent - key, velocity and time stamp of the event
805       */       */
806      void Engine::ProcessPitchbend(Event* pPitchbendEvent) {      void Engine::StealVoice(Pool<Event>::Iterator& itNoteOnEvent) {
807          this->Pitch = pPitchbendEvent->Pitch; // store current pitch value          if (!pEventPool->poolIsEmpty()) {
808          pEvents->move(pPitchbendEvent, pSynthesisEvents[Event::destination_vco]);  
809                RTList<uint>::Iterator  iuiOldestKey;
810                RTList<Voice>::Iterator itOldestVoice;
811    
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                        midi_key_info_t* pOldestKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
821                        if (itLastStolenVoice) {
822                            itOldestVoice = itLastStolenVoice;
823                            ++itOldestVoice;
824                        }
825                        else { // no voice stolen in this audio fragment cycle yet
826                            itOldestVoice = pOldestKey->pActiveVoices->first();
827                        }
828                        if (itOldestVoice) {
829                            iuiOldestKey = pOldestKey->itSelf;
830                            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                        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                                }
848                                else {
849                                    dmsg(1,("gig::Engine: Warning, too less voices, even for voice stealing! - Better recompile with higher MAX_AUDIO_VOICES.\n"));
850                                    return;
851                                }
852                            }
853                            else iuiOldestKey = iuiLastStolenKey;
854                        }
855                        else { // no voice stolen in this audio fragment cycle yet
856                            iuiOldestKey = pActiveKeys->first();
857                            midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiOldestKey];
858                            itOldestVoice = pOldestKey->pActiveVoices->first();
859                        }
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                //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                // now kill the selected voice
875                itOldestVoice->Kill(itNoteOnEvent);
876                // remember which voice on which key we stole, so we can simply proceed for the next voice stealing
877                this->itLastStolenVoice = itOldestVoice;
878                this->iuiLastStolenKey = iuiOldestKey;
879            }
880            else dmsg(1,("Event pool emtpy!\n"));
881      }      }
882    
883      /**      /**
884       *  Immediately kills the voice given with pVoice (no matter if sustain is       *  Removes the given voice from the MIDI key's list of active voices.
885       *  pressed or not) and removes it from the MIDI key's list of active voice.       *  This method will be called when a voice went inactive, e.g. because
886       *  This method will e.g. be called if a voice went inactive by itself.       *  it finished to playback its sample, finished its release stage or
887         *  just was killed.
888       *       *
889       *  @param pVoice - points to the voice to be killed       *  @param itVoice - points to the voice to be freed
890       */       */
891      void Engine::KillVoice(Voice* pVoice) {      void Engine::FreeVoice(Pool<Voice>::Iterator& itVoice) {
892          if (pVoice) {          if (itVoice) {
893              if (pVoice->IsActive()) pVoice->Kill();              midi_key_info_t* pKey = &pMIDIKeyInfo[itVoice->MIDIKey];
894    
895              midi_key_info_t* pKey = &pMIDIKeyInfo[pVoice->MIDIKey];              uint keygroup = itVoice->KeyGroup;
896    
897              // free the voice object              // free the voice object
898              pVoicePool->free(pVoice);              pVoicePool->free(itVoice);
899    
900              // check if there are no voices left on the MIDI key and update the key info if so              // if no other voices left and member of a key group, remove from key group
901              if (pKey->pActiveVoices->is_empty()) {              if (pKey->pActiveVoices->isEmpty() && keygroup) {
902                  pKey->Active = false;                  uint** ppKeyGroup = &ActiveKeyGroups[keygroup];
903                  pActiveKeys->free(pKey->pSelf); // remove key from list of active keys                  if (*ppKeyGroup == &*pKey->itSelf) *ppKeyGroup = NULL; // remove key from key group
                 pKey->pSelf = NULL;  
                 dmsg(3,("Key has no more voices now\n"));  
904              }              }
905          }          }
906          else std::cerr << "Couldn't release voice! (pVoice == NULL)\n" << std::flush;          else std::cerr << "Couldn't release voice! (!itVoice)\n" << std::flush;
907        }
908    
909        /**
910         *  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       *  Reacts on supported control change commands (e.g. pitch bend wheel,       *  Reacts on supported control change commands (e.g. pitch bend wheel,
929       *  modulation wheel, aftertouch).       *  modulation wheel, aftertouch).
930       *       *
931       *  @param pControlChangeEvent - controller, value and time stamp of the event       *  @param itControlChangeEvent - controller, value and time stamp of the event
932       */       */
933      void Engine::ProcessControlChange(Event* pControlChangeEvent) {      void Engine::ProcessControlChange(Pool<Event>::Iterator& itControlChangeEvent) {
934          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", pControlChangeEvent->Controller, pControlChangeEvent->Value));          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", itControlChangeEvent->Param.CC.Controller, itControlChangeEvent->Param.CC.Value));
935    
936          switch (pControlChangeEvent->Controller) {          switch (itControlChangeEvent->Param.CC.Controller) {
937              case 64: {              case 64: {
938                  if (pControlChangeEvent->Value >= 64 && !SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value >= 64 && !SustainPedal) {
939                      dmsg(4,("PEDAL DOWN\n"));                      dmsg(4,("PEDAL DOWN\n"));
940                      SustainPedal = true;                      SustainPedal = true;
941    
942                      // cancel release process of voices if necessary                      // cancel release process of voices if necessary
943                      uint* piKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pActiveKeys->first();
944                      if (piKey) {                      if (iuiKey) {
945                          pControlChangeEvent->Type = Event::type_cancel_release; // transform event type                          itControlChangeEvent->Type = Event::type_cancel_release; // transform event type
946                          while (piKey) {                          while (iuiKey) {
947                              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];                              midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
948                              pActiveKeys->set_current(piKey);                              ++iuiKey;
                             piKey = pActiveKeys->next();  
949                              if (!pKey->KeyPressed) {                              if (!pKey->KeyPressed) {
950                                  Event* pNewEvent = pKey->pEvents->alloc();                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
951                                  if (pNewEvent) *pNewEvent = *pControlChangeEvent; // copy event to the key's own event list                                  if (itNewEvent) *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
952                                  else dmsg(1,("Event pool emtpy!\n"));                                  else dmsg(1,("Event pool emtpy!\n"));
953                              }                              }
954                          }                          }
955                      }                      }
956                  }                  }
957                  if (pControlChangeEvent->Value < 64 && SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value < 64 && SustainPedal) {
958                      dmsg(4,("PEDAL UP\n"));                      dmsg(4,("PEDAL UP\n"));
959                      SustainPedal = false;                      SustainPedal = false;
960    
961                      // release voices if their respective key is not pressed                      // release voices if their respective key is not pressed
962                      uint* piKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pActiveKeys->first();
963                      if (piKey) {                      if (iuiKey) {
964                          pControlChangeEvent->Type = Event::type_release; // transform event type                          itControlChangeEvent->Type = Event::type_release; // transform event type
965                          while (piKey) {                          while (iuiKey) {
966                              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];                              midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
967                              pActiveKeys->set_current(piKey);                              ++iuiKey;
                             piKey = pActiveKeys->next();  
968                              if (!pKey->KeyPressed) {                              if (!pKey->KeyPressed) {
969                                  Event* pNewEvent = pKey->pEvents->alloc();                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
970                                  if (pNewEvent) *pNewEvent = *pControlChangeEvent; // copy event to the key's own event list                                  if (itNewEvent) *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
971                                  else dmsg(1,("Event pool emtpy!\n"));                                  else dmsg(1,("Event pool emtpy!\n"));
972                              }                              }
973                          }                          }
# Line 633  namespace LinuxSampler { namespace gig { Line 978  namespace LinuxSampler { namespace gig {
978          }          }
979    
980          // update controller value in the engine's controller table          // update controller value in the engine's controller table
981          ControllerTable[pControlChangeEvent->Controller] = pControlChangeEvent->Value;          ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
982    
983          // move event from the unsorted event list to the control change event list          // move event from the unsorted event list to the control change event list
984          pEvents->move(pControlChangeEvent, pCCEvents);          itControlChangeEvent.moveToEndOf(pCCEvents);
985        }
986    
987        /**
988         *  Reacts on MIDI system exclusive messages.
989         *
990         *  @param itSysexEvent - sysex data size and time stamp of the sysex event
991         */
992        void Engine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) {
993            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            pSysexBuffer->increment_read_ptr(itSysexEvent->Param.Sysex.Size);
1041        }
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      /**      /**
# Line 662  namespace LinuxSampler { namespace gig { Line 1090  namespace LinuxSampler { namespace gig {
1090          GlobalVolume = f;          GlobalVolume = f;
1091      }      }
1092    
1093        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      uint Engine::VoiceCount() {      uint Engine::VoiceCount() {
1126          return ActiveVoiceCount;          return ActiveVoiceCount;
1127      }      }
# Line 690  namespace LinuxSampler { namespace gig { Line 1150  namespace LinuxSampler { namespace gig {
1150          return pDiskThread->GetBufferFillPercentage();          return pDiskThread->GetBufferFillPercentage();
1151      }      }
1152    
1153        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        int Engine::InstrumentStatus() {
1166            return InstrumentStat;
1167        }
1168    
1169      String Engine::Description() {      String Engine::Description() {
1170          return "Gigasampler Engine";          return "Gigasampler Engine";
1171      }      }
1172    
1173      String Engine::Version() {      String Engine::Version() {
1174          return "0.0.1-0cvs20040423";          String s = "$Revision: 1.20 $";
1175            return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword
1176      }      }
1177    
1178  }} // namespace LinuxSampler::gig  }} // namespace LinuxSampler::gig

Legend:
Removed from v.80  
changed lines
  Added in v.329

  ViewVC Help
Powered by ViewVC