/[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 473 by schoenebeck, Thu Mar 17 20:13:08 2005 UTC revision 769 by schoenebeck, Sat Sep 3 11:14:30 2005 UTC
# Line 29  Line 29 
29    
30  #include "Engine.h"  #include "Engine.h"
31    
 #if defined(__APPLE__)  
 # include <stdlib.h>  
 #else  
 # include <malloc.h>  
 #endif  
   
32  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
33    
34      InstrumentResourceManager Engine::instruments;      InstrumentResourceManager Engine::instruments;
# Line 103  namespace LinuxSampler { namespace gig { Line 97  namespace LinuxSampler { namespace gig {
97          pAudioOutputDevice = NULL;          pAudioOutputDevice = NULL;
98          pDiskThread        = NULL;          pDiskThread        = NULL;
99          pEventGenerator    = NULL;          pEventGenerator    = NULL;
100          pSysexBuffer       = new RingBuffer<uint8_t>(SYSEX_BUFFER_SIZE, 0);          pSysexBuffer       = new RingBuffer<uint8_t>(CONFIG_SYSEX_BUFFER_SIZE, 0);
101          pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT, 0);          pEventQueue        = new RingBuffer<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);
102          pEventPool         = new Pool<Event>(MAX_EVENTS_PER_FRAGMENT);          pEventPool         = new Pool<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT);
103          pVoicePool         = new Pool<Voice>(MAX_AUDIO_VOICES);          pVoicePool         = new Pool<Voice>(CONFIG_MAX_VOICES);
104          pVoiceStealingQueue = new RTList<Event>(pEventPool);          pVoiceStealingQueue = new RTList<Event>(pEventPool);
105          pGlobalEvents      = new RTList<Event>(pEventPool);          pGlobalEvents      = new RTList<Event>(pEventPool);
106          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
# Line 114  namespace LinuxSampler { namespace gig { Line 108  namespace LinuxSampler { namespace gig {
108          }          }
109          pVoicePool->clear();          pVoicePool->clear();
110    
         pSynthesisParameters[0] = NULL; // we allocate when an audio device is connected  
         pBasicFilterParameters  = NULL;  
         pMainFilterParameters   = NULL;  
   
