/[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 242 by schoenebeck, Wed Sep 15 13:59:08 2004 UTC revision 319 by schoenebeck, Mon Dec 13 00:46:42 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].ReleaseTrigger = false;              pMIDIKeyInfo[i].ReleaseTrigger = false;
58              pMIDIKeyInfo[i].pSelf          = NULL;              pMIDIKeyInfo[i].pEvents        = new RTList<Event>(pEventPool);
             pMIDIKeyInfo[i].pEvents        = new RTEList<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 93  namespace LinuxSampler { namespace gig { Line 96  namespace LinuxSampler { namespace gig {
96          if (pEventPool)  delete pEventPool;          if (pEventPool)  delete pEventPool;
97          if (pVoicePool)  delete pVoicePool;          if (pVoicePool)  delete pVoicePool;
98          if (pActiveKeys) delete pActiveKeys;          if (pActiveKeys) delete pActiveKeys;
99            if (pSysexBuffer) delete pSysexBuffer;
100          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
101          if (pMainFilterParameters) delete[] pMainFilterParameters;          if (pMainFilterParameters) delete[] pMainFilterParameters;
102          if (pBasicFilterParameters) delete[] pBasicFilterParameters;          if (pBasicFilterParameters) delete[] pBasicFilterParameters;
103          if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];          if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
104            if (pVoiceStealingQueue) delete pVoiceStealingQueue;
105      }      }
106    
107      void Engine::Enable() {      void Engine::Enable() {
# Line 155  namespace LinuxSampler { namespace gig { Line 160  namespace LinuxSampler { namespace gig {
160          ActiveVoiceCountMax = 0;          ActiveVoiceCountMax = 0;
161          GlobalVolume        = 1.0;          GlobalVolume        = 1.0;
162    
163            // reset voice stealing parameters
164            itLastStolenVoice = RTList<Voice>::Iterator();
165            iuiLastStolenKey  = RTList<uint>::Iterator();
166            pVoiceStealingQueue->clear();
167    
168            // reset to normal chromatic scale (means equal temper)
169            memset(&ScaleTuning[0], 0x00, 12);
170    
171          // set all MIDI controller values to zero          // set all MIDI controller values to zero
172          memset(ControllerTable, 0x00, 128);          memset(ControllerTable, 0x00, 128);
173    
# Line 165  namespace LinuxSampler { namespace gig { Line 178  namespace LinuxSampler { namespace gig {
178              pMIDIKeyInfo[i].KeyPressed     = false;              pMIDIKeyInfo[i].KeyPressed     = false;
179              pMIDIKeyInfo[i].Active         = false;              pMIDIKeyInfo[i].Active         = false;
180              pMIDIKeyInfo[i].ReleaseTrigger = false;              pMIDIKeyInfo[i].ReleaseTrigger = false;
181              pMIDIKeyInfo[i].pSelf          = NULL;              pMIDIKeyInfo[i].itSelf         = Pool<uint>::Iterator();
182          }          }
183    
184          // reset all key groups          // reset all key groups
# Line 173  namespace LinuxSampler { namespace gig { Line 186  namespace LinuxSampler { namespace gig {
186          for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;          for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;
187    
188          // reset all voices          // reset all voices
189          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
190              pVoice->Reset();              iterVoice->Reset();
191          }          }
192          pVoicePool->clear();          pVoicePool->clear();
193    
# Line 302  namespace LinuxSampler { namespace gig { Line 315  namespace LinuxSampler { namespace gig {
315          this->MaxSamplesPerCycle      = pAudioOutputDevice->MaxSamplesPerCycle();          this->MaxSamplesPerCycle      = pAudioOutputDevice->MaxSamplesPerCycle();
316          this->SampleRate              = pAudioOutputDevice->SampleRate();          this->SampleRate              = pAudioOutputDevice->SampleRate();
317    
318            // FIXME: audio drivers with varying fragment sizes might be a problem here
319            MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * EG_MIN_RELEASE_TIME) - 1;
320            if (MaxFadeOutPos < 0)
321                throw LinuxSamplerException("EG_MIN_RELEASE_TIME in EGADSR.h to big for current audio fragment size / sampling rate!");
322    
323          // (re)create disk thread          // (re)create disk thread
324          if (this->pDiskThread) {          if (this->pDiskThread) {
325              this->pDiskThread->StopThread();              this->pDiskThread->StopThread();
# Line 313  namespace LinuxSampler { namespace gig { Line 331  namespace LinuxSampler { namespace gig {
331              exit(EXIT_FAILURE);              exit(EXIT_FAILURE);
332          }          }
333    
334          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
335              pVoice->pDiskThread = this->pDiskThread;              iterVoice->pDiskThread = this->pDiskThread;
336              dmsg(3,("d"));              dmsg(3,("d"));
337          }          }
338          pVoicePool->clear();          pVoicePool->clear();
# Line 324  namespace LinuxSampler { namespace gig { Line 342  namespace LinuxSampler { namespace gig {
342          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
343    
344          // (re)allocate synthesis parameter matrix          // (re)allocate synthesis parameter matrix
345          if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];          if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
346          pSynthesisParameters[0] = new float[Event::destination_count * pAudioOut->MaxSamplesPerCycle()];          pSynthesisParameters[0] = (float *) memalign(16,(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle()));
347          for (int dst = 1; dst < Event::destination_count; dst++)          for (int dst = 1; dst < Event::destination_count; dst++)
348              pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();              pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();
349    
# Line 339  namespace LinuxSampler { namespace gig { Line 357  namespace LinuxSampler { namespace gig {
357          pDiskThread->StartThread();          pDiskThread->StartThread();
358          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
359    
360          for (Voice* pVoice = pVoicePool->first(); pVoice; pVoice = pVoicePool->next()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
361              if (!pVoice->pDiskThread) {              if (!iterVoice->pDiskThread) {
362                  dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));                  dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));
363                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
364              }              }
# Line 381  namespace LinuxSampler { namespace gig { Line 399  namespace LinuxSampler { namespace gig {
399          }          }
400    
401    
402            // update time of start and end of this audio fragment (as events' time stamps relate to this)
403            pEventGenerator->UpdateFragmentTime(Samples);
404    
405    
406          // empty the event lists for the new fragment          // empty the event lists for the new fragment
407          pEvents->clear();          pEvents->clear();
408          pCCEvents->clear();          pCCEvents->clear();
409          for (uint i = 0; i < Event::destination_count; i++) {          for (uint i = 0; i < Event::destination_count; i++) {
410              pSynthesisEvents[i]->clear();              pSynthesisEvents[i]->clear();
411          }          }
412            {
413          // read and copy events from input queue              RTList<uint>::Iterator iuiKey = pActiveKeys->first();
414          Event event = pEventGenerator->CreateEvent();              RTList<uint>::Iterator end    = pActiveKeys->end();
415          while (true) {              for(; iuiKey != end; ++iuiKey) {
416              if (!pEventQueue->pop(&event)) break;                  pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key
417              pEvents->alloc_assign(event);              }
418          }          }
419    
420    
421          // 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
422          pEventGenerator->UpdateFragmentTime(Samples);          {
423                RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
424                Event* pEvent;
425                while (true) {
426                    // get next event from input event queue
427                    if (!(pEvent = eventQueueReader.pop())) break;
428                    // if younger event reached, ignore that and all subsequent ones for now
429                    if (pEvent->FragmentPos() >= Samples) {
430                        eventQueueReader--;
431                        dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
432                        pEvent->ResetFragmentPos();
433                        break;
434                    }
435                    // copy event to internal event list
436                    if (pEvents->poolIsEmpty()) {
437                        dmsg(1,("Event pool emtpy!\n"));
438                        break;
439                    }
440                    *pEvents->allocAppend() = *pEvent;
441                }
442                eventQueueReader.free(); // free all copied events from input queue
443            }
444    
445    
446          // process events          // process events
447          Event* pNextEvent = pEvents->first();          {
448          while (pNextEvent) {              RTList<Event>::Iterator itEvent = pEvents->first();
449              Event* pEvent = pNextEvent;              RTList<Event>::Iterator end     = pEvents->end();
450              pEvents->set_current(pEvent);              for (; itEvent != end; ++itEvent) {
451              pNextEvent = pEvents->next();                  switch (itEvent->Type) {
452              switch (pEvent->Type) {                      case Event::type_note_on:
453                  case Event::type_note_on:                          dmsg(5,("Engine: Note on received\n"));
454                      dmsg(5,("Audio Thread: Note on received\n"));                          ProcessNoteOn(itEvent);
455                      ProcessNoteOn(pEvent);                          break;
456                      break;                      case Event::type_note_off:
457                  case Event::type_note_off:                          dmsg(5,("Engine: Note off received\n"));
458                      dmsg(5,("Audio Thread: Note off received\n"));                          ProcessNoteOff(itEvent);
459                      ProcessNoteOff(pEvent);                          break;
460                      break;                      case Event::type_control_change:
461                  case Event::type_control_change:                          dmsg(5,("Engine: MIDI CC received\n"));
462                      dmsg(5,("Audio Thread: MIDI CC received\n"));                          ProcessControlChange(itEvent);
463                      ProcessControlChange(pEvent);                          break;
464                      break;                      case Event::type_pitchbend:
465                  case Event::type_pitchbend:                          dmsg(5,("Engine: Pitchbend received\n"));
466                      dmsg(5,("Audio Thread: Pitchbend received\n"));                          ProcessPitchbend(itEvent);
467                      ProcessPitchbend(pEvent);                          break;
468                      break;                      case Event::type_sysex:
469                            dmsg(5,("Engine: Sysex received\n"));
470                            ProcessSysex(itEvent);
471                            break;
472                    }
473              }              }
474          }          }
475    
476    
         // render audio from all active voices  
