/[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 246 by schoenebeck, Sun Sep 19 14:12:55 2004 UTC revision 351 by schoenebeck, Tue Jan 25 22:11:43 2005 UTC
# Line 23  Line 23 
23  #include <sstream>  #include <sstream>
24  #include "DiskThread.h"  #include "DiskThread.h"
25  #include "Voice.h"  #include "Voice.h"
26    #include "EGADSR.h"
27    
28  #include "Engine.h"  #include "Engine.h"
29    #include <malloc.h>
30    
31  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
32    
# Line 39  namespace LinuxSampler { namespace gig { Line 41  namespace LinuxSampler { namespace gig {
41          pEventGenerator    = NULL;          pEventGenerator    = NULL;
42          pSysexBuffer       = new RingBuffer<uint8_t>(SYSEX_BUFFER_SIZE, 0);          pSysexBuffer       = new RingBuffer<uint8_t>(SYSEX_BUFFER_SIZE, 0);
43          pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT, 0);          pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT, 0);
44          pEventPool         = new RTELMemoryPool<Event>(MAX_EVENTS_PER_FRAGMENT);          pEventPool         = new Pool<Event>(MAX_EVENTS_PER_FRAGMENT);
45          pVoicePool         = new RTELMemoryPool<Voice>(MAX_AUDIO_VOICES);          pVoicePool         = new Pool<Voice>(MAX_AUDIO_VOICES);
46          pActiveKeys        = new RTELMemoryPool<uint>(128);          pActiveKeys        = new Pool<uint>(128);
47          pEvents            = new RTEList<Event>(pEventPool);          pVoiceStealingQueue = new RTList<Event>(pEventPool);
48          pCCEvents          = new RTEList<Event>(pEventPool);          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 75  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 87  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;          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 157  namespace LinuxSampler { namespace gig { Line 167  namespace LinuxSampler { namespace gig {
167          ActiveVoiceCountMax = 0;          ActiveVoiceCountMax = 0;
168          GlobalVolume        = 1.0;          GlobalVolume        = 1.0;
169    
170            // reset voice stealing parameters
171            itLastStolenVoice = RTList<Voice>::Iterator();
172            iuiLastStolenKey  = RTList<uint>::Iterator();
173            pVoiceStealingQueue->clear();
174    
175          // reset to normal chromatic scale (means equal temper)          // reset to normal chromatic scale (means equal temper)
176          memset(&ScaleTuning[0], 0x00, 12);          memset(&ScaleTuning[0], 0x00, 12);
177    
# Line 170  namespace LinuxSampler { namespace gig { Line 185  namespace LinuxSampler { namespace gig {
185              pMIDIKeyInfo[i].KeyPressed     = false;              pMIDIKeyInfo[i].KeyPressed     = false;
186              pMIDIKeyInfo[i].Active         = false;              pMIDIKeyInfo[i].Active         = false;
187              pMIDIKeyInfo[i].ReleaseTrigger = false;              pMIDIKeyInfo[i].ReleaseTrigger = false;
188              pMIDIKeyInfo[i].pSelf          = NULL;              pMIDIKeyInfo[i].itSelf         = Pool<uint>::Iterator();
189          }          }
190    
191          // reset all key groups          // reset all key groups
# Line 178  namespace LinuxSampler { namespace gig { Line 193  namespace LinuxSampler { namespace gig {
193          for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;          for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;
194    
195          // reset all voices          // reset all voices
196          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
197              pVoice->Reset();              iterVoice->Reset();
198          }          }
199          pVoicePool->clear();          pVoicePool->clear();
200    
# Line 307  namespace LinuxSampler { namespace gig { Line 322  namespace LinuxSampler { namespace gig {
322          this->MaxSamplesPerCycle      = pAudioOutputDevice->MaxSamplesPerCycle();          this->MaxSamplesPerCycle      = pAudioOutputDevice->MaxSamplesPerCycle();
323          this->SampleRate              = pAudioOutputDevice->SampleRate();          this->SampleRate              = pAudioOutputDevice->SampleRate();
324    
325            // FIXME: audio drivers with varying fragment sizes might be a problem here
326            MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * EG_MIN_RELEASE_TIME) - 1;
327            if (MaxFadeOutPos < 0)
328                throw LinuxSamplerException("EG_MIN_RELEASE_TIME in EGADSR.h to big for current audio fragment size / sampling rate!");
329    
330          // (re)create disk thread          // (re)create disk thread
331          if (this->pDiskThread) {          if (this->pDiskThread) {
332                dmsg(1,("Stopping disk thread..."));
333              this->pDiskThread->StopThread();              this->pDiskThread->StopThread();
334              delete this->pDiskThread;              delete this->pDiskThread;
335                dmsg(1,("OK\n"));
336          }          }
337          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo
338          if (!pDiskThread) {          if (!pDiskThread) {
# Line 318  namespace LinuxSampler { namespace gig { Line 340  namespace LinuxSampler { namespace gig {
340              exit(EXIT_FAILURE);              exit(EXIT_FAILURE);
341          }          }
342    
343          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
344              pVoice->pDiskThread = this->pDiskThread;              iterVoice->pDiskThread = this->pDiskThread;
345              dmsg(3,("d"));              dmsg(3,("d"));
346          }          }
347          pVoicePool->clear();          pVoicePool->clear();
# Line 329  namespace LinuxSampler { namespace gig { Line 351  namespace LinuxSampler { namespace gig {
351          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
352    
353          // (re)allocate synthesis parameter matrix          // (re)allocate synthesis parameter matrix
354          if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];          if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
355          pSynthesisParameters[0] = new float[Event::destination_count * pAudioOut->MaxSamplesPerCycle()];          pSynthesisParameters[0] = (float *) memalign(16,(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle()));
356          for (int dst = 1; dst < Event::destination_count; dst++)          for (int dst = 1; dst < Event::destination_count; dst++)
357              pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();              pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();
358    
# Line 344  namespace LinuxSampler { namespace gig { Line 366  namespace LinuxSampler { namespace gig {
366          pDiskThread->StartThread();          pDiskThread->StartThread();
367          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
368    
369          for (Voice* pVoice = pVoicePool->first(); pVoice; pVoice = pVoicePool->next()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
370              if (!pVoice->pDiskThread) {              if (!iterVoice->pDiskThread) {
371                  dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));                  dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));
372                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
373              }              }
# Line 386  namespace LinuxSampler { namespace gig { Line 408  namespace LinuxSampler { namespace gig {
408          }          }
409    
410    
411            // update time of start and end of this audio fragment (as events' time stamps relate to this)
412            pEventGenerator->UpdateFragmentTime(Samples);
413    
414    
415          // empty the event lists for the new fragment          // empty the event lists for the new fragment
416          pEvents->clear();          pEvents->clear();
417          pCCEvents->clear();          pCCEvents->clear();
418          for (uint i = 0; i < Event::destination_count; i++) {          for (uint i = 0; i < Event::destination_count; i++) {
419              pSynthesisEvents[i]->clear();              pSynthesisEvents[i]->clear();
420          }          }
421            {
422          // read and copy events from input queue              RTList<uint>::Iterator iuiKey = pActiveKeys->first();
423          Event event = pEventGenerator->CreateEvent();              RTList<uint>::Iterator end    = pActiveKeys->end();
424          while (true) {              for(; iuiKey != end; ++iuiKey) {
425              if (!pEventQueue->pop(&event)) break;                  pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key
426              pEvents->alloc_assign(event);              }
427          }          }
428    
429    
430          // update time of start and end of this audio fragment (as events' time stamps relate to this)          // get all events from the input event queue which belong to the current fragment
431          pEventGenerator->UpdateFragmentTime(Samples);          {
432                RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
433                Event* pEvent;
434                while (true) {
435                    // get next event from input event queue
436                    if (!(pEvent = eventQueueReader.pop())) break;
437                    // if younger event reached, ignore that and all subsequent ones for now
438                    if (pEvent->FragmentPos() >= Samples) {
439                        eventQueueReader--;
440                        dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
441                        pEvent->ResetFragmentPos();
442                        break;
443                    }
444                    // copy event to internal event list
445                    if (pEvents->poolIsEmpty()) {
446                        dmsg(1,("Event pool emtpy!\n"));
447                        break;
448                    }
449                    *pEvents->allocAppend() = *pEvent;
450                }
451                eventQueueReader.free(); // free all copied events from input queue
452            }
453    
454    
455          // process events          // process events
456          Event* pNextEvent = pEvents->first();          {
457          while (pNextEvent) {              RTList<Event>::Iterator itEvent = pEvents->first();
458              Event* pEvent = pNextEvent;              RTList<Event>::Iterator end     = pEvents->end();
459              pEvents->set_current(pEvent);              for (; itEvent != end; ++itEvent) {
460              pNextEvent = pEvents->next();                  switch (itEvent->Type) {
461              switch (pEvent->Type) {                      case Event::type_note_on:
462                  case Event::type_note_on:                          dmsg(5,("Engine: Note on received\n"));
463                      dmsg(5,("Engine: Note on received\n"));                          ProcessNoteOn(itEvent);
464                      ProcessNoteOn(pEvent);                          break;
465                      break;                      case Event::type_note_off:
466                  case Event::type_note_off:                          dmsg(5,("Engine: Note off received\n"));
467                      dmsg(5,("Engine: Note off received\n"));                          ProcessNoteOff(itEvent);
468                      ProcessNoteOff(pEvent);                          break;
469                      break;                      case Event::type_control_change:
470                  case Event::type_control_change:                          dmsg(5,("Engine: MIDI CC received\n"));
471                      dmsg(5,("Engine: MIDI CC received\n"));                          ProcessControlChange(itEvent);
472                      ProcessControlChange(pEvent);                          break;
473                      break;                      case Event::type_pitchbend:
474                  case Event::type_pitchbend:                          dmsg(5,("Engine: Pitchbend received\n"));
475                      dmsg(5,("Engine: Pitchbend received\n"));                          ProcessPitchbend(itEvent);
476                      ProcessPitchbend(pEvent);                          break;
477                      break;                      case Event::type_sysex:
478                  case Event::type_sysex:                          dmsg(5,("Engine: Sysex received\n"));
479                      dmsg(5,("Engine: Sysex received\n"));                          ProcessSysex(itEvent);
480                      ProcessSysex(pEvent);                          break;
481                      break;                  }
482              }              }
483          }          }
484    
485    
         // render audio from all active voices  