111          ResetInternal();          ResetInternal();
112            ResetScaleTuning();
113      }      }
114    
115      /**      /**
# Line 138  namespace LinuxSampler { namespace gig { Line 129  namespace LinuxSampler { namespace gig {
129              delete pVoicePool;              delete pVoicePool;
130          }          }
131          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
         if (pMainFilterParameters) delete[] pMainFilterParameters;  
         if (pBasicFilterParameters) delete[] pBasicFilterParameters;  
         if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);  
132          if (pVoiceStealingQueue) delete pVoiceStealingQueue;          if (pVoiceStealingQueue) delete pVoiceStealingQueue;
133          if (pSysexBuffer) delete pSysexBuffer;          if (pSysexBuffer) delete pSysexBuffer;
134          EngineFactory::Destroy(this);          EngineFactory::Destroy(this);
# Line 171  namespace LinuxSampler { namespace gig { Line 159  namespace LinuxSampler { namespace gig {
159      void Engine::Reset() {      void Engine::Reset() {
160          DisableAndLock();          DisableAndLock();
161          ResetInternal();          ResetInternal();
162            ResetScaleTuning();
163          Enable();          Enable();
164      }      }
165    
# Line 184  namespace LinuxSampler { namespace gig { Line 173  namespace LinuxSampler { namespace gig {
173    
174          // reset voice stealing parameters          // reset voice stealing parameters
175          pVoiceStealingQueue->clear();          pVoiceStealingQueue->clear();
176          itLastStolenVoice  = RTList<Voice>::Iterator();          itLastStolenVoice          = RTList<Voice>::Iterator();
177          iuiLastStolenKey   = RTList<uint>::Iterator();          itLastStolenVoiceGlobally  = RTList<Voice>::Iterator();
178          pLastStolenChannel = NULL;          iuiLastStolenKey           = RTList<uint>::Iterator();
179            iuiLastStolenKeyGlobally   = RTList<uint>::Iterator();
180          // reset to normal chromatic scale (means equal temper)          pLastStolenChannel         = NULL;
         memset(&ScaleTuning[0], 0x00, 12);  
181    
182          // reset all voices          // reset all voices
183          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
# Line 205  namespace LinuxSampler { namespace gig { Line 193  namespace LinuxSampler { namespace gig {
193      }      }
194    
195      /**      /**
196         * Reset to normal, chromatic scale (means equal tempered).
197         */
198        void Engine::ResetScaleTuning() {
199            memset(&ScaleTuning[0], 0x00, 12);
200        }
201    
202        /**
203       * Connect this engine instance with the given audio output device.       * Connect this engine instance with the given audio output device.
204       * This method will be called when an Engine instance is created.       * This method will be called when an Engine instance is created.
205       * All of the engine's data structures which are dependant to the used       * All of the engine's data structures which are dependant to the used
# Line 231  namespace LinuxSampler { namespace gig { Line 226  namespace LinuxSampler { namespace gig {
226          this->SampleRate         = pAudioOutputDevice->SampleRate();          this->SampleRate         = pAudioOutputDevice->SampleRate();
227    
228          // FIXME: audio drivers with varying fragment sizes might be a problem here          // FIXME: audio drivers with varying fragment sizes might be a problem here
229          MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * EG_MIN_RELEASE_TIME) - 1;          MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * CONFIG_EG_MIN_RELEASE_TIME) - 1;
230          if (MaxFadeOutPos < 0)          if (MaxFadeOutPos < 0) {
231              throw LinuxSamplerException("EG_MIN_RELEASE_TIME in EGADSR.h too big for current audio fragment size / sampling rate!");              std::cerr << "gig::Engine: WARNING, CONFIG_EG_MIN_RELEASE_TIME "
232                          << "too big for current audio fragment size & sampling rate! "
233                          << "May lead to click sounds if voice stealing chimes in!\n" << std::flush;
234                // force volume ramp downs at the beginning of each fragment
235                MaxFadeOutPos = 0;
236                // lower minimum release time
237                const float minReleaseTime = (float) MaxSamplesPerCycle / (float) SampleRate;
238                for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
239                    iterVoice->EG1.CalculateFadeOutCoeff(minReleaseTime, SampleRate);
240                }
241                pVoicePool->clear();
242            }
243    
244          // (re)create disk thread          // (re)create disk thread
245          if (this->pDiskThread) {          if (this->pDiskThread) {
# Line 242  namespace LinuxSampler { namespace gig { Line 248  namespace LinuxSampler { namespace gig {
248              delete this->pDiskThread;              delete this->pDiskThread;
249              dmsg(1,("OK\n"));              dmsg(1,("OK\n"));
250          }          }
251          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << CONFIG_MAX_PITCH) << 1) + 6); //FIXME: assuming stereo
252          if (!pDiskThread) {          if (!pDiskThread) {
253              dmsg(0,("gig::Engine  new diskthread = NULL\n"));              dmsg(0,("gig::Engine  new diskthread = NULL\n"));
254              exit(EXIT_FAILURE);              exit(EXIT_FAILURE);
# Line 258  namespace LinuxSampler { namespace gig { Line 264  namespace LinuxSampler { namespace gig {
264          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
265          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
266    
         // (re)allocate synthesis parameter matrix  
         if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);  
   
         #if defined(__APPLE__)  
         pSynthesisParameters[0] = (float *) malloc(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle());  
         #else  
         pSynthesisParameters[0] = (float *) memalign(16,(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle()));  
         #endif  
         for (int dst = 1; dst < Event::destination_count; dst++)  
             pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();  
   
         // (re)allocate biquad filter parameter sequence  
         if (pBasicFilterParameters) delete[] pBasicFilterParameters;  
         if (pMainFilterParameters)  delete[] pMainFilterParameters;  
         pBasicFilterParameters = new biquad_param_t[pAudioOut->MaxSamplesPerCycle()];  
         pMainFilterParameters  = new biquad_param_t[pAudioOut->MaxSamplesPerCycle()];  
   
267          dmsg(1,("Starting disk thread..."));          dmsg(1,("Starting disk thread..."));
268          pDiskThread->StartThread();          pDiskThread->StartThread();
269          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
# Line 352  namespace LinuxSampler { namespace gig { Line 341  namespace LinuxSampler { namespace gig {
341          // update time of start and end of this audio fragment (as events' time stamps relate to this)          // update time of start and end of this audio fragment (as events' time stamps relate to this)
342          pEventGenerator->UpdateFragmentTime(Samples);          pEventGenerator->UpdateFragmentTime(Samples);
343    
344            // We only allow a maximum of CONFIG_MAX_VOICES voices to be spawned
345            // in each audio fragment. All subsequent request for spawning new
346            // voices in the same audio fragment will be ignored.
347            VoiceSpawnsLeft = CONFIG_MAX_VOICES;
348    
349          // get all events from the engine's global input event queue which belong to the current fragment          // get all events from the engine's global input event queue which belong to the current fragment
350          // (these are usually just SysEx messages)          // (these are usually just SysEx messages)
351          ImportEvents(Samples);          ImportEvents(Samples);
# Line 370  namespace LinuxSampler { namespace gig { Line 364  namespace LinuxSampler { namespace gig {
364              }              }
365          }          }
366    
         // We only allow a maximum of MAX_AUDIO_VOICES voices to be stolen  
         // in each audio fragment. All subsequent request for spawning new  
         // voices in the same audio fragment will be ignored.  
         VoiceTheftsLeft = MAX_AUDIO_VOICES;  
   
367          // reset internal voice counter (just for statistic of active voices)          // reset internal voice counter (just for statistic of active voices)
368          ActiveVoiceCountTemp = 0;          ActiveVoiceCountTemp = 0;
369    
   
370          // handle events on all engine channels          // handle events on all engine channels
371          for (int i = 0; i < engineChannels.size(); i++) {          for (int i = 0; i < engineChannels.size(); i++) {
372              if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded              if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
# Line 406  namespace LinuxSampler { namespace gig { Line 394  namespace LinuxSampler { namespace gig {
394    
395          // reset voice stealing for the next audio fragment          // reset voice stealing for the next audio fragment
396          pVoiceStealingQueue->clear();          pVoiceStealingQueue->clear();
         itLastStolenVoice  = RTList<Voice>::Iterator();  
         iuiLastStolenKey   = RTList<uint>::Iterator();  
         pLastStolenChannel = NULL;  
397    
398          // just some statistics about this engine instance          // just some statistics about this engine instance
399          ActiveVoiceCount = ActiveVoiceCountTemp;          ActiveVoiceCount = ActiveVoiceCountTemp;
400          if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;          if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;
401    
402            FrameTime += Samples;
403    
404          return 0;          return 0;
405      }      }
406    
# Line 456  namespace LinuxSampler { namespace gig { Line 443  namespace LinuxSampler { namespace gig {
443                  }                  }
444              }              }
445          }          }
446    
447            // reset voice stealing for the next engine channel (or next audio fragment)
448            itLastStolenVoice         = RTList<Voice>::Iterator();
449            itLastStolenVoiceGlobally = RTList<Voice>::Iterator();
450            iuiLastStolenKey          = RTList<uint>::Iterator();
451            iuiLastStolenKeyGlobally  = RTList<uint>::Iterator();
452            pLastStolenChannel        = NULL;
453      }      }
454    
455      /**      /**
# Line 468  namespace LinuxSampler { namespace gig { Line 462  namespace LinuxSampler { namespace gig {
462       *                         this audio fragment cycle       *                         this audio fragment cycle
463       */       */
464      void Engine::RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {      void Engine::RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {
465            #if !CONFIG_PROCESS_MUTED_CHANNELS
466            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
467            #endif
468    
469          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
470          RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();          RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
471          while (iuiKey != end) { // iterate through all active keys          while (iuiKey != end) { // iterate through all active keys
# Line 506  namespace LinuxSampler { namespace gig { Line 504  namespace LinuxSampler { namespace gig {
504          for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {          for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
505              EngineChannel* pEngineChannel = (EngineChannel*) itVoiceStealEvent->pEngineChannel;              EngineChannel* pEngineChannel = (EngineChannel*) itVoiceStealEvent->pEngineChannel;
506              Pool<Voice>::Iterator itNewVoice =              Pool<Voice>::Iterator itNewVoice =
507                  LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false);                  LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false, false);
508              if (itNewVoice) {              if (itNewVoice) {
509                  itNewVoice->Render(Samples);                  itNewVoice->Render(Samples);
510                  if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active                  if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active
# Line 539  namespace LinuxSampler { namespace gig { Line 537  namespace LinuxSampler { namespace gig {
537                  midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];                  midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
538                  ++iuiKey;                  ++iuiKey;
539                  if (pKey->pActiveVoices->isEmpty()) FreeKey(pEngineChannel, pKey);                  if (pKey->pActiveVoices->isEmpty()) FreeKey(pEngineChannel, pKey);
540                  #if DEVMODE                  #if CONFIG_DEVMODE
541                  else { // FIXME: should be removed before the final release (purpose: just a sanity check for debugging)                  else { // just a sanity check for debugging
542                      RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();                      RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
543                      RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();                      RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
544                      for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key                      for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
# Line 549  namespace LinuxSampler { namespace gig { Line 547  namespace LinuxSampler { namespace gig {
547                          }                          }
548                      }                      }
549                  }                  }
550                  #endif // DEVMODE                  #endif // CONFIG_DEVMODE
551              }              }
552          }          }
553    
# Line 584  namespace LinuxSampler { namespace gig { Line 582  namespace LinuxSampler { namespace gig {
582                  // finally place sysex event into input event queue                  // finally place sysex event into input event queue
583                  pEventQueue->push(&event);                  pEventQueue->push(&event);
584              }              }
585              else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,SYSEX_BUFFER_SIZE));              else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,CONFIG_SYSEX_BUFFER_SIZE));
586          }          }
587          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
588      }      }
# Line 596  namespace LinuxSampler { namespace gig { Line 594  namespace LinuxSampler { namespace gig {
594       *  @param itNoteOnEvent - key, velocity and time stamp of the event       *  @param itNoteOnEvent - key, velocity and time stamp of the event
595       */       */
596      void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {      void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
597            #if !CONFIG_PROCESS_MUTED_CHANNELS
598            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
599            #endif
600    
601          const int key = itNoteOnEvent->Param.Note.Key;          const int key = itNoteOnEvent->Param.Note.Key;
602    
# Line 610  namespace LinuxSampler { namespace gig { Line 611  namespace LinuxSampler { namespace gig {
611          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];
612    
613          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
614            pKey->Velocity   = itNoteOnEvent->Param.Note.Velocity;
615            pKey->NoteOnTime = FrameTime + itNoteOnEvent->FragmentPos(); // will be used to calculate note length
616    
617          // cancel release process of voices on this key if needed          // cancel release process of voices on this key if needed
618          if (pKey->Active && !pEngineChannel->SustainPedal) {          if (pKey->Active && !pEngineChannel->SustainPedal) {
# Line 632  namespace LinuxSampler { namespace gig { Line 635  namespace LinuxSampler { namespace gig {
635                  int voicesRequired = pRegion->Layers;                  int voicesRequired = pRegion->Layers;
636                  // now launch the required amount of voices                  // now launch the required amount of voices
637                  for (int i = 0; i < voicesRequired; i++)                  for (int i = 0; i < voicesRequired; i++)
638                      LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true);                      LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true, true);
639              }              }
640          }          }
641    
# Line 653  namespace LinuxSampler { namespace gig { Line 656  namespace LinuxSampler { namespace gig {
656       *  @param itNoteOffEvent - key, velocity and time stamp of the event       *  @param itNoteOffEvent - key, velocity and time stamp of the event
657       */       */
658      void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {      void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {
659          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];          #if !CONFIG_PROCESS_MUTED_CHANNELS
660            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
661            #endif
662    
663            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];
664          pKey->KeyPressed = false; // the MIDI key was now released          pKey->KeyPressed = false; // the MIDI key was now released
665    
666          // release voices on this key if needed          // release voices on this key if needed
667          if (pKey->Active && !pEngineChannel->SustainPedal) {          if (pKey->Active && !pEngineChannel->SustainPedal) {
668              itNoteOffEvent->Type = Event::type_release; // transform event type              itNoteOffEvent->Type = Event::type_release; // transform event type
         }  
669    
670          // move event to the key's own event list              // move event to the key's own event list
671          RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);              RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
672    
673          // spawn release triggered voice(s) if needed              // spawn release triggered voice(s) if needed
674          if (pKey->ReleaseTrigger) {              if (pKey->ReleaseTrigger) {
675              // first, get total amount of required voices (dependant on amount of layers)                  // first, get total amount of required voices (dependant on amount of layers)
676              ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOffEventOnKeyList->Param.Note.Key);                  ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOffEventOnKeyList->Param.Note.Key);
677              if (pRegion) {                  if (pRegion) {
678                  int voicesRequired = pRegion->Layers;                      int voicesRequired = pRegion->Layers;
679                  // now launch the required amount of voices  
680                  for (int i = 0; i < voicesRequired; i++)                      // MIDI note-on velocity is used instead of note-off velocity
681                      LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, i, true, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples                      itNoteOffEventOnKeyList->Param.Note.Velocity = pKey->Velocity;
682    
683                        // now launch the required amount of voices
684                        for (int i = 0; i < voicesRequired; i++)
685                            LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, i, true, false, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
686                    }
687                    pKey->ReleaseTrigger = false;
688              }              }
             pKey->ReleaseTrigger = false;  
         }  
