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

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

  ViewVC Help
Powered by ViewVC