486          int active_voices = 0;          int active_voices = 0;
487          uint* piKey = pActiveKeys->first();  
488          while (piKey) { // iterate through all active keys          // render audio from all active voices
489              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];          {
490              pActiveKeys->set_current(piKey);              RTList<uint>::Iterator iuiKey = pActiveKeys->first();
491              piKey = pActiveKeys->next();              RTList<uint>::Iterator end    = pActiveKeys->end();
492                while (iuiKey != end) { // iterate through all active keys
493              Voice* pVoiceNext = pKey->pActiveVoices->first();                  midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
494              while (pVoiceNext) { // iterate through all voices on this key                  ++iuiKey;
495                  // already get next voice on key  
496                  Voice* pVoice = pVoiceNext;                  RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
497                  pKey->pActiveVoices->set_current(pVoice);                  RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
498                  pVoiceNext = pKey->pActiveVoices->next();                  for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
499                        // now render current voice
500                  // now render current voice                      itVoice->Render(Samples);
501                  pVoice->Render(Samples);                      if (itVoice->IsActive()) active_voices++; // still active
502                  if (pVoice->IsActive()) active_voices++; // still active                      else { // voice reached end, is now inactive
503                  else { // voice reached end, is now inactive                          FreeVoice(itVoice); // remove voice from the list of active voices
504                      KillVoiceImmediately(pVoice); // remove voice from the list of active voices                      }
505                    }
506                }
507            }
508    
509    
510            // now render all postponed voices from voice stealing
511            {
512                RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();
513                RTList<Event>::Iterator end               = pVoiceStealingQueue->end();
514                for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
515                    Pool<Voice>::Iterator itNewVoice = LaunchVoice(itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false);
516                    if (itNewVoice) {
517                        for (; itNewVoice; itNewVoice = itNewVoice->itChildVoice) {
518                            itNewVoice->Render(Samples);
519                            if (itNewVoice->IsActive()) active_voices++; // still active
520                            else { // voice reached end, is now inactive
521                                FreeVoice(itNewVoice); // remove voice from the list of active voices
522                            }
523                        }
524                    }
525                    else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));
526                }
527            }
528            // reset voice stealing for the new fragment
529            pVoiceStealingQueue->clear();
530            itLastStolenVoice = RTList<Voice>::Iterator();
531            iuiLastStolenKey  = RTList<uint>::Iterator();
532    
533    
534            // free all keys which have no active voices left
535            {
536                RTList<uint>::Iterator iuiKey = pActiveKeys->first();
537                RTList<uint>::Iterator end    = pActiveKeys->end();
538                while (iuiKey != end) { // iterate through all active keys
539                    midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
540                    ++iuiKey;
541                    if (pKey->pActiveVoices->isEmpty()) FreeKey(pKey);
542                    #if DEVMODE
543                    else { // FIXME: should be removed before the final release (purpose: just a sanity check for debugging)
544                        RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
545                        RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
546                        for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
547                            if (itVoice->itKillEvent) {
548                                dmsg(1,("gig::Engine: ERROR, killed voice survived !!!\n"));
549                            }
550                        }
551                  }                  }
552                    #endif // DEVMODE
553              }              }
             pKey->pEvents->clear(); // free all events on the key  