689    
690          // if neither a voice was spawned or postponed then remove note off event from key again              // if neither a voice was spawned or postponed then remove note off event from key again
691          if (!pKey->Active && !pKey->VoiceTheftsQueued)              if (!pKey->Active && !pKey->VoiceTheftsQueued)
692              pKey->pEvents->free(itNoteOffEventOnKeyList);                  pKey->pEvents->free(itNoteOffEventOnKeyList);
693            }
694      }      }
695    
696      /**      /**
697       *  Moves pitchbend event from the general (input) event list to the pitch       *  Moves pitchbend event from the general (input) event list to the engine
698       *  event list.       *  channel's event list. It will actually processed later by the
699         *  respective voice.
700       *       *
701       *  @param pEngineChannel - engine channel on which this event occured on       *  @param pEngineChannel - engine channel on which this event occured on
702       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event
703       */       */
704      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {
705          pEngineChannel->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value          pEngineChannel->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value
         itPitchbendEvent.moveToEndOf(pEngineChannel->pSynthesisEvents[Event::destination_vco]);  
706      }      }
707    
708      /**      /**
# Line 709  namespace LinuxSampler { namespace gig { Line 719  namespace LinuxSampler { namespace gig {
719       *  @param VoiceStealing       - if voice stealing should be performed       *  @param VoiceStealing       - if voice stealing should be performed
720       *                               when there is no free voice       *                               when there is no free voice
721       *                               (optional, default = true)       *                               (optional, default = true)
722         *  @param HandleKeyGroupConflicts - if voices should be killed due to a
723         *                                   key group conflict
724       *  @returns pointer to new voice or NULL if there was no free voice or       *  @returns pointer to new voice or NULL if there was no free voice or
725       *           if the voice wasn't triggered (for example when no region is       *           if the voice wasn't triggered (for example when no region is
726       *           defined for the given key).       *           defined for the given key).
727       */       */
728      Pool<Voice>::Iterator Engine::LaunchVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing) {      Pool<Voice>::Iterator Engine::LaunchVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing, bool HandleKeyGroupConflicts) {
729          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];          int MIDIKey            = itNoteOnEvent->Param.Note.Key;
730            midi_key_info_t* pKey  = &pEngineChannel->pMIDIKeyInfo[MIDIKey];
731            ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(MIDIKey);
732    
733            // if nothing defined for this key
734            if (!pRegion) return Pool<Voice>::Iterator(); // nothing to do
735    
736            // only mark the first voice of a layered voice (group) to be in a
737            // key group, so the layered voices won't kill each other
738            int iKeyGroup = (iLayer == 0 && !ReleaseTriggerVoice) ? pRegion->KeyGroup : 0;
739    
740            // handle key group (a.k.a. exclusive group) conflicts
741            if (HandleKeyGroupConflicts) {
742                if (iKeyGroup) { // if this voice / key belongs to a key group
743                    uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[iKeyGroup];
744                    if (*ppKeyGroup) { // if there's already an active key in that key group
745                        midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[**ppKeyGroup];
746                        // kill all voices on the (other) key
747                        RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
748                        RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
749                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
750                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger) {
751                                itVoiceToBeKilled->Kill(itNoteOnEvent);
752                                --VoiceSpawnsLeft; //FIXME: just a hack, we should better check in StealVoice() if the voice was killed due to key conflict
753                            }
754                        }
755                    }
756                }
757            }
758    
759            Voice::type_t VoiceType = Voice::type_normal;
760    
761            // get current dimension values to select the right dimension region
762            //TODO: for stolen voices this dimension region selection block is processed twice, this should be changed
763            //FIXME: controller values for selecting the dimension region here are currently not sample accurate
764            uint DimValues[8] = { 0 };
765            for (int i = pRegion->Dimensions - 1; i >= 0; i--) {
766                switch (pRegion->pDimensionDefinitions[i].dimension) {
767                    case ::gig::dimension_samplechannel:
768                        DimValues[i] = 0; //TODO: we currently ignore this dimension
769                        break;
770                    case ::gig::dimension_layer:
771                        DimValues[i] = iLayer;
772                        break;
773                    case ::gig::dimension_velocity:
774                        DimValues[i] = itNoteOnEvent->Param.Note.Velocity;
775                        break;
776                    case ::gig::dimension_channelaftertouch:
777                        DimValues[i] = 0; //TODO: we currently ignore this dimension
778                        break;
779                    case ::gig::dimension_releasetrigger:
780                        VoiceType = (ReleaseTriggerVoice) ? Voice::type_release_trigger : (!iLayer) ? Voice::type_release_trigger_required : Voice::type_normal;
781                        DimValues[i] = (uint) ReleaseTriggerVoice;
782                        break;
783                    case ::gig::dimension_keyboard:
784                        DimValues[i] = (uint) pEngineChannel->CurrentKeyDimension;
785                        break;
786                    case ::gig::dimension_roundrobin:
787                        DimValues[i] = (uint) pEngineChannel->pMIDIKeyInfo[MIDIKey].RoundRobinIndex; // incremented for each note on
788                        break;
789                    case ::gig::dimension_random:
790                        RandomSeed   = RandomSeed * 1103515245 + 12345; // classic pseudo random number generator
791                        DimValues[i] = (uint) RandomSeed >> (32 - pRegion->pDimensionDefinitions[i].bits); // highest bits are most random
792                        break;
793                    case ::gig::dimension_modwheel:
794                        DimValues[i] = pEngineChannel->ControllerTable[1];
795                        break;
796                    case ::gig::dimension_breath:
797                        DimValues[i] = pEngineChannel->ControllerTable[2];
798                        break;
799                    case ::gig::dimension_foot:
800                        DimValues[i] = pEngineChannel->ControllerTable[4];
801                        break;
802                    case ::gig::dimension_portamentotime:
803                        DimValues[i] = pEngineChannel->ControllerTable[5];
804                        break;
805                    case ::gig::dimension_effect1:
806                        DimValues[i] = pEngineChannel->ControllerTable[12];
807                        break;
808                    case ::gig::dimension_effect2:
809                        DimValues[i] = pEngineChannel->ControllerTable[13];
810                        break;
811                    case ::gig::dimension_genpurpose1:
812                        DimValues[i] = pEngineChannel->ControllerTable[16];
813                        break;
814                    case ::gig::dimension_genpurpose2:
815                        DimValues[i] = pEngineChannel->ControllerTable[17];
816                        break;
817                    case ::gig::dimension_genpurpose3:
818                        DimValues[i] = pEngineChannel->ControllerTable[18];
819                        break;
820                    case ::gig::dimension_genpurpose4:
821                        DimValues[i] = pEngineChannel->ControllerTable[19];
822                        break;
823                    case ::gig::dimension_sustainpedal:
824                        DimValues[i] = pEngineChannel->ControllerTable[64];
825                        break;
826                    case ::gig::dimension_portamento:
827                        DimValues[i] = pEngineChannel->ControllerTable[65];
828                        break;
829                    case ::gig::dimension_sostenutopedal:
830                        DimValues[i] = pEngineChannel->ControllerTable[66];
831                        break;
832                    case ::gig::dimension_softpedal:
833                        DimValues[i] = pEngineChannel->ControllerTable[67];
834                        break;
835                    case ::gig::dimension_genpurpose5:
836                        DimValues[i] = pEngineChannel->ControllerTable[80];
837                        break;
838                    case ::gig::dimension_genpurpose6:
839                        DimValues[i] = pEngineChannel->ControllerTable[81];
840                        break;
841                    case ::gig::dimension_genpurpose7:
842                        DimValues[i] = pEngineChannel->ControllerTable[82];
843                        break;
844                    case ::gig::dimension_genpurpose8:
845                        DimValues[i] = pEngineChannel->ControllerTable[83];
846                        break;
847                    case ::gig::dimension_effect1depth:
848                        DimValues[i] = pEngineChannel->ControllerTable[91];
849                        break;
850                    case ::gig::dimension_effect2depth:
851                        DimValues[i] = pEngineChannel->ControllerTable[92];
852                        break;
853                    case ::gig::dimension_effect3depth:
854                        DimValues[i] = pEngineChannel->ControllerTable[93];
855                        break;
856                    case ::gig::dimension_effect4depth:
857                        DimValues[i] = pEngineChannel->ControllerTable[94];
858                        break;
859                    case ::gig::dimension_effect5depth:
860                        DimValues[i] = pEngineChannel->ControllerTable[95];
861                        break;
862                    case ::gig::dimension_none:
863                        std::cerr << "gig::Engine::LaunchVoice() Error: dimension=none\n" << std::flush;
864                        break;
865                    default:
866                        std::cerr << "gig::Engine::LaunchVoice() Error: Unknown dimension\n" << std::flush;
867                }
868            }
869            ::gig::DimensionRegion* pDimRgn = pRegion->GetDimensionRegionByValue(DimValues);
870    
871            // no need to continue if sample is silent
872            if (!pDimRgn->pSample || !pDimRgn->pSample->SamplesTotal) return Pool<Voice>::Iterator();
873    
874          // allocate a new voice for the key          // allocate a new voice for the key
875          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
876          if (itNewVoice) {          if (itNewVoice) {
877              // launch the new voice              // launch the new voice
878              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pEngineChannel->pInstrument, iLayer, ReleaseTriggerVoice, VoiceStealing) < 0) {              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pDimRgn, VoiceType, iKeyGroup) < 0) {
879                  dmsg(4,("Voice not triggered\n"));                  dmsg(4,("Voice not triggered\n"));
880                  pKey->pActiveVoices->free(itNewVoice);                  pKey->pActiveVoices->free(itNewVoice);
881              }              }
882              else { // on success              else { // on success
883                  uint** ppKeyGroup = NULL;                  --VoiceSpawnsLeft;
                 if (itNewVoice->KeyGroup) { // if this voice / key belongs to a key group  
                     ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup];  
                     if (*ppKeyGroup) { // if there's already an active key in that key group  
                         midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[**ppKeyGroup];  
                         // kill all voices on the (other) key  
                         RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();  
                         RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();  
                         for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {  
                             if (itVoiceToBeKilled->Type != Voice::type_release_trigger) itVoiceToBeKilled->Kill(itNoteOnEvent);  
                         }  
                     }  
                 }  
