/[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 351 by schoenebeck, Tue Jan 25 22:11:43 2005 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    
86            if (pInstrument) Instruments.HandBack(pInstrument, this);
87    
88          if (pGig)  delete pGig;          if (pGig)  delete pGig;
89          if (pRIFF) delete pRIFF;          if (pRIFF) delete pRIFF;
90          for (uint i = 0; i < 128; i++) {          for (uint i = 0; i < 128; i++) {
# Line 79  namespace LinuxSampler { namespace gig { Line 94  namespace LinuxSampler { namespace gig {
94          for (uint i = 0; i < Event::destination_count; i++) {          for (uint i = 0; i < Event::destination_count; i++) {
95              if (pSynthesisEvents[i]) delete pSynthesisEvents[i];              if (pSynthesisEvents[i]) delete pSynthesisEvents[i];
96          }          }
         delete[] pSynthesisEvents;  
97          if (pEvents)     delete pEvents;          if (pEvents)     delete pEvents;
98          if (pCCEvents)   delete pCCEvents;          if (pCCEvents)   delete pCCEvents;
99          if (pEventQueue) delete pEventQueue;          if (pEventQueue) delete pEventQueue;
100          if (pEventPool)  delete pEventPool;          if (pEventPool)  delete pEventPool;
101          if (pVoicePool)  delete pVoicePool;          if (pVoicePool) {
102                    pVoicePool->clear();
103                    delete pVoicePool;
104            }
105          if (pActiveKeys) delete pActiveKeys;          if (pActiveKeys) delete pActiveKeys;
106            if (pSysexBuffer) delete pSysexBuffer;
107          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
108          if (pMainFilterParameters) delete[] pMainFilterParameters;          if (pMainFilterParameters) delete[] pMainFilterParameters;
109          if (pBasicFilterParameters) delete[] pBasicFilterParameters;          if (pBasicFilterParameters) delete[] pBasicFilterParameters;
110          if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];          if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
111            if (pVoiceStealingQueue) delete pVoiceStealingQueue;
112      }      }
113    
114      void Engine::Enable() {      void Engine::Enable() {
# Line 146  namespace LinuxSampler { namespace gig { Line 165  namespace LinuxSampler { namespace gig {
165          SustainPedal        = false;          SustainPedal        = false;
166          ActiveVoiceCount    = 0;          ActiveVoiceCount    = 0;
167          ActiveVoiceCountMax = 0;          ActiveVoiceCountMax = 0;
168            GlobalVolume        = 1.0;
169    
170            // reset voice stealing parameters
171            itLastStolenVoice = RTList<Voice>::Iterator();
172            iuiLastStolenKey  = RTList<uint>::Iterator();
173            pVoiceStealingQueue->clear();
174    
175            // reset to normal chromatic scale (means equal temper)
176            memset(&ScaleTuning[0], 0x00, 12);
177    
178          // set all MIDI controller values to zero          // set all MIDI controller values to zero
179          memset(ControllerTable, 0x00, 128);          memset(ControllerTable, 0x00, 128);
# Line 154  namespace LinuxSampler { namespace gig { Line 182  namespace LinuxSampler { namespace gig {
182          for (uint i = 0; i < 128; i++) {          for (uint i = 0; i < 128; i++) {
183              pMIDIKeyInfo[i].pActiveVoices->clear();              pMIDIKeyInfo[i].pActiveVoices->clear();
184              pMIDIKeyInfo[i].pEvents->clear();              pMIDIKeyInfo[i].pEvents->clear();
185              pMIDIKeyInfo[i].KeyPressed = false;              pMIDIKeyInfo[i].KeyPressed     = false;
186              pMIDIKeyInfo[i].Active     = false;              pMIDIKeyInfo[i].Active         = false;
187              pMIDIKeyInfo[i].pSelf      = NULL;              pMIDIKeyInfo[i].ReleaseTrigger = false;
188                pMIDIKeyInfo[i].itSelf         = Pool<uint>::Iterator();
189          }          }
190    
191            // reset all key groups
192            map<uint,uint*>::iterator iter = ActiveKeyGroups.begin();
193            for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;
194    
195          // reset all voices          // reset all voices
196          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
197              pVoice->Reset();              iterVoice->Reset();
198          }          }
199          pVoicePool->clear();          pVoicePool->clear();
200    
# Line 195  namespace LinuxSampler { namespace gig { Line 228  namespace LinuxSampler { namespace gig {
228              Instruments.HandBack(pInstrument, this);              Instruments.HandBack(pInstrument, this);
229          }          }
230    
231            InstrumentFile = FileName;
232            InstrumentIdx = Instrument;
233            InstrumentStat = 0;
234    
235            // delete all key groups
236            ActiveKeyGroups.clear();
237    
238          // request gig instrument from instrument manager          // request gig instrument from instrument manager
239          try {          try {
240              instrument_id_t instrid;              instrument_id_t instrid;
# Line 202  namespace LinuxSampler { namespace gig { Line 242  namespace LinuxSampler { namespace gig {
242              instrid.iInstrument = Instrument;              instrid.iInstrument = Instrument;
243              pInstrument = Instruments.Borrow(instrid, this);              pInstrument = Instruments.Borrow(instrid, this);
244              if (!pInstrument) {              if (!pInstrument) {
245                    InstrumentStat = -1;
246                  dmsg(1,("no instrument loaded!!!\n"));                  dmsg(1,("no instrument loaded!!!\n"));
247                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
248              }              }
249          }          }
250          catch (RIFF::Exception e) {          catch (RIFF::Exception e) {
251                InstrumentStat = -2;
252              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;
253              throw LinuxSamplerException(msg);              throw LinuxSamplerException(msg);
254          }          }
255          catch (InstrumentResourceManagerException e) {          catch (InstrumentResourceManagerException e) {
256                InstrumentStat = -3;
257              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();
258              throw LinuxSamplerException(msg);              throw LinuxSamplerException(msg);
259          }          }
260          catch (...) {          catch (...) {
261                InstrumentStat = -4;
262              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.");
263          }          }
264    
265            // 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            InstrumentStat = 100;
270    
271          // inform audio driver for the need of two channels          // inform audio driver for the need of two channels
272          try {          try {
273              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 297  namespace LinuxSampler { namespace gig {
297       * update process was completed, so we can continue with playback.       * update process was completed, so we can continue with playback.
298       */       */
299      void Engine::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {      void Engine::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {
300          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())
301          Enable();          Enable();
302      }      }
303    
# Line 265  namespace LinuxSampler { namespace gig { Line 315  namespace LinuxSampler { namespace gig {
315              throw LinuxSamplerException(msg);              throw LinuxSamplerException(msg);
316          }          }
317    
318            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            // 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          // (re)create disk thread          // (re)create disk thread
331          if (this->pDiskThread) {          if (this->pDiskThread) {
332                dmsg(1,("Stopping disk thread..."));
333              this->pDiskThread->StopThread();              this->pDiskThread->StopThread();
334              delete this->pDiskThread;              delete this->pDiskThread;
335                dmsg(1,("OK\n"));
336          }          }
337          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
338          if (!pDiskThread) {          if (!pDiskThread) {
# Line 276  namespace LinuxSampler { namespace gig { Line 340  namespace LinuxSampler { namespace gig {
340              exit(EXIT_FAILURE);              exit(EXIT_FAILURE);
341          }          }
342    
343          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
344              pVoice->pDiskThread = this->pDiskThread;              iterVoice->pDiskThread = this->pDiskThread;
             pVoice->SetOutput(pAudioOut);  
345              dmsg(3,("d"));              dmsg(3,("d"));
346          }          }
347          pVoicePool->clear();          pVoicePool->clear();
# Line 288  namespace LinuxSampler { namespace gig { Line 351  namespace LinuxSampler { namespace gig {
351          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
352    
353          // (re)allocate synthesis parameter matrix          // (re)allocate synthesis parameter matrix
354          if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];          if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
355          pSynthesisParameters[0] = new float[Event::destination_count * pAudioOut->MaxSamplesPerCycle()];          pSynthesisParameters[0] = (float *) memalign(16,(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle()));
356          for (int dst = 1; dst < Event::destination_count; dst++)          for (int dst = 1; dst < Event::destination_count; dst++)
357              pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();              pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();
358    
# Line 303  namespace LinuxSampler { namespace gig { Line 366  namespace LinuxSampler { namespace gig {
366          pDiskThread->StartThread();          pDiskThread->StartThread();
367          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
368    
369          for (Voice* pVoice = pVoicePool->first(); pVoice; pVoice = pVoicePool->next()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
370              if (!pVoice->pDiskThread) {              if (!iterVoice->pDiskThread) {
371                  dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));                  dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));
372                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
373              }              }
# Line 316  namespace LinuxSampler { namespace gig { Line 379  namespace LinuxSampler { namespace gig {
379              AudioOutputDevice* olddevice = pAudioOutputDevice;              AudioOutputDevice* olddevice = pAudioOutputDevice;
380              pAudioOutputDevice = NULL;              pAudioOutputDevice = NULL;
381              olddevice->Disconnect(this);              olddevice->Disconnect(this);
382                AudioDeviceChannelLeft  = -1;
383                AudioDeviceChannelRight = -1;
384          }          }
385      }      }
386    
# Line 343  namespace LinuxSampler { namespace gig { Line 408  namespace LinuxSampler { namespace gig {
408          }          }
409    
410    
411            // update time of start and end of this audio fragment (as events' time stamps relate to this)
412            pEventGenerator->UpdateFragmentTime(Samples);
413    
414    
415          // empty the event lists for the new fragment          // empty the event lists for the new fragment
416          pEvents->clear();          pEvents->clear();
417          pCCEvents->clear();          pCCEvents->clear();
418          for (uint i = 0; i < Event::destination_count; i++) {          for (uint i = 0; i < Event::destination_count; i++) {
419              pSynthesisEvents[i]->clear();              pSynthesisEvents[i]->clear();
420          }          }
421            {
422          // read and copy events from input queue              RTList<uint>::Iterator iuiKey = pActiveKeys->first();
423          Event event = pEventGenerator->CreateEvent();              RTList<uint>::Iterator end    = pActiveKeys->end();
424          while (true) {              for(; iuiKey != end; ++iuiKey) {
425              if (!pEventQueue->pop(&event)) break;                  pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key
426              pEvents->alloc_assign(event);              }
427          }          }
428    
429    
430          // 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
431          pEventGenerator->UpdateFragmentTime(Samples);          {
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            }
453    
454    
455          // process events          // process events
456          Event* pNextEvent = pEvents->first();          {
457          while (pNextEvent) {              RTList<Event>::Iterator itEvent = pEvents->first();
458              Event* pEvent = pNextEvent;              RTList<Event>::Iterator end     = pEvents->end();
459              pEvents->set_current(pEvent);              for (; itEvent != end; ++itEvent) {
460              pNextEvent = pEvents->next();                  switch (itEvent->Type) {
461              switch (pEvent->Type) {                      case Event::type_note_on:
462                  case Event::type_note_on:                          dmsg(5,("Engine: Note on received\n"));
463                      dmsg(5,("Audio Thread: Note on received\n"));                          ProcessNoteOn(itEvent);
464                      ProcessNoteOn(pEvent);                          break;
465                      break;                      case Event::type_note_off:
466                  case Event::type_note_off:                          dmsg(5,("Engine: Note off received\n"));
467                      dmsg(5,("Audio Thread: Note off received\n"));                          ProcessNoteOff(itEvent);
468                      ProcessNoteOff(pEvent);                          break;
469                      break;                      case Event::type_control_change:
470                  case Event::type_control_change:                          dmsg(5,("Engine: MIDI CC received\n"));
471                      dmsg(5,("Audio Thread: MIDI CC received\n"));                          ProcessControlChange(itEvent);
472                      ProcessControlChange(pEvent);                          break;
473                      break;                      case Event::type_pitchbend:
474                  case Event::type_pitchbend:                          dmsg(5,("Engine: Pitchbend received\n"));
475                      dmsg(5,("Audio Thread: Pitchbend received\n"));                          ProcessPitchbend(itEvent);
476                      ProcessPitchbend(pEvent);                          break;
477                      break;                      case Event::type_sysex:
478                            dmsg(5,("Engine: Sysex received\n"));
479                            ProcessSysex(itEvent);
480                            break;
481                    }
482              }              }
483          }          }
484    
485    
         // render audio from all active voices  