554          }          }
555    
556    
# Line 567  namespace LinuxSampler { namespace gig { Line 659  namespace LinuxSampler { namespace gig {
659      /**      /**
660       *  Assigns and triggers a new voice for the respective MIDI key.       *  Assigns and triggers a new voice for the respective MIDI key.
661       *       *
662       *  @param pNoteOnEvent - key, velocity and time stamp of the event       *  @param itNoteOnEvent - key, velocity and time stamp of the event
663       */       */
664      void Engine::ProcessNoteOn(Event* pNoteOnEvent) {      void Engine::ProcessNoteOn(Pool<Event>::Iterator& itNoteOnEvent) {
665          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Param.Note.Key];          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
666    
667          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
668    
669          // cancel release process of voices on this key if needed          // cancel release process of voices on this key if needed
670          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !SustainPedal) {
671              Event* pCancelReleaseEvent = pKey->pEvents->alloc();              RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
672              if (pCancelReleaseEvent) {              if (itCancelReleaseEvent) {
673                  *pCancelReleaseEvent = *pNoteOnEvent;                  *itCancelReleaseEvent = *itNoteOnEvent;                  // copy event
674                  pCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type                  itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type
675              }              }
676              else dmsg(1,("Event pool emtpy!\n"));              else dmsg(1,("Event pool emtpy!\n"));
677          }          }
678    
679          // allocate and trigger a new voice for the key          // move note on event to the key's own event list
680          LaunchVoice(pNoteOnEvent);          RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
681    
682          // finally move note on event to the key's own event list          // allocate and trigger a new voice for the key
683          pEvents->move(pNoteOnEvent, pKey->pEvents);          LaunchVoice(itNoteOnEventOnKeyList, 0, false, true);
684      }      }
685    
686      /**      /**
# Line 597  namespace LinuxSampler { namespace gig { Line 689  namespace LinuxSampler { namespace gig {
689       *  sustain pedal will be released or voice turned inactive by itself (e.g.       *  sustain pedal will be released or voice turned inactive by itself (e.g.
690       *  due to completion of sample playback).       *  due to completion of sample playback).
691       *       *
692       *  @param pNoteOffEvent - key, velocity and time stamp of the event       *  @param itNoteOffEvent - key, velocity and time stamp of the event
693       */       */
694      void Engine::ProcessNoteOff(Event* pNoteOffEvent) {      void Engine::ProcessNoteOff(Pool<Event>::Iterator& itNoteOffEvent) {
695          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOffEvent->Param.Note.Key];          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];
696    
697          pKey->KeyPressed = false; // the MIDI key was now released          pKey->KeyPressed = false; // the MIDI key was now released
698    
699          // release voices on this key if needed          // release voices on this key if needed
700          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !SustainPedal) {
701              pNoteOffEvent->Type = Event::type_release; // transform event type              itNoteOffEvent->Type = Event::type_release; // transform event type
702          }          }
703    
704            // move event to the key's own event list
705            RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
706    
707          // spawn release triggered voice(s) if needed          // spawn release triggered voice(s) if needed
708          if (pKey->ReleaseTrigger) {          if (pKey->ReleaseTrigger) {
709              LaunchVoice(pNoteOffEvent, 0, true);              LaunchVoice(itNoteOffEventOnKeyList, 0, true, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
710              pKey->ReleaseTrigger = false;              pKey->ReleaseTrigger = false;
711          }          }
   
         // move event to the key's own event list  
         pEvents->move(pNoteOffEvent, pKey->pEvents);  
712      }      }
713    
714      /**      /**
715       *  Moves pitchbend event from the general (input) event list to the pitch       *  Moves pitchbend event from the general (input) event list to the pitch
716       *  event list.       *  event list.
717       *       *
718       *  @param pPitchbendEvent - absolute pitch value and time stamp of the event       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event
719       */       */
720      void Engine::ProcessPitchbend(Event* pPitchbendEvent) {      void Engine::ProcessPitchbend(Pool<Event>::Iterator& itPitchbendEvent) {
721          this->Pitch = pPitchbendEvent->Param.Pitch.Pitch; // store current pitch value          this->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value
722          pEvents->move(pPitchbendEvent, pSynthesisEvents[Event::destination_vco]);          itPitchbendEvent.moveToEndOf(pSynthesisEvents[Event::destination_vco]);
723      }      }
724    
725      /**      /**
# Line 635  namespace LinuxSampler { namespace gig { Line 727  namespace LinuxSampler { namespace gig {
727       *  called by the ProcessNoteOn() method and by the voices itself       *  called by the ProcessNoteOn() method and by the voices itself
728       *  (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).
729       *       *
730       *  @param pNoteOnEvent        - key, velocity and time stamp of the event       *  @param itNoteOnEvent       - key, velocity and time stamp of the event
731       *  @param iLayer              - layer index for the new voice (optional - only       *  @param iLayer              - layer index for the new voice (optional - only
732       *                               in case of layered sounds of course)       *                               in case of layered sounds of course)
733       *  @param ReleaseTriggerVoice - if new voice is a release triggered voice       *  @param ReleaseTriggerVoice - if new voice is a release triggered voice
734       *                               (optional, default = false)       *                               (optional, default = false)
735         *  @param VoiceStealing       - if voice stealing should be performed
736         *                               when there is no free voice
737         *                               (optional, default = true)
738         *  @returns pointer to new voice or NULL if there was no free voice or
739         *           if an error occured while trying to trigger the new voice
740       */       */
741      void Engine::LaunchVoice(Event* pNoteOnEvent, int iLayer, bool ReleaseTriggerVoice) {      Pool<Voice>::Iterator Engine::LaunchVoice(Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing) {
742          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Param.Note.Key];          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
743    
744          // allocate a new voice for the key          // allocate a new voice for the key
745          Voice* pNewVoice = pKey->pActiveVoices->alloc();          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
746          if (pNewVoice) {          if (itNewVoice) {
747              // launch the new voice              // launch the new voice
748              if (pNewVoice->Trigger(pNoteOnEvent, this->Pitch, this->pInstrument, iLayer, ReleaseTriggerVoice) < 0) {              if (itNewVoice->Trigger(itNoteOnEvent, this->Pitch, this->pInstrument, iLayer, ReleaseTriggerVoice, VoiceStealing) < 0) {
749                  dmsg(1,("Triggering new voice failed!\n"));                  dmsg(1,("Triggering new voice failed!\n"));
750                  pKey->pActiveVoices->free(pNewVoice);                  pKey->pActiveVoices->free(itNewVoice);
751              }              }
752              else { // on success              else { // on success
753                  uint** ppKeyGroup = NULL;                  uint** ppKeyGroup = NULL;
754                  if (pNewVoice->KeyGroup) { // if this voice / key belongs to a key group                  if (itNewVoice->KeyGroup) { // if this voice / key belongs to a key group
755                      ppKeyGroup = &ActiveKeyGroups[pNewVoice->KeyGroup];                      ppKeyGroup = &ActiveKeyGroups[itNewVoice->KeyGroup];
756                      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
757                          midi_key_info_t* pOtherKey = &pMIDIKeyInfo[**ppKeyGroup];                          midi_key_info_t* pOtherKey = &pMIDIKeyInfo[**ppKeyGroup];
758                          // kill all voices on the (other) key                          // kill all voices on the (other) key
759                          Voice* pVoiceToBeKilled = pOtherKey->pActiveVoices->first();                          RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
760                          while (pVoiceToBeKilled) {                          RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
761                              Voice* pVoiceToBeKilledNext = pOtherKey->pActiveVoices->next();                          for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
762                              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;  
763                          }                          }
764                      }                      }
765                  }                  }
766                  if (!pKey->Active) { // mark as active key                  if (!pKey->Active) { // mark as active key
767                      pKey->Active = true;                      pKey->Active = true;
768                      pKey->pSelf  = pActiveKeys->alloc();                      pKey->itSelf = pActiveKeys->allocAppend();
769                      *pKey->pSelf = pNoteOnEvent->Param.Note.Key;                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
770                    }
771                    if (itNewVoice->KeyGroup) {
772                        *ppKeyGroup = &*pKey->itSelf; // put key as the (new) active key to its key group
773                    }
774                    if (itNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)
775                    return itNewVoice; // success
776                }
777            }
778            else if (VoiceStealing) {
779                // first, get total amount of required voices (dependant on amount of layers)
780                ::gig::Region* pRegion = pInstrument->GetRegion(itNoteOnEvent->Param.Note.Key);
781                if (!pRegion) return Pool<Voice>::Iterator(); // nothing defined for this MIDI key, so no voice needed
782                int voicesRequired = pRegion->Layers;
783    
784                // now steal the (remaining) amount of voices
785                for (int i = iLayer; i < voicesRequired; i++)
786                    StealVoice(itNoteOnEvent);
787    
788                // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died
789                RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();
790                if (itStealEvent) {
791                    *itStealEvent = *itNoteOnEvent; // copy event
792                    itStealEvent->Param.Note.Layer = iLayer;
793                    itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;
794                }
795                else dmsg(1,("Voice stealing queue full!\n"));
796            }
797    
798            return Pool<Voice>::Iterator(); // no free voice or error
799        }
800    
801        /**
802         *  Will be called by LaunchVoice() method in case there are no free
803         *  voices left. This method will select and kill one old voice for
804         *  voice stealing and postpone the note-on event until the selected
805         *  voice actually died.
806         *
807         *  @param itNoteOnEvent - key, velocity and time stamp of the event
808         */
809        void Engine::StealVoice(Pool<Event>::Iterator& itNoteOnEvent) {
810            if (!pEventPool->poolIsEmpty()) {
811    
812                RTList<uint>::Iterator  iuiOldestKey;
813                RTList<Voice>::Iterator itOldestVoice;
814    
815                // Select one voice for voice stealing
816                switch (VOICE_STEAL_ALGORITHM) {
817    
818                    // try to pick the oldest voice on the key where the new
819                    // voice should be spawned, if there is no voice on that
820                    // key, or no voice left to kill there, then procceed with
821                    // 'oldestkey' algorithm
822                    case voice_steal_algo_keymask: {
823                        midi_key_info_t* pOldestKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
824                        if (itLastStolenVoice) {
825                            itOldestVoice = itLastStolenVoice;
826                            ++itOldestVoice;
827                        }
828                        else { // no voice stolen in this audio fragment cycle yet
829                            itOldestVoice = pOldestKey->pActiveVoices->first();
830                        }
831                        if (itOldestVoice) {
832                            iuiOldestKey = pOldestKey->itSelf;
833                            break; // selection succeeded
834                        }
835                    } // no break - intentional !
836    
837                    // try to pick the oldest voice on the oldest active key
838                    // (caution: must stay after 'keymask' algorithm !)
839                    case voice_steal_algo_oldestkey: {
840                        if (itLastStolenVoice) {
841                            midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiLastStolenKey];
842                            itOldestVoice = itLastStolenVoice;
843                            ++itOldestVoice;
844                            if (!itOldestVoice) {
845                                iuiOldestKey = iuiLastStolenKey;
846                                ++iuiOldestKey;
847                                if (iuiOldestKey) {
848                                    midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiOldestKey];
849                                    itOldestVoice = pOldestKey->pActiveVoices->first();
850                                }
851                                else {
852                                    dmsg(1,("gig::Engine: Warning, too less voices, even for voice stealing! - Better recompile with higher MAX_AUDIO_VOICES.\n"));
853                                    return;
854                                }
855                            }
856                            else iuiOldestKey = iuiLastStolenKey;
857                        }
858                        else { // no voice stolen in this audio fragment cycle yet
859                            iuiOldestKey = pActiveKeys->first();
860                            midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiOldestKey];
861                            itOldestVoice = pOldestKey->pActiveVoices->first();
862                        }
863                        break;
864                  }                  }
865                  if (pNewVoice->KeyGroup) {  
866                      *ppKeyGroup = pKey->pSelf; // put key as the (new) active key to its key group                  // don't steal anything
867                    case voice_steal_algo_none:
868                    default: {
869                        dmsg(1,("No free voice (voice stealing disabled)!\n"));
870                        return;
871                  }                  }
                 if (pNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)  