477          int active_voices = 0;          int active_voices = 0;
478          uint* piKey = pActiveKeys->first();  
479          while (piKey) { // iterate through all active keys          // render audio from all active voices
480              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];          {
481              pActiveKeys->set_current(piKey);              RTList<uint>::Iterator iuiKey = pActiveKeys->first();
482              piKey = pActiveKeys->next();              RTList<uint>::Iterator end    = pActiveKeys->end();
483                while (iuiKey != end) { // iterate through all active keys
484              Voice* pVoiceNext = pKey->pActiveVoices->first();                  midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
485              while (pVoiceNext) { // iterate through all voices on this key                  ++iuiKey;
486                  // already get next voice on key  
487                  Voice* pVoice = pVoiceNext;                  RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
488                  pKey->pActiveVoices->set_current(pVoice);                  RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
489                  pVoiceNext = pKey->pActiveVoices->next();                  for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
490                        // now render current voice
491                  // now render current voice                      itVoice->Render(Samples);
492                  pVoice->Render(Samples);                      if (itVoice->IsActive()) active_voices++; // still active
493                  if (pVoice->IsActive()) active_voices++; // still active                      else { // voice reached end, is now inactive
494                  else { // voice reached end, is now inactive                          FreeVoice(itVoice); // remove voice from the list of active voices
495                      KillVoiceImmediately(pVoice); // remove voice from the list of active voices                      }
496                    }
497                }
498            }
499    
500    
501            // now render all postponed voices from voice stealing
502            {
503                RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();
504                RTList<Event>::Iterator end               = pVoiceStealingQueue->end();
505                for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
506                    Pool<Voice>::Iterator itNewVoice = LaunchVoice(itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false);
507                    if (itNewVoice) {
508                        for (; itNewVoice; itNewVoice = itNewVoice->itChildVoice) {
509                            itNewVoice->Render(Samples);
510                            if (itNewVoice->IsActive()) active_voices++; // still active
511                            else { // voice reached end, is now inactive
512                                FreeVoice(itNewVoice); // remove voice from the list of active voices
513                            }
514                        }
515                  }                  }
516                    else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));
517                }
518            }
519            // reset voice stealing for the new fragment
520            pVoiceStealingQueue->clear();
521            itLastStolenVoice = RTList<Voice>::Iterator();
522            iuiLastStolenKey  = RTList<uint>::Iterator();
523    
524    
525            // free all keys which have no active voices left
526            {
527                RTList<uint>::Iterator iuiKey = pActiveKeys->first();
528                RTList<uint>::Iterator end    = pActiveKeys->end();
529                while (iuiKey != end) { // iterate through all active keys
530                    midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
531                    ++iuiKey;
532                    if (pKey->pActiveVoices->isEmpty()) FreeKey(pKey);
533                    #if DEVMODE
534                    else { // FIXME: should be removed before the final release (purpose: just a sanity check for debugging)
535                        RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
536                        RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
537                        for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
538                            if (itVoice->itKillEvent) {
539                                dmsg(1,("gig::Engine: ERROR, killed voice survived !!!\n"));
540                            }
541                        }
542                    }
543                    #endif // DEVMODE
544              }              }
             pKey->pEvents->clear(); // free all events on the key  