486          int active_voices = 0;          int active_voices = 0;
487          uint* piKey = pActiveKeys->first();  
488          while (piKey) { // iterate through all active keys          // render audio from all active voices
489              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];          {
490              pActiveKeys->set_current(piKey);              RTList<uint>::Iterator iuiKey = pActiveKeys->first();
491              piKey = pActiveKeys->next();              RTList<uint>::Iterator end    = pActiveKeys->end();
492                while (iuiKey != end) { // iterate through all active keys
493              Voice* pVoiceNext = pKey->pActiveVoices->first();                  midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
494              while (pVoiceNext) { // iterate through all voices on this key                  ++iuiKey;
495                  // already get next voice on key  
496                  Voice* pVoice = pVoiceNext;                  RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
497                  pKey->pActiveVoices->set_current(pVoice);                  RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
498                  pVoiceNext = pKey->pActiveVoices->next();                  for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
499                        // now render current voice
500                  // now render current voice                      itVoice->Render(Samples);
501                  pVoice->Render(Samples);                      if (itVoice->IsActive()) active_voices++; // still active
502                  if (pVoice->IsActive()) active_voices++; // still active                      else { // voice reached end, is now inactive
503                  else { // voice reached end, is now inactive                          FreeVoice(itVoice); // remove voice from the list of active voices
504                      KillVoice(pVoice); // remove voice from the list of active voices                      }
505                    }
506                }
507            }
508    
509    
510            // now render all postponed voices from voice stealing
511            {
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                        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                        }
524                    }
525                    else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));
526                }
527            }
528            // reset voice stealing for the new fragment
529            pVoiceStealingQueue->clear();
530            itLastStolenVoice = RTList<Voice>::Iterator();
531            iuiLastStolenKey  = RTList<uint>::Iterator();
532    
533    
534            // 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              }              }
             pKey->pEvents->clear(); // free all events on the key  