884                  if (!pKey->Active) { // mark as active key                  if (!pKey->Active) { // mark as active key
885                      pKey->Active = true;                      pKey->Active = true;
886                      pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();                      pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();
887                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
888                  }                  }
889                  if (itNewVoice->KeyGroup) {                  if (itNewVoice->KeyGroup) {
890                        uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup];
891                      *ppKeyGroup = &*pKey->itSelf; // 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
892                  }                  }
893                  if (itNewVoice->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)
# Line 780  namespace LinuxSampler { namespace gig { Line 924  namespace LinuxSampler { namespace gig {
924       *  @returns 0 on success, a value < 0 if no active voice could be picked for voice stealing       *  @returns 0 on success, a value < 0 if no active voice could be picked for voice stealing
925       */       */
926      int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {      int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
927          if (!VoiceTheftsLeft) {          if (VoiceSpawnsLeft <= 0) {
928              dmsg(1,("Max. voice thefts per audio fragment reached (you may raise MAX_AUDIO_VOICES).\n"));              dmsg(1,("Max. voice thefts per audio fragment reached (you may raise CONFIG_MAX_VOICES).\n"));
929              return -1;              return -1;
930          }          }
931          if (!pEventPool->poolIsEmpty()) {          if (!pEventPool->poolIsEmpty()) {
# Line 789  namespace LinuxSampler { namespace gig { Line 933  namespace LinuxSampler { namespace gig {
933              RTList<Voice>::Iterator itSelectedVoice;              RTList<Voice>::Iterator itSelectedVoice;
934    
935              // Select one voice for voice stealing              // Select one voice for voice stealing
936              switch (VOICE_STEAL_ALGORITHM) {              switch (CONFIG_VOICE_STEAL_ALGO) {
937    
938                  // try to pick the oldest voice on the key where the new                  // try to pick the oldest voice on the key where the new
939                  // voice should be spawned, if there is no voice on that                  // voice should be spawned, if there is no voice on that
940                  // key, or no voice left to kill there, then procceed with                  // key, or no voice left to kill, then procceed with
941                  // 'oldestkey' algorithm                  // 'oldestkey' algorithm
942                  case voice_steal_algo_oldestvoiceonkey: {                  case voice_steal_algo_oldestvoiceonkey: {
                 #if 0 // FIXME: broken  
943                      midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];                      midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
944                      if (this->itLastStolenVoice) {                      itSelectedVoice = pSelectedKey->pActiveVoices->first();
945                          itSelectedVoice = this->itLastStolenVoice;                      // proceed iterating if voice was created in this fragment cycle
946                          ++itSelectedVoice;                      while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
947                      }                      // if we haven't found a voice then proceed with algorithm 'oldestkey'
948                      else { // no voice stolen in this audio fragment cycle yet                      if (itSelectedVoice && itSelectedVoice->IsStealable()) break;
                         itSelectedVoice = pSelectedKey->pActiveVoices->first();  
                     }  
                     if (itSelectedVoice) {  
                         iuiSelectedKey = pSelectedKey->itSelf;  
                         break; // selection succeeded  
                     }  
                 #endif  
949                  } // no break - intentional !                  } // no break - intentional !
950    
951                  // try to pick the oldest voice on the oldest active key                  // try to pick the oldest voice on the oldest active key
952                    // from the same engine channel
953                  // (caution: must stay after 'oldestvoiceonkey' algorithm !)                  // (caution: must stay after 'oldestvoiceonkey' algorithm !)
954                  case voice_steal_algo_oldestkey: {                  case voice_steal_algo_oldestkey: {
955                        // if we already stole in this fragment, try to proceed on same key
956                      if (this->itLastStolenVoice) {                      if (this->itLastStolenVoice) {
957                          itSelectedVoice = this->itLastStolenVoice;                          itSelectedVoice = this->itLastStolenVoice;
958                          ++itSelectedVoice;                          do {
959                          if (itSelectedVoice) break; // selection succeeded                              ++itSelectedVoice;
960                          RTList<uint>::Iterator iuiSelectedKey = this->iuiLastStolenKey;                          } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
961                          ++iuiSelectedKey;                          // found a "stealable" voice ?
962                          if (iuiSelectedKey) {                          if (itSelectedVoice && itSelectedVoice->IsStealable()) {
963                              this->iuiLastStolenKey = iuiSelectedKey;                              // remember which voice we stole, so we can simply proceed on next voice stealing
964                              midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];                              this->itLastStolenVoice = itSelectedVoice;
                             itSelectedVoice = pSelectedKey->pActiveVoices->first();  
965                              break; // selection succeeded                              break; // selection succeeded
966                          }                          }
967                      }                      }
968                        // get (next) oldest key
969                        RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKey) ? ++this->iuiLastStolenKey : pEngineChannel->pActiveKeys->first();
970                        while (iuiSelectedKey) {
971                            midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];
972                            itSelectedVoice = pSelectedKey->pActiveVoices->first();
973                            // proceed iterating if voice was created in this fragment cycle
974                            while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
975                            // found a "stealable" voice ?
976                            if (itSelectedVoice && itSelectedVoice->IsStealable()) {
977                                // remember which voice on which key we stole, so we can simply proceed on next voice stealing
978                                this->iuiLastStolenKey  = iuiSelectedKey;
979                                this->itLastStolenVoice = itSelectedVoice;
980                                break; // selection succeeded
981                            }
982                            ++iuiSelectedKey; // get next oldest key
983                        }
984                      break;                      break;
985                  }                  }
986    
# Line 839  namespace LinuxSampler { namespace gig { Line 992  namespace LinuxSampler { namespace gig {
992                  }                  }
993              }              }
994    
995              // steal oldest voice on the oldest key from this or any other engine channel              // if we couldn't steal a voice from the same engine channel then
996              if (!itSelectedVoice) {              // steal oldest voice on the oldest key from any other engine channel
997                  EngineChannel* pSelectedChannel = (pLastStolenChannel) ? pLastStolenChannel : pEngineChannel;              // (the smaller engine channel number, the higher priority)
998                  int iChannelIndex = pSelectedChannel->iEngineIndexSelf;              if (!itSelectedVoice || !itSelectedVoice->IsStealable()) {
999                  while (true) {                  EngineChannel* pSelectedChannel;
1000                      RTList<uint>::Iterator iuiSelectedKey = pSelectedChannel->pActiveKeys->first();                  int            iChannelIndex;
1001                      if (iuiSelectedKey) {                  // select engine channel
1002                    if (pLastStolenChannel) {
1003                        pSelectedChannel = pLastStolenChannel;
1004                        iChannelIndex    = pSelectedChannel->iEngineIndexSelf;
1005                    } else { // pick the engine channel followed by this engine channel
1006                        iChannelIndex    = (pEngineChannel->iEngineIndexSelf + 1) % engineChannels.size();
1007                        pSelectedChannel = engineChannels[iChannelIndex];
1008                    }
1009    
1010                    // if we already stole in this fragment, try to proceed on same key
1011                    if (this->itLastStolenVoiceGlobally) {
1012                        itSelectedVoice = this->itLastStolenVoiceGlobally;
1013                        do {
1014                            ++itSelectedVoice;
1015                        } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1016                    }
1017    
1018                    #if CONFIG_DEVMODE
1019                    EngineChannel* pBegin = pSelectedChannel; // to detect endless loop
1020                    #endif // CONFIG_DEVMODE
1021    
1022                    // did we find a 'stealable' voice?
1023                    if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1024                        // remember which voice we stole, so we can simply proceed on next voice stealing
1025                        this->itLastStolenVoiceGlobally = itSelectedVoice;
1026                    } else while (true) { // iterate through engine channels
1027                        // get (next) oldest key
1028                        RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKeyGlobally) ? ++this->iuiLastStolenKeyGlobally : pSelectedChannel->pActiveKeys->first();
1029                        this->iuiLastStolenKeyGlobally = RTList<uint>::Iterator(); // to prevent endless loop (see line above)
1030                        while (iuiSelectedKey) {
1031                          midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];                          midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];
1032                          itSelectedVoice    = pSelectedKey->pActiveVoices->first();                          itSelectedVoice = pSelectedKey->pActiveVoices->first();
1033                          iuiLastStolenKey   = iuiSelectedKey;                          // proceed iterating if voice was created in this fragment cycle
1034                          pLastStolenChannel = pSelectedChannel;                          while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1035                          break; // selection succeeded                          // found a "stealable" voice ?
1036                            if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1037                                // remember which voice on which key on which engine channel we stole, so we can simply proceed on next voice stealing
1038                                this->iuiLastStolenKeyGlobally  = iuiSelectedKey;
1039                                this->itLastStolenVoiceGlobally = itSelectedVoice;
1040                                this->pLastStolenChannel        = pSelectedChannel;
1041                                goto stealable_voice_found; // selection succeeded
1042                            }
1043                            ++iuiSelectedKey; // get next key on current engine channel
1044                      }                      }
1045                        // get next engine channel
1046                      iChannelIndex    = (iChannelIndex + 1) % engineChannels.size();                      iChannelIndex    = (iChannelIndex + 1) % engineChannels.size();
1047                      pSelectedChannel =  engineChannels[iChannelIndex];                      pSelectedChannel = engineChannels[iChannelIndex];
1048    
1049                        #if CONFIG_DEVMODE
1050                        if (pSelectedChannel == pBegin) {
1051                            dmsg(1,("FATAL ERROR: voice stealing endless loop!\n"));
1052                            dmsg(1,("VoiceSpawnsLeft=%d.\n", VoiceSpawnsLeft));
1053                            dmsg(1,("Exiting.\n"));
1054                            exit(-1);
1055                        }
1056                        #endif // CONFIG_DEVMODE
1057                  }                  }
1058              }              }
1059    
1060              //FIXME: can be removed, just a sanity check for debugging              // jump point if a 'stealable' voice was found
1061                stealable_voice_found:
1062    
1063                #if CONFIG_DEVMODE
1064              if (!itSelectedVoice->IsActive()) {              if (!itSelectedVoice->IsActive()) {
1065                  dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));                  dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
1066                  return -1;                  return -1;
1067              }              }
1068                #endif // CONFIG_DEVMODE
1069    
1070              // now kill the selected voice              // now kill the selected voice
1071              itSelectedVoice->Kill(itNoteOnEvent);              itSelectedVoice->Kill(itNoteOnEvent);
1072    
1073              // remember which voice we stole, so we can simply proceed for the next voice stealing              --VoiceSpawnsLeft;
             itLastStolenVoice = itSelectedVoice;  
   
             --VoiceTheftsLeft;  