545          }          }
546    
547    
# Line 470  namespace LinuxSampler { namespace gig { Line 562  namespace LinuxSampler { namespace gig {
562       *  @param Velocity - MIDI velocity value of the triggered key       *  @param Velocity - MIDI velocity value of the triggered key
563       */       */
564      void Engine::SendNoteOn(uint8_t Key, uint8_t Velocity) {      void Engine::SendNoteOn(uint8_t Key, uint8_t Velocity) {
565          Event event    = pEventGenerator->CreateEvent();          Event event               = pEventGenerator->CreateEvent();
566          event.Type     = Event::type_note_on;          event.Type                = Event::type_note_on;
567          event.Key      = Key;          event.Param.Note.Key      = Key;
568          event.Velocity = Velocity;          event.Param.Note.Velocity = Velocity;
569          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
570          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
571      }      }
# Line 486  namespace LinuxSampler { namespace gig { Line 578  namespace LinuxSampler { namespace gig {
578       *  @param Velocity - MIDI release velocity value of the released key       *  @param Velocity - MIDI release velocity value of the released key
579       */       */
580      void Engine::SendNoteOff(uint8_t Key, uint8_t Velocity) {      void Engine::SendNoteOff(uint8_t Key, uint8_t Velocity) {
581          Event event    = pEventGenerator->CreateEvent();          Event event               = pEventGenerator->CreateEvent();
582          event.Type     = Event::type_note_off;          event.Type                = Event::type_note_off;
583          event.Key      = Key;          event.Param.Note.Key      = Key;
584          event.Velocity = Velocity;          event.Param.Note.Velocity = Velocity;
585          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
586          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
587      }      }
# Line 501  namespace LinuxSampler { namespace gig { Line 593  namespace LinuxSampler { namespace gig {
593       *  @param Pitch - MIDI pitch value (-8192 ... +8191)       *  @param Pitch - MIDI pitch value (-8192 ... +8191)
594       */       */
595      void Engine::SendPitchbend(int Pitch) {      void Engine::SendPitchbend(int Pitch) {
596          Event event = pEventGenerator->CreateEvent();          Event event             = pEventGenerator->CreateEvent();
597          event.Type  = Event::type_pitchbend;          event.Type              = Event::type_pitchbend;
598          event.Pitch = Pitch;          event.Param.Pitch.Pitch = Pitch;
599          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
600          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
601      }      }
# Line 516  namespace LinuxSampler { namespace gig { Line 608  namespace LinuxSampler { namespace gig {
608       *  @param Value      - value of the control change       *  @param Value      - value of the control change
609       */       */
610      void Engine::SendControlChange(uint8_t Controller, uint8_t Value) {      void Engine::SendControlChange(uint8_t Controller, uint8_t Value) {
611          Event event      = pEventGenerator->CreateEvent();          Event event               = pEventGenerator->CreateEvent();
612          event.Type       = Event::type_control_change;          event.Type                = Event::type_control_change;
613          event.Controller = Controller;          event.Param.CC.Controller = Controller;
614          event.Value      = Value;          event.Param.CC.Value      = Value;
615          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
616          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
617      }      }
618    
619      /**      /**
620         *  Will be called by the MIDI input device whenever a MIDI system
621         *  exclusive message has arrived.
622         *
623         *  @param pData - pointer to sysex data
624         *  @param Size  - lenght of sysex data (in bytes)
625         */
626        void Engine::SendSysex(void* pData, uint Size) {
627            Event event             = pEventGenerator->CreateEvent();
628            event.Type              = Event::type_sysex;
629            event.Param.Sysex.Size  = Size;
630            if (pEventQueue->write_space() > 0) {
631                if (pSysexBuffer->write_space() >= Size) {
632                    // copy sysex data to input buffer
633                    uint toWrite = Size;
634                    uint8_t* pPos = (uint8_t*) pData;
635                    while (toWrite) {
636                        const uint writeNow = RTMath::Min(toWrite, pSysexBuffer->write_space_to_end());
637                        pSysexBuffer->write(pPos, writeNow);
638                        toWrite -= writeNow;
639                        pPos    += writeNow;
640    
641                    }
642                    // finally place sysex event into input event queue
643                    pEventQueue->push(&event);
644                }
645                else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,SYSEX_BUFFER_SIZE));
646            }
647            else dmsg(1,("Engine: Input event queue full!"));
648        }
649    
650        /**
651       *  Assigns and triggers a new voice for the respective MIDI key.       *  Assigns and triggers a new voice for the respective MIDI key.
652       *       *
653       *  @param pNoteOnEvent - key, velocity and time stamp of the event       *  @param itNoteOnEvent - key, velocity and time stamp of the event
654       */       */
655      void Engine::ProcessNoteOn(Event* pNoteOnEvent) {      void Engine::ProcessNoteOn(Pool<Event>::Iterator& itNoteOnEvent) {
656          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Key];          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
657    
658          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
659    
660          // cancel release process of voices on this key if needed          // cancel release process of voices on this key if needed
661          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !SustainPedal) {
662              Event* pCancelReleaseEvent = pKey->pEvents->alloc();              RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
663              if (pCancelReleaseEvent) {              if (itCancelReleaseEvent) {
664                  *pCancelReleaseEvent = *pNoteOnEvent;                  *itCancelReleaseEvent = *itNoteOnEvent;                  // copy event
665                  pCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type                  itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type
666              }              }
667              else dmsg(1,("Event pool emtpy!\n"));              else dmsg(1,("Event pool emtpy!\n"));
668          }          }
669    
670          // allocate and trigger a new voice for the key          // move note on event to the key's own event list
671          LaunchVoice(pNoteOnEvent);          RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
672    
673          // finally move note on event to the key's own event list          // allocate and trigger a new voice for the key
674          pEvents->move(pNoteOnEvent, pKey->pEvents);          LaunchVoice(itNoteOnEventOnKeyList, 0, false, true);
675      }      }
676    
677      /**      /**
# Line 557  namespace LinuxSampler { namespace gig { Line 680  namespace LinuxSampler { namespace gig {
680       *  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.
681       *  due to completion of sample playback).       *  due to completion of sample playback).
682       *       *
683       *  @param pNoteOffEvent - key, velocity and time stamp of the event       *  @param itNoteOffEvent - key, velocity and time stamp of the event
684       */       */
685      void Engine::ProcessNoteOff(Event* pNoteOffEvent) {      void Engine::ProcessNoteOff(Pool<Event>::Iterator& itNoteOffEvent) {
686          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOffEvent->Key];          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];
687    
688          pKey->KeyPressed = false; // the MIDI key was now released          pKey->KeyPressed = false; // the MIDI key was now released
689    
690          // release voices on this key if needed          // release voices on this key if needed
691          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !SustainPedal) {
692              pNoteOffEvent->Type = Event::type_release; // transform event type              itNoteOffEvent->Type = Event::type_release; // transform event type
693          }          }
694    
695            // move event to the key's own event list
696            RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
697    
698          // spawn release triggered voice(s) if needed          // spawn release triggered voice(s) if needed
699          if (pKey->ReleaseTrigger) {          if (pKey->ReleaseTrigger) {
700              LaunchVoice(pNoteOffEvent, 0, true);              LaunchVoice(itNoteOffEventOnKeyList, 0, true, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
701              pKey->ReleaseTrigger = false;              pKey->ReleaseTrigger = false;
702          }          }
   
         // move event to the key's own event list  
         pEvents->move(pNoteOffEvent, pKey->pEvents);  
703      }      }
704    
705      /**      /**
706       *  Moves pitchbend event from the general (input) event list to the pitch       *  Moves pitchbend event from the general (input) event list to the pitch
707       *  event list.       *  event list.
708       *       *
709       *  @param pPitchbendEvent - absolute pitch value and time stamp of the event       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event
710       */       */
711      void Engine::ProcessPitchbend(Event* pPitchbendEvent) {      void Engine::ProcessPitchbend(Pool<Event>::Iterator& itPitchbendEvent) {
712          this->Pitch = pPitchbendEvent->Pitch; // store current pitch value          this->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value
713          pEvents->move(pPitchbendEvent, pSynthesisEvents[Event::destination_vco]);          itPitchbendEvent.moveToEndOf(pSynthesisEvents[Event::destination_vco]);
714      }      }
715    
716      /**      /**
# Line 595  namespace LinuxSampler { namespace gig { Line 718  namespace LinuxSampler { namespace gig {
718       *  called by the ProcessNoteOn() method and by the voices itself       *  called by the ProcessNoteOn() method and by the voices itself
719       *  (e.g. to spawn further voices on the same key for layered sounds).       *  (e.g. to spawn further voices on the same key for layered sounds).
720       *       *
721       *  @param pNoteOnEvent        - key, velocity and time stamp of the event       *  @param itNoteOnEvent       - key, velocity and time stamp of the event
722       *  @param iLayer              - layer index for the new voice (optional - only       *  @param iLayer              - layer index for the new voice (optional - only
723       *                               in case of layered sounds of course)       *                               in case of layered sounds of course)
724       *  @param ReleaseTriggerVoice - if new voice is a release triggered voice       *  @param ReleaseTriggerVoice - if new voice is a release triggered voice
725       *                               (optional, default = false)       *                               (optional, default = false)
726         *  @param VoiceStealing       - if voice stealing should be performed
727         *                               when there is no free voice
728         *                               (optional, default = true)
729         *  @returns pointer to new voice or NULL if there was no free voice or
730         *           if an error occured while trying to trigger the new voice
731       */       */
732      void Engine::LaunchVoice(Event* pNoteOnEvent, int iLayer, bool ReleaseTriggerVoice) {      Pool<Voice>::Iterator Engine::LaunchVoice(Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing) {
733          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Key];          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
734    
735          // allocate a new voice for the key          // allocate a new voice for the key
736          Voice* pNewVoice = pKey->pActiveVoices->alloc();          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
737          if (pNewVoice) {          if (itNewVoice) {
738              // launch the new voice              // launch the new voice
739              if (pNewVoice->Trigger(pNoteOnEvent, this->Pitch, this->pInstrument, iLayer, ReleaseTriggerVoice) < 0) {              if (itNewVoice->Trigger(itNoteOnEvent, this->Pitch, this->pInstrument, iLayer, ReleaseTriggerVoice, VoiceStealing) < 0) {
740                  dmsg(1,("Triggering new voice failed!\n"));                  dmsg(1,("Triggering new voice failed!\n"));
741                  pKey->pActiveVoices->free(pNewVoice);                  pKey->pActiveVoices->free(itNewVoice);
742              }              }
743              else { // on success              else { // on success
744                  uint** ppKeyGroup = NULL;                  uint** ppKeyGroup = NULL;
745                  if (pNewVoice->KeyGroup) { // if this voice / key belongs to a key group                  if (itNewVoice->KeyGroup) { // if this voice / key belongs to a key group
746                      ppKeyGroup = &ActiveKeyGroups[pNewVoice->KeyGroup];                      ppKeyGroup = &ActiveKeyGroups[itNewVoice->KeyGroup];
747                      if (*ppKeyGroup) { // if there's already an active key in that key group                      if (*ppKeyGroup) { // if there's already an active key in that key group
748                          midi_key_info_t* pOtherKey = &pMIDIKeyInfo[**ppKeyGroup];                          midi_key_info_t* pOtherKey = &pMIDIKeyInfo[**ppKeyGroup];
749                          // kill all voices on the (other) key                          // kill all voices on the (other) key
750                          Voice* pVoiceToBeKilled = pOtherKey->pActiveVoices->first();                          RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
751                          while (pVoiceToBeKilled) {                          RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
752                              Voice* pVoiceToBeKilledNext = pOtherKey->pActiveVoices->next();                          for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
753                              if (pVoiceToBeKilled->Type != Voice::type_release_trigger) pVoiceToBeKilled->Kill(pNoteOnEvent);                              if (itVoiceToBeKilled->Type != Voice::type_release_trigger) itVoiceToBeKilled->Kill(itNoteOnEvent);
                             pOtherKey->pActiveVoices->set_current(pVoiceToBeKilled);  
                             pVoiceToBeKilled = pVoiceToBeKilledNext;  
754                          }                          }
755                      }                      }
756                  }                  }
757                  if (!pKey->Active) { // mark as active key                  if (!pKey->Active) { // mark as active key
758                      pKey->Active = true;                      pKey->Active = true;
759                      pKey->pSelf  = pActiveKeys->alloc();                      pKey->itSelf = pActiveKeys->allocAppend();
760                      *pKey->pSelf = pNoteOnEvent->Key;                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
761                    }
762                    if (itNewVoice->KeyGroup) {
763                        *ppKeyGroup = &*pKey->itSelf; // put key as the (new) active key to its key group
764                    }
765                    if (itNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)
766                    return itNewVoice; // success
767                }
768            }
769            else if (VoiceStealing) {
770                // first, get total amount of required voices (dependant on amount of layers)
771                ::gig::Region* pRegion = pInstrument->GetRegion(itNoteOnEvent->Param.Note.Key);
772                if (!pRegion) return Pool<Voice>::Iterator(); // nothing defined for this MIDI key, so no voice needed
773                int voicesRequired = pRegion->Layers;
774    
775                // now steal the (remaining) amount of voices
776                for (int i = iLayer; i < voicesRequired; i++)
777                    StealVoice(itNoteOnEvent);
778    
779                // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died
780                RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();
781                if (itStealEvent) {
782                    *itStealEvent = *itNoteOnEvent; // copy event
783                    itStealEvent->Param.Note.Layer = iLayer;
784                    itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;
785                }
786                else dmsg(1,("Voice stealing queue full!\n"));
787            }
788    
789            return Pool<Voice>::Iterator(); // no free voice or error
790        }
791    
792        /**
793         *  Will be called by LaunchVoice() method in case there are no free
794         *  voices left. This method will select and kill one old voice for
795         *  voice stealing and postpone the note-on event until the selected
796         *  voice actually died.
797         *
798         *  @param itNoteOnEvent - key, velocity and time stamp of the event
799         */
800        void Engine::StealVoice(Pool<Event>::Iterator& itNoteOnEvent) {
801            if (!pEventPool->poolIsEmpty()) {
802    
803                RTList<uint>::Iterator  iuiOldestKey;
804                RTList<Voice>::Iterator itOldestVoice;
805    
806                // Select one voice for voice stealing
807                switch (VOICE_STEAL_ALGORITHM) {
808    
809                    // try to pick the oldest voice on the key where the new
810                    // voice should be spawned, if there is no voice on that
811                    // key, or no voice left to kill there, then procceed with
812                    // 'oldestkey' algorithm
813                    case voice_steal_algo_keymask: {
814                        midi_key_info_t* pOldestKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
815                        if (itLastStolenVoice) {
816                            itOldestVoice = itLastStolenVoice;
817                            ++itOldestVoice;
818                        }
819                        else { // no voice stolen in this audio fragment cycle yet
820                            itOldestVoice = pOldestKey->pActiveVoices->first();
821                        }
822                        if (itOldestVoice) {
823                            iuiOldestKey = pOldestKey->itSelf;
824                            break; // selection succeeded
825                        }
826                    } // no break - intentional !
827    
828                    // try to pick the oldest voice on the oldest active key
829                    // (caution: must stay after 'keymask' algorithm !)
830                    case voice_steal_algo_oldestkey: {
831                        if (itLastStolenVoice) {
832                            midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiLastStolenKey];
833                            itOldestVoice = itLastStolenVoice;
834                            ++itOldestVoice;
835                            if (!itOldestVoice) {
836                                iuiOldestKey = iuiLastStolenKey;
837                                ++iuiOldestKey;
838                                if (iuiOldestKey) {
839                                    midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiOldestKey];
840                                    itOldestVoice = pOldestKey->pActiveVoices->first();
841                                }
842                                else {
843                                    dmsg(1,("gig::Engine: Warning, too less voices, even for voice stealing! - Better recompile with higher MAX_AUDIO_VOICES.\n"));
844                                    return;
845                                }
846                            }
847                            else iuiOldestKey = iuiLastStolenKey;
848                        }
849                        else { // no voice stolen in this audio fragment cycle yet
850                            iuiOldestKey = pActiveKeys->first();
851                            midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiOldestKey];
852                            itOldestVoice = pOldestKey->pActiveVoices->first();
853                        }
854                        break;
855                  }                  }
856                  if (pNewVoice->KeyGroup) {  
857                      *ppKeyGroup = pKey->pSelf; // put key as the (new) active key to its key group                  // don't steal anything
858                    case voice_steal_algo_none:
859                    default: {
860                        dmsg(1,("No free voice (voice stealing disabled)!\n"));
861                        return;
862                  }                  }
                 if (pNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)  