872              }              }
873    
874                //FIXME: can be removed, just a sanity check for debugging
875                if (!itOldestVoice->IsActive()) dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
876    
877                // now kill the selected voice
878                itOldestVoice->Kill(itNoteOnEvent);
879                // remember which voice on which key we stole, so we can simply proceed for the next voice stealing
880                this->itLastStolenVoice = itOldestVoice;
881                this->iuiLastStolenKey = iuiOldestKey;
882          }          }
883          else std::cerr << "No free voice!" << std::endl << std::flush;          else dmsg(1,("Event pool emtpy!\n"));
884      }      }
885    
886      /**      /**
887       *  Immediately kills the voice given with pVoice (no matter if sustain is       *  Removes the given voice from the MIDI key's list of active voices.
888       *  pressed or not) and removes it from the MIDI key's list of active voice.       *  This method will be called when a voice went inactive, e.g. because
889       *  This method will e.g. be called if a voice went inactive by itself.       *  it finished to playback its sample, finished its release stage or
890         *  just was killed.
891       *       *
892       *  @param pVoice - points to the voice to be killed       *  @param itVoice - points to the voice to be freed
893       */       */
894      void Engine::KillVoiceImmediately(Voice* pVoice) {      void Engine::FreeVoice(Pool<Voice>::Iterator& itVoice) {
895          if (pVoice) {          if (itVoice) {
896              if (pVoice->IsActive()) pVoice->KillImmediately();              midi_key_info_t* pKey = &pMIDIKeyInfo[itVoice->MIDIKey];
897    
898              midi_key_info_t* pKey = &pMIDIKeyInfo[pVoice->MIDIKey];              uint keygroup = itVoice->KeyGroup;
899    
900              // free the voice object              // free the voice object
901              pVoicePool->free(pVoice);              pVoicePool->free(itVoice);
902    
903              // check if there are no voices left on the MIDI key and update the key info if so              // if no other voices left and member of a key group, remove from key group
904              if (pKey->pActiveVoices->is_empty()) {              if (pKey->pActiveVoices->isEmpty() && keygroup) {
905                  if (pVoice->KeyGroup) { // if voice / key belongs to a key group                  uint** ppKeyGroup = &ActiveKeyGroups[keygroup];
906                      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"));  
907              }              }
908          }          }
909          else std::cerr << "Couldn't release voice! (pVoice == NULL)\n" << std::flush;          else std::cerr << "Couldn't release voice! (!itVoice)\n" << std::flush;
910        }
911    
912        /**
913         *  Called when there's no more voice left on a key, this call will
914         *  update the key info respectively.
915         *
916         *  @param pKey - key which is now inactive
917         */
918        void Engine::FreeKey(midi_key_info_t* pKey) {
919            if (pKey->pActiveVoices->isEmpty()) {
920                pKey->Active = false;
921                pActiveKeys->free(pKey->itSelf); // remove key from list of active keys
922                pKey->itSelf = RTList<uint>::Iterator();
923                pKey->ReleaseTrigger = false;
924                pKey->pEvents->clear();
925                dmsg(3,("Key has no more voices now\n"));
926            }
927            else dmsg(1,("gig::Engine: Oops, tried to free a key which contains voices.\n"));
928      }      }
929    
930      /**      /**
931       *  Reacts on supported control change commands (e.g. pitch bend wheel,       *  Reacts on supported control change commands (e.g. pitch bend wheel,
932       *  modulation wheel, aftertouch).       *  modulation wheel, aftertouch).
933       *       *
934       *  @param pControlChangeEvent - controller, value and time stamp of the event       *  @param itControlChangeEvent - controller, value and time stamp of the event
935       */       */
936      void Engine::ProcessControlChange(Event* pControlChangeEvent) {      void Engine::ProcessControlChange(Pool<Event>::Iterator& itControlChangeEvent) {
937          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", pControlChangeEvent->Param.CC.Controller, pControlChangeEvent->Param.CC.Value));          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", itControlChangeEvent->Param.CC.Controller, itControlChangeEvent->Param.CC.Value));
938    
939          switch (pControlChangeEvent->Param.CC.Controller) {          switch (itControlChangeEvent->Param.CC.Controller) {
940              case 64: {              case 64: {
941                  if (pControlChangeEvent->Param.CC.Value >= 64 && !SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value >= 64 && !SustainPedal) {
942                      dmsg(4,("PEDAL DOWN\n"));                      dmsg(4,("PEDAL DOWN\n"));
943                      SustainPedal = true;                      SustainPedal = true;
944    
945                      // cancel release process of voices if necessary                      // cancel release process of voices if necessary
946                      uint* piKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pActiveKeys->first();
947                      if (piKey) {                      if (iuiKey) {
948                          pControlChangeEvent->Type = Event::type_cancel_release; // transform event type                          itControlChangeEvent->Type = Event::type_cancel_release; // transform event type
949                          while (piKey) {                          while (iuiKey) {
950                              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];                              midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
951                              pActiveKeys->set_current(piKey);                              ++iuiKey;
                             piKey = pActiveKeys->next();  
952                              if (!pKey->KeyPressed) {                              if (!pKey->KeyPressed) {
953                                  Event* pNewEvent = pKey->pEvents->alloc();                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
954                                  if (pNewEvent) *pNewEvent = *pControlChangeEvent; // copy event to the key's own event list                                  if (itNewEvent) *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
955                                  else dmsg(1,("Event pool emtpy!\n"));                                  else dmsg(1,("Event pool emtpy!\n"));
956                              }                              }
957                          }                          }
958                      }                      }
959                  }                  }
960                  if (pControlChangeEvent->Param.CC.Value < 64 && SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value < 64 && SustainPedal) {
961                      dmsg(4,("PEDAL UP\n"));                      dmsg(4,("PEDAL UP\n"));
962                      SustainPedal = false;                      SustainPedal = false;
963    
964                      // release voices if their respective key is not pressed                      // release voices if their respective key is not pressed
965                      uint* piKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pActiveKeys->first();
966                      if (piKey) {                      if (iuiKey) {
967                          pControlChangeEvent->Type = Event::type_release; // transform event type                          itControlChangeEvent->Type = Event::type_release; // transform event type
968                          while (piKey) {                          while (iuiKey) {
969                              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];                              midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
970                              pActiveKeys->set_current(piKey);                              ++iuiKey;
                             piKey = pActiveKeys->next();  
971                              if (!pKey->KeyPressed) {                              if (!pKey->KeyPressed) {
972                                  Event* pNewEvent = pKey->pEvents->alloc();                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
973                                  if (pNewEvent) *pNewEvent = *pControlChangeEvent; // copy event to the key's own event list                                  if (itNewEvent) *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
974                                  else dmsg(1,("Event pool emtpy!\n"));                                  else dmsg(1,("Event pool emtpy!\n"));
975                              }                              }
976                          }                          }
# Line 770  namespace LinuxSampler { namespace gig { Line 981  namespace LinuxSampler { namespace gig {
981          }          }
982    
983          // update controller value in the engine's controller table          // update controller value in the engine's controller table
984          ControllerTable[pControlChangeEvent->Param.CC.Controller] = pControlChangeEvent->Param.CC.Value;          ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
985    
986          // move event from the unsorted event list to the control change event list          // move event from the unsorted event list to the control change event list
987          pEvents->move(pControlChangeEvent, pCCEvents);          itControlChangeEvent.moveToEndOf(pCCEvents);
988      }      }
989    
990      /**      /**
991       *  Reacts on MIDI system exclusive messages.       *  Reacts on MIDI system exclusive messages.
992       *       *
993       *  @param pSysexEvent - sysex data size and time stamp of the sysex event       *  @param itSysexEvent - sysex data size and time stamp of the sysex event
994       */       */
995      void Engine::ProcessSysex(Event* pSysexEvent) {      void Engine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) {
996          RingBuffer<uint8_t>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();          RingBuffer<uint8_t>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();
997    
998          uint8_t exclusive_status, id;          uint8_t exclusive_status, id;
# Line 829  namespace LinuxSampler { namespace gig { Line 1040  namespace LinuxSampler { namespace gig {
1040          }          }
1041    
1042          free_sysex_data: // finally free sysex data          free_sysex_data: // finally free sysex data
1043          pSysexBuffer->increment_read_ptr(pSysexEvent->Param.Sysex.Size);          pSysexBuffer->increment_read_ptr(itSysexEvent->Param.Sysex.Size);
1044      }      }
1045    
1046      /**      /**
# Line 963  namespace LinuxSampler { namespace gig { Line 1174  namespace LinuxSampler { namespace gig {
1174      }      }
1175    
1176      String Engine::Version() {      String Engine::Version() {
1177          String s = "$Revision: 1.13 $";          String s = "$Revision: 1.21 $";
1178          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
1179      }      }
1180    

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

  ViewVC Help
Powered by ViewVC