554          }          }
555    
556    
# Line 432  namespace LinuxSampler { namespace gig { Line 571  namespace LinuxSampler { namespace gig {
571       *  @param Velocity - MIDI velocity value of the triggered key       *  @param Velocity - MIDI velocity value of the triggered key
572       */       */
573      void Engine::SendNoteOn(uint8_t Key, uint8_t Velocity) {      void Engine::SendNoteOn(uint8_t Key, uint8_t Velocity) {
574          Event event    = pEventGenerator->CreateEvent();          Event event               = pEventGenerator->CreateEvent();
575          event.Type     = Event::type_note_on;          event.Type                = Event::type_note_on;
576          event.Key      = Key;          event.Param.Note.Key      = Key;
577          event.Velocity = Velocity;          event.Param.Note.Velocity = Velocity;
578          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
579          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
580      }      }
# Line 448  namespace LinuxSampler { namespace gig { Line 587  namespace LinuxSampler { namespace gig {
587       *  @param Velocity - MIDI release velocity value of the released key       *  @param Velocity - MIDI release velocity value of the released key
588       */       */
589      void Engine::SendNoteOff(uint8_t Key, uint8_t Velocity) {      void Engine::SendNoteOff(uint8_t Key, uint8_t Velocity) {
590          Event event    = pEventGenerator->CreateEvent();          Event event               = pEventGenerator->CreateEvent();
591          event.Type     = Event::type_note_off;          event.Type                = Event::type_note_off;
592          event.Key      = Key;          event.Param.Note.Key      = Key;
593          event.Velocity = Velocity;          event.Param.Note.Velocity = Velocity;
594          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
595          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
596      }      }
# Line 463  namespace LinuxSampler { namespace gig { Line 602  namespace LinuxSampler { namespace gig {
602       *  @param Pitch - MIDI pitch value (-8192 ... +8191)       *  @param Pitch - MIDI pitch value (-8192 ... +8191)
603       */       */
604      void Engine::SendPitchbend(int Pitch) {      void Engine::SendPitchbend(int Pitch) {
605          Event event = pEventGenerator->CreateEvent();          Event event             = pEventGenerator->CreateEvent();
606          event.Type  = Event::type_pitchbend;          event.Type              = Event::type_pitchbend;
607          event.Pitch = Pitch;          event.Param.Pitch.Pitch = Pitch;
608          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
609          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
610      }      }
# Line 478  namespace LinuxSampler { namespace gig { Line 617  namespace LinuxSampler { namespace gig {
617       *  @param Value      - value of the control change       *  @param Value      - value of the control change
618       */       */
619      void Engine::SendControlChange(uint8_t Controller, uint8_t Value) {      void Engine::SendControlChange(uint8_t Controller, uint8_t Value) {
620          Event event      = pEventGenerator->CreateEvent();          Event event               = pEventGenerator->CreateEvent();
621          event.Type       = Event::type_control_change;          event.Type                = Event::type_control_change;
622          event.Controller = Controller;          event.Param.CC.Controller = Controller;
623          event.Value      = Value;          event.Param.CC.Value      = Value;
624          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
625          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
626      }      }
627    
628      /**      /**
629         *  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            Event event             = pEventGenerator->CreateEvent();
637            event.Type              = Event::type_sysex;
638            event.Param.Sysex.Size  = Size;
639            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       *  Assigns and triggers a new voice for the respective MIDI key.       *  Assigns and triggers a new voice for the respective MIDI key.
661       *       *
662       *  @param pNoteOnEvent - key, velocity and time stamp of the event       *  @param itNoteOnEvent - key, velocity and time stamp of the event
663       */       */
664      void Engine::ProcessNoteOn(Event* pNoteOnEvent) {      void Engine::ProcessNoteOn(Pool<Event>::Iterator& itNoteOnEvent) {
665          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Key];          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
666    
667          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
668    
669          // cancel release process of voices on this key if needed          // cancel release process of voices on this key if needed
670          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !SustainPedal) {
671              pNoteOnEvent->Type = Event::type_cancel_release; // transform event type              RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
672              pEvents->move(pNoteOnEvent, pKey->pEvents); // move event to the key's own event list              if (itCancelReleaseEvent) {
673          }                  *itCancelReleaseEvent = *itNoteOnEvent;                  // copy event
674                    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;  
675              }              }
676                else dmsg(1,("Event pool emtpy!\n"));
677          }          }
678          else std::cerr << "No free voice!" << std::endl << std::flush;  
679            // move note on event to the key's own event list
680            RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
681    
682            // allocate and trigger a new voice for the key
683            LaunchVoice(itNoteOnEventOnKeyList, 0, false, true);
684      }      }
685    
686      /**      /**
# Line 525  namespace LinuxSampler { namespace gig { Line 689  namespace LinuxSampler { namespace gig {
689       *  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.
690       *  due to completion of sample playback).       *  due to completion of sample playback).
691       *       *
692       *  @param pNoteOffEvent - key, velocity and time stamp of the event       *  @param itNoteOffEvent - key, velocity and time stamp of the event
693       */       */
694      void Engine::ProcessNoteOff(Event* pNoteOffEvent) {      void Engine::ProcessNoteOff(Pool<Event>::Iterator& itNoteOffEvent) {
695          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOffEvent->Key];          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];
696    
697          pKey->KeyPressed = false; // the MIDI key was now released          pKey->KeyPressed = false; // the MIDI key was now released
698    
699          // release voices on this key if needed          // release voices on this key if needed
700          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !SustainPedal) {
701              pNoteOffEvent->Type = Event::type_release; // transform event type              itNoteOffEvent->Type = Event::type_release; // transform event type
702              pEvents->move(pNoteOffEvent, pKey->pEvents); // move event to the key's own event list          }
703    
704            // move event to the key's own event list
705            RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
706    
707            // spawn release triggered voice(s) if needed
708            if (pKey->ReleaseTrigger) {
709                LaunchVoice(itNoteOffEventOnKeyList, 0, true, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
710                pKey->ReleaseTrigger = false;
711          }          }
712      }      }
713    
# Line 543  namespace LinuxSampler { namespace gig { Line 715  namespace LinuxSampler { namespace gig {
715       *  Moves pitchbend event from the general (input) event list to the pitch       *  Moves pitchbend event from the general (input) event list to the pitch
716       *  event list.       *  event list.
717       *       *
718       *  @param pPitchbendEvent - absolute pitch value and time stamp of the event       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event
719         */
720        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        }
724    
725        /**
726         *  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         *  @param itNoteOnEvent       - key, velocity and time stamp of the event
731         *  @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         *  @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         */
741        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    
744            // allocate a new voice for the key
745            Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
746            if (itNewVoice) {
747                // launch the new voice
748                if (itNewVoice->Trigger(itNoteOnEvent, this->Pitch, this->pInstrument, iLayer, ReleaseTriggerVoice, VoiceStealing) < 0) {
749                    dmsg(1,("Triggering new voice failed!\n"));
750                    pKey->pActiveVoices->free(itNewVoice);
751                }
752                else { // on success
753                    uint** ppKeyGroup = NULL;
754                    if (itNewVoice->KeyGroup) { // if this voice / key belongs to a key group
755                        ppKeyGroup = &ActiveKeyGroups[itNewVoice->KeyGroup];
756                        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                            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                            }
764                        }
765                    }
766                    if (!pKey->Active) { // mark as active key
767                        pKey->Active = true;
768                        pKey->itSelf = pActiveKeys->allocAppend();
769                        *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
770                    }
771                    if (itNewVoice->KeyGroup) {
772                        *ppKeyGroup = &*pKey->itSelf; // put key as the (new) active key to its key group
773                    }
774                    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                }
777            }
778            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    
784                // 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            return Pool<Voice>::Iterator(); // no free voice or error
799        }
800    
801        /**
802         *  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         *  @param itNoteOnEvent - key, velocity and time stamp of the event
808       */       */
809      void Engine::ProcessPitchbend(Event* pPitchbendEvent) {      void Engine::StealVoice(Pool<Event>::Iterator& itNoteOnEvent) {
810          this->Pitch = pPitchbendEvent->Pitch; // store current pitch value          if (!pEventPool->poolIsEmpty()) {
811          pEvents->move(pPitchbendEvent, pSynthesisEvents[Event::destination_vco]);  
812                RTList<uint>::Iterator  iuiOldestKey;
813                RTList<Voice>::Iterator itOldestVoice;
814    
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                        midi_key_info_t* pOldestKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
824                        if (itLastStolenVoice) {
825                            itOldestVoice = itLastStolenVoice;
826                            ++itOldestVoice;
827                        }
828                        else { // no voice stolen in this audio fragment cycle yet
829                            itOldestVoice = pOldestKey->pActiveVoices->first();
830                        }
831                        if (itOldestVoice) {
832                            iuiOldestKey = pOldestKey->itSelf;
833                            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                        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                                }
851                                else {
852                                    dmsg(1,("gig::Engine: Warning, too less voices, even for voice stealing! - Better recompile with higher MAX_AUDIO_VOICES.\n"));
853                                    return;
854                                }
855                            }
856                            else iuiOldestKey = iuiLastStolenKey;
857                        }
858                        else { // no voice stolen in this audio fragment cycle yet
859                            iuiOldestKey = pActiveKeys->first();
860                            midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiOldestKey];
861                            itOldestVoice = pOldestKey->pActiveVoices->first();
862                        }
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                //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                // now kill the selected voice
878                itOldestVoice->Kill(itNoteOnEvent);
879                // remember which voice on which key we stole, so we can simply proceed for the next voice stealing
880                this->itLastStolenVoice = itOldestVoice;
881                this->iuiLastStolenKey = iuiOldestKey;
882            }
883            else dmsg(1,("Event pool emtpy!\n"));
884      }      }
885    
886      /**      /**
887       *  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.
888       *  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
889       *  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
890         *  just was killed.
891       *       *
892       *  @param pVoice - points to the voice to be killed       *  @param itVoice - points to the voice to be freed
893       */       */
894      void Engine::KillVoice(Voice* pVoice) {      void Engine::FreeVoice(Pool<Voice>::Iterator& itVoice) {
895          if (pVoice) {          if (itVoice) {
896              if (pVoice->IsActive()) pVoice->Kill();              midi_key_info_t* pKey = &pMIDIKeyInfo[itVoice->MIDIKey];
897    
898              midi_key_info_t* pKey = &pMIDIKeyInfo[pVoice->MIDIKey];              uint keygroup = itVoice->KeyGroup;
899    
900              // free the voice object              // free the voice object
901              pVoicePool->free(pVoice);              pVoicePool->free(itVoice);
902    
903              // 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
904              if (pKey->pActiveVoices->is_empty()) {              if (pKey->pActiveVoices->isEmpty() && keygroup) {
905                  pKey->Active = false;                  uint** ppKeyGroup = &ActiveKeyGroups[keygroup];
906                  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"));  
907              }              }
908          }          }
909          else std::cerr << "Couldn't release voice! (pVoice == NULL)\n" << std::flush;          else std::cerr << "Couldn't release voice! (!itVoice)\n" << std::flush;
910        }
911    
912        /**
913         *  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       *  Reacts on supported control change commands (e.g. pitch bend wheel,       *  Reacts on supported control change commands (e.g. pitch bend wheel,
932       *  modulation wheel, aftertouch).       *  modulation wheel, aftertouch).
933       *       *
934       *  @param pControlChangeEvent - controller, value and time stamp of the event       *  @param itControlChangeEvent - controller, value and time stamp of the event
935       */       */
936      void Engine::ProcessControlChange(Event* pControlChangeEvent) {      void Engine::ProcessControlChange(Pool<Event>::Iterator& itControlChangeEvent) {
937          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));
938    
939          switch (pControlChangeEvent->Controller) {          switch (itControlChangeEvent->Param.CC.Controller) {
940              case 64: {              case 64: {
941                  if (pControlChangeEvent->Value >= 64 && !SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value >= 64 && !SustainPedal) {
942                      dmsg(4,("PEDAL DOWN\n"));                      dmsg(4,("PEDAL DOWN\n"));
943                      SustainPedal = true;                      SustainPedal = true;
944    
945                      // cancel release process of voices if necessary                      // cancel release process of voices if necessary
946                      uint* piKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pActiveKeys->first();
947                      if (piKey) {                      if (iuiKey) {
948                          pControlChangeEvent->Type = Event::type_cancel_release; // transform event type                          itControlChangeEvent->Type = Event::type_cancel_release; // transform event type
949                          while (piKey) {                          while (iuiKey) {
950                              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];                              midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
951                              pActiveKeys->set_current(piKey);                              ++iuiKey;
                             piKey = pActiveKeys->next();  
952                              if (!pKey->KeyPressed) {                              if (!pKey->KeyPressed) {
953                                  Event* pNewEvent = pKey->pEvents->alloc();                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
954                                  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
955                                  else dmsg(1,("Event pool emtpy!\n"));                                  else dmsg(1,("Event pool emtpy!\n"));
956                              }                              }
957                          }                          }
958                      }                      }
959                  }                  }
960                  if (pControlChangeEvent->Value < 64 && SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value < 64 && SustainPedal) {
961                      dmsg(4,("PEDAL UP\n"));                      dmsg(4,("PEDAL UP\n"));
962                      SustainPedal = false;                      SustainPedal = false;
963    
964                      // release voices if their respective key is not pressed                      // release voices if their respective key is not pressed
965                      uint* piKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pActiveKeys->first();
966                      if (piKey) {                      if (iuiKey) {
967                          pControlChangeEvent->Type = Event::type_release; // transform event type                          itControlChangeEvent->Type = Event::type_release; // transform event type
968                          while (piKey) {                          while (iuiKey) {
969                              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];                              midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
970                              pActiveKeys->set_current(piKey);                              ++iuiKey;
                             piKey = pActiveKeys->next();  
971                              if (!pKey->KeyPressed) {                              if (!pKey->KeyPressed) {
972                                  Event* pNewEvent = pKey->pEvents->alloc();                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
973                                  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
974                                  else dmsg(1,("Event pool emtpy!\n"));                                  else dmsg(1,("Event pool emtpy!\n"));
975                              }                              }
976                          }                          }
# Line 633  namespace LinuxSampler { namespace gig { Line 981  namespace LinuxSampler { namespace gig {
981          }          }
982    
983          // update controller value in the engine's controller table          // update controller value in the engine's controller table
984          ControllerTable[pControlChangeEvent->Controller] = pControlChangeEvent->Value;          ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
985    
986          // 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
987          pEvents->move(pControlChangeEvent, pCCEvents);          itControlChangeEvent.moveToEndOf(pCCEvents);
988        }
989    
990        /**
991         *  Reacts on MIDI system exclusive messages.
992         *
993         *  @param itSysexEvent - sysex data size and time stamp of the sysex event
994         */
995        void Engine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) {
996            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            pSysexBuffer->increment_read_ptr(itSysexEvent->Param.Sysex.Size);
1044        }
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      /**      /**
# Line 662  namespace LinuxSampler { namespace gig { Line 1093  namespace LinuxSampler { namespace gig {
1093          GlobalVolume = f;          GlobalVolume = f;
1094      }      }
1095    
1096        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      uint Engine::VoiceCount() {      uint Engine::VoiceCount() {
1129          return ActiveVoiceCount;          return ActiveVoiceCount;
1130      }      }
# Line 690  namespace LinuxSampler { namespace gig { Line 1153  namespace LinuxSampler { namespace gig {
1153          return pDiskThread->GetBufferFillPercentage();          return pDiskThread->GetBufferFillPercentage();
1154      }      }
1155    
1156        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        int Engine::InstrumentStatus() {
1169            return InstrumentStat;
1170        }
1171    
1172      String Engine::Description() {      String Engine::Description() {
1173          return "Gigasampler Engine";          return "Gigasampler Engine";
1174      }      }
1175    
1176      String Engine::Version() {      String Engine::Version() {
1177          return "0.0.1-0cvs20040423";          String s = "$Revision: 1.21 $";
1178            return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword
1179      }      }
1180    
1181  }} // namespace LinuxSampler::gig  }} // namespace LinuxSampler::gig

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

  ViewVC Help
Powered by ViewVC