863              }              }
864    
865                //FIXME: can be removed, just a sanity check for debugging
866                if (!itOldestVoice->IsActive()) dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
867    
868                // now kill the selected voice
869                itOldestVoice->Kill(itNoteOnEvent);
870                // remember which voice on which key we stole, so we can simply proceed for the next voice stealing
871                this->itLastStolenVoice = itOldestVoice;
872                this->iuiLastStolenKey = iuiOldestKey;
873          }          }
874          else std::cerr << "No free voice!" << std::endl << std::flush;          else dmsg(1,("Event pool emtpy!\n"));
875      }      }
876    
877      /**      /**
878       *  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.
879       *  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
880       *  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
881         *  just was killed.
882       *       *
883       *  @param pVoice - points to the voice to be killed       *  @param itVoice - points to the voice to be freed
884       */       */
885      void Engine::KillVoiceImmediately(Voice* pVoice) {      void Engine::FreeVoice(Pool<Voice>::Iterator& itVoice) {
886          if (pVoice) {          if (itVoice) {
887              if (pVoice->IsActive()) pVoice->KillImmediately();              midi_key_info_t* pKey = &pMIDIKeyInfo[itVoice->MIDIKey];
888    
889              midi_key_info_t* pKey = &pMIDIKeyInfo[pVoice->MIDIKey];              uint keygroup = itVoice->KeyGroup;
890    
891              // free the voice object              // free the voice object
892              pVoicePool->free(pVoice);              pVoicePool->free(itVoice);
893    
894              // 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
895              if (pKey->pActiveVoices->is_empty()) {              if (pKey->pActiveVoices->isEmpty() && keygroup) {
896                  if (pVoice->KeyGroup) { // if voice / key belongs to a key group                  uint** ppKeyGroup = &ActiveKeyGroups[keygroup];
897                      uint** ppKeyGroup = &ActiveKeyGroups[pVoice->KeyGroup];                  if (*ppKeyGroup == &*pKey->itSelf) *ppKeyGroup = NULL; // remove key from key group
                     if (*ppKeyGroup == pKey->pSelf) *ppKeyGroup = NULL; // remove key from key group  
                 }  
                 pKey->Active = false;  
                 pActiveKeys->free(pKey->pSelf); // remove key from list of active keys  
                 pKey->pSelf = NULL;  
                 pKey->ReleaseTrigger = false;  
                 dmsg(3,("Key has no more voices now\n"));  
898              }              }
899          }          }
900          else std::cerr << "Couldn't release voice! (pVoice == NULL)\n" << std::flush;          else std::cerr << "Couldn't release voice! (!itVoice)\n" << std::flush;
901        }
902    
903        /**
904         *  Called when there's no more voice left on a key, this call will
905         *  update the key info respectively.
906         *
907         *  @param pKey - key which is now inactive
908         */
909        void Engine::FreeKey(midi_key_info_t* pKey) {
910            if (pKey->pActiveVoices->isEmpty()) {
911                pKey->Active = false;
912                pActiveKeys->free(pKey->itSelf); // remove key from list of active keys
913                pKey->itSelf = RTList<uint>::Iterator();
914                pKey->ReleaseTrigger = false;
915                pKey->pEvents->clear();
916                dmsg(3,("Key has no more voices now\n"));
917            }
918            else dmsg(1,("gig::Engine: Oops, tried to free a key which contains voices.\n"));
919      }      }
920    
921      /**      /**
922       *  Reacts on supported control change commands (e.g. pitch bend wheel,       *  Reacts on supported control change commands (e.g. pitch bend wheel,
923       *  modulation wheel, aftertouch).       *  modulation wheel, aftertouch).
924       *       *
925       *  @param pControlChangeEvent - controller, value and time stamp of the event       *  @param itControlChangeEvent - controller, value and time stamp of the event
926       */       */
927      void Engine::ProcessControlChange(Event* pControlChangeEvent) {      void Engine::ProcessControlChange(Pool<Event>::Iterator& itControlChangeEvent) {
928          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));
929    
930          switch (pControlChangeEvent->Controller) {          switch (itControlChangeEvent->Param.CC.Controller) {
931              case 64: {              case 64: {
932                  if (pControlChangeEvent->Value >= 64 && !SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value >= 64 && !SustainPedal) {
933                      dmsg(4,("PEDAL DOWN\n"));                      dmsg(4,("PEDAL DOWN\n"));
934                      SustainPedal = true;                      SustainPedal = true;
935    
936                      // cancel release process of voices if necessary                      // cancel release process of voices if necessary
937                      uint* piKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pActiveKeys->first();
938                      if (piKey) {                      if (iuiKey) {
939                          pControlChangeEvent->Type = Event::type_cancel_release; // transform event type                          itControlChangeEvent->Type = Event::type_cancel_release; // transform event type
940                          while (piKey) {                          while (iuiKey) {
941                              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];                              midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
942                              pActiveKeys->set_current(piKey);                              ++iuiKey;
                             piKey = pActiveKeys->next();  
943                              if (!pKey->KeyPressed) {                              if (!pKey->KeyPressed) {
944                                  Event* pNewEvent = pKey->pEvents->alloc();                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
945                                  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
946                                  else dmsg(1,("Event pool emtpy!\n"));                                  else dmsg(1,("Event pool emtpy!\n"));
947                              }                              }
948                          }                          }
949                      }                      }
950                  }                  }
951                  if (pControlChangeEvent->Value < 64 && SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value < 64 && SustainPedal) {
952                      dmsg(4,("PEDAL UP\n"));                      dmsg(4,("PEDAL UP\n"));
953                      SustainPedal = false;                      SustainPedal = false;
954    
955                      // release voices if their respective key is not pressed                      // release voices if their respective key is not pressed
956                      uint* piKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pActiveKeys->first();
957                      if (piKey) {                      if (iuiKey) {
958                          pControlChangeEvent->Type = Event::type_release; // transform event type                          itControlChangeEvent->Type = Event::type_release; // transform event type
959                          while (piKey) {                          while (iuiKey) {
960                              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];                              midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
961                              pActiveKeys->set_current(piKey);                              ++iuiKey;
                             piKey = pActiveKeys->next();  
962                              if (!pKey->KeyPressed) {                              if (!pKey->KeyPressed) {
963                                  Event* pNewEvent = pKey->pEvents->alloc();                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
964                                  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
965                                  else dmsg(1,("Event pool emtpy!\n"));                                  else dmsg(1,("Event pool emtpy!\n"));
966                              }                              }
967                          }                          }
# Line 730  namespace LinuxSampler { namespace gig { Line 972  namespace LinuxSampler { namespace gig {
972          }          }
973    
974          // update controller value in the engine's controller table          // update controller value in the engine's controller table
975          ControllerTable[pControlChangeEvent->Controller] = pControlChangeEvent->Value;          ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
976    
977          // 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
978          pEvents->move(pControlChangeEvent, pCCEvents);          itControlChangeEvent.moveToEndOf(pCCEvents);
979        }
980    
981        /**
982         *  Reacts on MIDI system exclusive messages.
983         *
984         *  @param itSysexEvent - sysex data size and time stamp of the sysex event
985         */
986        void Engine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) {
987            RingBuffer<uint8_t>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();
988    
989            uint8_t exclusive_status, id;
990            if (!reader.pop(&exclusive_status)) goto free_sysex_data;
991            if (!reader.pop(&id))               goto free_sysex_data;
992            if (exclusive_status != 0xF0)       goto free_sysex_data;
993    
994            switch (id) {
995                case 0x41: { // Roland
996                    uint8_t device_id, model_id, cmd_id;
997                    if (!reader.pop(&device_id)) goto free_sysex_data;
998                    if (!reader.pop(&model_id))  goto free_sysex_data;
999                    if (!reader.pop(&cmd_id))    goto free_sysex_data;
1000                    if (model_id != 0x42 /*GS*/) goto free_sysex_data;
1001                    if (cmd_id != 0x12 /*DT1*/)  goto free_sysex_data;
1002    
1003                    // command address
1004                    uint8_t addr[3]; // 2 byte addr MSB, followed by 1 byte addr LSB)
1005                    const RingBuffer<uint8_t>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later
1006                    if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;
1007                    if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters
1008                    }
1009                    else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters
1010                    }
1011                    else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)
1012                        switch (addr[3]) {
1013                            case 0x40: { // scale tuning
1014                                uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave
1015                                if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;
1016                                uint8_t checksum;
1017                                if (!reader.pop(&checksum))                      goto free_sysex_data;
1018                                if (GSCheckSum(checksum_reader, 12) != checksum) goto free_sysex_data;
1019                                for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;
1020                                AdjustScale((int8_t*) scale_tunes);
1021                                break;
1022                            }
1023                        }
1024                    }
1025                    else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x20) { // Part Parameters (2)
1026                    }
1027                    else if (addr[0] == 0x41) { // Drum Setup Parameters
1028                    }
1029                    break;
1030                }
1031            }
1032    
1033            free_sysex_data: // finally free sysex data
1034            pSysexBuffer->increment_read_ptr(itSysexEvent->Param.Sysex.Size);
1035        }
1036    
1037        /**
1038         * Calculates the Roland GS sysex check sum.
1039         *
1040         * @param AddrReader - reader which currently points to the first GS
1041         *                     command address byte of the GS sysex message in
1042         *                     question
1043         * @param DataSize   - size of the GS message data (in bytes)
1044         */
1045        uint8_t Engine::GSCheckSum(const RingBuffer<uint8_t>::NonVolatileReader AddrReader, uint DataSize) {
1046            RingBuffer<uint8_t>::NonVolatileReader reader = AddrReader;
1047            uint bytes = 3 /*addr*/ + DataSize;
1048            uint8_t addr_and_data[bytes];
1049            reader.read(&addr_and_data[0], bytes);
1050            uint8_t sum = 0;
1051            for (uint i = 0; i < bytes; i++) sum += addr_and_data[i];
1052            return 128 - sum % 128;
1053        }
1054    
1055        /**
1056         * Allows to tune each of the twelve semitones of an octave.
1057         *
1058         * @param ScaleTunes - detuning of all twelve semitones (in cents)
1059         */
1060        void Engine::AdjustScale(int8_t ScaleTunes[12]) {
1061            memcpy(&this->ScaleTuning[0], &ScaleTunes[0], 12); //TODO: currently not sample accurate
1062      }      }
1063    
1064      /**      /**
# Line 840  namespace LinuxSampler { namespace gig { Line 1165  namespace LinuxSampler { namespace gig {
1165      }      }
1166    
1167      String Engine::Version() {      String Engine::Version() {
1168          String s = "$Revision: 1.11 $";          String s = "$Revision: 1.19 $";
1169          return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword          return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword
1170      }      }
1171    

Legend:
Removed from v.242  
changed lines
  Added in v.319

  ViewVC Help
Powered by ViewVC