1074    
1075              return 0; // success              return 0; // success
1076          }          }
# Line 938  namespace LinuxSampler { namespace gig { Line 1139  namespace LinuxSampler { namespace gig {
1139          // update controller value in the engine channel's controller table          // update controller value in the engine channel's controller table
1140          pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;          pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
1141    
1142          // move event from the unsorted event list to the control change event list          switch (itControlChangeEvent->Param.CC.Controller) {
         Pool<Event>::Iterator itControlChangeEventOnCCList = itControlChangeEvent.moveToEndOf(pEngineChannel->pCCEvents);  
   
         switch (itControlChangeEventOnCCList->Param.CC.Controller) {  
1143              case 7: { // volume              case 7: { // volume
1144                  //TODO: not sample accurate yet                  //TODO: not sample accurate yet
1145                  pEngineChannel->GlobalVolume = (float) itControlChangeEventOnCCList->Param.CC.Value / 127.0f;                  pEngineChannel->GlobalVolume = (float) itControlChangeEvent->Param.CC.Value / 127.0f;
1146                    pEngineChannel->bStatusChanged = true; // engine channel status has changed, so set notify flag
1147                  break;                  break;
1148              }              }
1149              case 10: { // panpot              case 10: { // panpot
1150                  //TODO: not sample accurate yet                  //TODO: not sample accurate yet
1151                  const int pan = (int) itControlChangeEventOnCCList->Param.CC.Value - 64;                  const int pan = (int) itControlChangeEvent->Param.CC.Value - 64;
1152                  pEngineChannel->GlobalPanLeft  = 1.0f - float(RTMath::Max(pan, 0)) /  63.0f;                  pEngineChannel->GlobalPanLeft  = 1.0f - float(RTMath::Max(pan, 0)) /  63.0f;
1153                  pEngineChannel->GlobalPanRight = 1.0f - float(RTMath::Min(pan, 0)) / -64.0f;                  pEngineChannel->GlobalPanRight = 1.0f - float(RTMath::Min(pan, 0)) / -64.0f;
1154                  break;                  break;
1155              }              }
1156              case 64: { // sustain              case 64: { // sustain
1157                  if (itControlChangeEventOnCCList->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {
1158                      dmsg(4,("PEDAL DOWN\n"));                      dmsg(4,("PEDAL DOWN\n"));
1159                      pEngineChannel->SustainPedal = true;                      pEngineChannel->SustainPedal = true;
1160    
1161                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1162                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1163                        #endif
1164    
1165                      // cancel release process of voices if necessary                      // cancel release process of voices if necessary
1166                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1167                      for (; iuiKey; ++iuiKey) {                      for (; iuiKey; ++iuiKey) {
# Line 966  namespace LinuxSampler { namespace gig { Line 1169  namespace LinuxSampler { namespace gig {
1169                          if (!pKey->KeyPressed) {                          if (!pKey->KeyPressed) {
1170                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1171                              if (itNewEvent) {                              if (itNewEvent) {
1172                                  *itNewEvent = *itControlChangeEventOnCCList; // copy event to the key's own event list                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1173                                  itNewEvent->Type = Event::type_cancel_release; // transform event type                                  itNewEvent->Type = Event::type_cancel_release; // transform event type
1174                              }                              }
1175                              else dmsg(1,("Event pool emtpy!\n"));                              else dmsg(1,("Event pool emtpy!\n"));
1176                          }                          }
1177                      }                      }
1178                  }                  }
1179                  if (itControlChangeEventOnCCList->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {
1180                      dmsg(4,("PEDAL UP\n"));                      dmsg(4,("PEDAL UP\n"));
1181                      pEngineChannel->SustainPedal = false;                      pEngineChannel->SustainPedal = false;
1182    
1183                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1184                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1185                        #endif
1186    
1187                      // release voices if their respective key is not pressed                      // release voices if their respective key is not pressed
1188                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1189                      for (; iuiKey; ++iuiKey) {                      for (; iuiKey; ++iuiKey) {
# Line 984  namespace LinuxSampler { namespace gig { Line 1191  namespace LinuxSampler { namespace gig {
1191                          if (!pKey->KeyPressed) {                          if (!pKey->KeyPressed) {
1192                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1193                              if (itNewEvent) {                              if (itNewEvent) {
1194                                  *itNewEvent = *itControlChangeEventOnCCList; // copy event to the key's own event list                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1195                                  itNewEvent->Type = Event::type_release; // transform event type                                  itNewEvent->Type = Event::type_release; // transform event type
1196                              }                              }
1197                              else dmsg(1,("Event pool emtpy!\n"));                              else dmsg(1,("Event pool emtpy!\n"));
# Line 998  namespace LinuxSampler { namespace gig { Line 1205  namespace LinuxSampler { namespace gig {
1205              // Channel Mode Messages              // Channel Mode Messages
1206    
1207              case 120: { // all sound off              case 120: { // all sound off
1208                  KillAllVoices(pEngineChannel, itControlChangeEventOnCCList);                  KillAllVoices(pEngineChannel, itControlChangeEvent);
1209                  break;                  break;
1210              }              }
1211              case 121: { // reset all controllers              case 121: { // reset all controllers
# Line 1006  namespace LinuxSampler { namespace gig { Line 1213  namespace LinuxSampler { namespace gig {
1213                  break;                  break;
1214              }              }
1215              case 123: { // all notes off              case 123: { // all notes off
1216                  ReleaseAllVoices(pEngineChannel, itControlChangeEventOnCCList);                  ReleaseAllVoices(pEngineChannel, itControlChangeEvent);
1217                  break;                  break;
1218              }              }
1219          }          }
# Line 1027  namespace LinuxSampler { namespace gig { Line 1234  namespace LinuxSampler { namespace gig {
1234    
1235          switch (id) {          switch (id) {
1236              case 0x41: { // Roland              case 0x41: { // Roland
1237                    dmsg(3,("Roland Sysex\n"));
1238                  uint8_t device_id, model_id, cmd_id;                  uint8_t device_id, model_id, cmd_id;
1239                  if (!reader.pop(&device_id)) goto free_sysex_data;                  if (!reader.pop(&device_id)) goto free_sysex_data;
1240                  if (!reader.pop(&model_id))  goto free_sysex_data;                  if (!reader.pop(&model_id))  goto free_sysex_data;
# Line 1039  namespace LinuxSampler { namespace gig { Line 1247  namespace LinuxSampler { namespace gig {
1247                  const RingBuffer<uint8_t>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later                  const RingBuffer<uint8_t>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later
1248                  if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;                  if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;
1249                  if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters                  if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters
1250                        dmsg(3,("\tSystem Parameter\n"));
1251                  }                  }
1252                  else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters                  else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters
1253                        dmsg(3,("\tCommon Parameter\n"));
1254                  }                  }
1255                  else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)                  else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)
1256                      switch (addr[3]) {                      dmsg(3,("\tPart Parameter\n"));
1257                        switch (addr[2]) {
1258                          case 0x40: { // scale tuning                          case 0x40: { // scale tuning
1259                                dmsg(3,("\t\tScale Tuning\n"));
1260                              uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave                              uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave
1261                              if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;                              if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;
1262                              uint8_t checksum;                              uint8_t checksum;
1263                              if (!reader.pop(&checksum))                      goto free_sysex_data;                              if (!reader.pop(&checksum)) goto free_sysex_data;
1264                              if (GSCheckSum(checksum_reader, 12) != checksum) goto free_sysex_data;                              #if CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1265                                if (GSCheckSum(checksum_reader, 12)) goto free_sysex_data;
1266                                #endif // CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1267                              for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;                              for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;
1268                              AdjustScale((int8_t*) scale_tunes);                              AdjustScale((int8_t*) scale_tunes);
1269                                dmsg(3,("\t\t\tNew scale applied.\n"));
1270                              break;                              break;
1271                          }                          }
1272                      }                      }
# Line 1136  namespace LinuxSampler { namespace gig { Line 1351  namespace LinuxSampler { namespace gig {
1351              RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();              RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
1352              for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key              for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
1353                  itVoice->Kill(itKillEvent);                  itVoice->Kill(itKillEvent);
1354                    --VoiceSpawnsLeft; //FIXME: just a temporary workaround, we should check the cause in StealVoice() instead
1355              }              }
1356          }          }
1357      }      }
1358    
     /**  
      * Initialize the parameter sequence for the modulation destination given by  
      * by 'dst' with the constant value given by val.  
      */  
     void Engine::ResetSynthesisParameters(Event::destination_t dst, float val) {  
         int maxsamples = pAudioOutputDevice->MaxSamplesPerCycle();  
         float* m = &pSynthesisParameters[dst][0];  
         for (int i = 0; i < maxsamples; i += 4) {  
            m[i]   = val;  
            m[i+1] = val;  
            m[i+2] = val;  
            m[i+3] = val;  
         }  
     }  
   
1359      uint Engine::VoiceCount() {      uint Engine::VoiceCount() {
1360          return ActiveVoiceCount;          return ActiveVoiceCount;
1361      }      }
# Line 1184  namespace LinuxSampler { namespace gig { Line 1385  namespace LinuxSampler { namespace gig {
1385      }      }
1386    
1387      String Engine::EngineName() {      String Engine::EngineName() {
1388          return "GigEngine";          return LS_GIG_ENGINE_NAME;
1389      }      }
1390    
1391      String Engine::Description() {      String Engine::Description() {
# Line 1192  namespace LinuxSampler { namespace gig { Line 1393  namespace LinuxSampler { namespace gig {
1393      }      }
1394    
1395      String Engine::Version() {      String Engine::Version() {
1396          String s = "$Revision: 1.33 $";          String s = "$Revision: 1.53 $";
1397          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
1398      }      }
1399    

Legend:
Removed from v.473  
changed lines
  Added in v.769

  ViewVC Help
Powered by ViewVC