/[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 659 by schoenebeck, Thu Jun 16 21:35:30 2005 UTC revision 970 by schoenebeck, Wed Dec 6 22:28:17 2006 UTC
# Line 3  Line 3 
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6   *   Copyright (C) 2005 Christian Schoenebeck                              *   *   Copyright (C) 2005, 2006 Christian Schoenebeck                        *
7   *                                                                         *   *                                                                         *
8   *   This program is free software; you can redistribute it and/or modify  *   *   This program is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# 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>(CONFIG_SYSEX_BUFFER_SIZE, 0);          pSysexBuffer       = new RingBuffer<uint8_t,false>(CONFIG_SYSEX_BUFFER_SIZE, 0);
101          pEventQueue        = new RingBuffer<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);          pEventQueue        = new RingBuffer<Event,false>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);
102          pEventPool         = new Pool<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT);          pEventPool         = new Pool<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT);
103          pVoicePool         = new Pool<Voice>(CONFIG_MAX_VOICES);          pVoicePool         = new Pool<Voice>(CONFIG_MAX_VOICES);
104          pVoiceStealingQueue = new RTList<Event>(pEventPool);          pVoiceStealingQueue = new RTList<Event>(pEventPool);
# 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();          ResetScaleTuning();
113      }      }
# Line 126  namespace LinuxSampler { namespace gig { Line 116  namespace LinuxSampler { namespace gig {
116       * Destructor       * Destructor
117       */       */
118      Engine::~Engine() {      Engine::~Engine() {
119            MidiInputPort::RemoveSysexListener(this);
120          if (pDiskThread) {          if (pDiskThread) {
121              dmsg(1,("Stopping disk thread..."));              dmsg(1,("Stopping disk thread..."));
122              pDiskThread->StopThread();              pDiskThread->StopThread();
# Line 139  namespace LinuxSampler { namespace gig { Line 130  namespace LinuxSampler { namespace gig {
130              delete pVoicePool;              delete pVoicePool;
131          }          }
132          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
         if (pMainFilterParameters) delete[] pMainFilterParameters;  
         if (pBasicFilterParameters) delete[] pBasicFilterParameters;  
         if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);  
133          if (pVoiceStealingQueue) delete pVoiceStealingQueue;          if (pVoiceStealingQueue) delete pVoiceStealingQueue;
134          if (pSysexBuffer) delete pSysexBuffer;          if (pSysexBuffer) delete pSysexBuffer;
135          EngineFactory::Destroy(this);          EngineFactory::Destroy(this);
# Line 178  namespace LinuxSampler { namespace gig { Line 166  namespace LinuxSampler { namespace gig {
166    
167      /**      /**
168       *  Reset all voices and disk thread and clear input event queue and all       *  Reset all voices and disk thread and clear input event queue and all
169       *  control and status variables. This method is not thread safe!       *  control and status variables. This method is protected by a mutex.
170       */       */
171      void Engine::ResetInternal() {      void Engine::ResetInternal() {
172            ResetInternalMutex.Lock();
173    
174            // make sure that the engine does not get any sysex messages
175            // while it's reseting
176            bool sysexDisabled = MidiInputPort::RemoveSysexListener(this);
177          ActiveVoiceCount    = 0;          ActiveVoiceCount    = 0;
178          ActiveVoiceCountMax = 0;          ActiveVoiceCountMax = 0;
179    
# Line 203  namespace LinuxSampler { namespace gig { Line 196  namespace LinuxSampler { namespace gig {
196    
197          // delete all input events          // delete all input events
198          pEventQueue->init();          pEventQueue->init();
199            pSysexBuffer->init();
200            if (sysexDisabled) MidiInputPort::AddSysexListener(this);
201            ResetInternalMutex.Unlock();
202      }      }
203    
204      /**      /**
# Line 232  namespace LinuxSampler { namespace gig { Line 228  namespace LinuxSampler { namespace gig {
228          }          }
229          catch (AudioOutputException e) {          catch (AudioOutputException e) {
230              String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();              String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();
231              throw LinuxSamplerException(msg);              throw Exception(msg);
232          }          }
233    
234          this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle();          this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle();
# Line 240  namespace LinuxSampler { namespace gig { Line 236  namespace LinuxSampler { namespace gig {
236    
237          // FIXME: audio drivers with varying fragment sizes might be a problem here          // FIXME: audio drivers with varying fragment sizes might be a problem here
238          MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * CONFIG_EG_MIN_RELEASE_TIME) - 1;          MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * CONFIG_EG_MIN_RELEASE_TIME) - 1;
239          if (MaxFadeOutPos < 0)          if (MaxFadeOutPos < 0) {
240              throw LinuxSamplerException("CONFIG_EG_MIN_RELEASE_TIME too big for current audio fragment size / sampling rate!");              std::cerr << "gig::Engine: WARNING, CONFIG_EG_MIN_RELEASE_TIME "
241                          << "too big for current audio fragment size & sampling rate! "
242                          << "May lead to click sounds if voice stealing chimes in!\n" << std::flush;
243                // force volume ramp downs at the beginning of each fragment
244                MaxFadeOutPos = 0;
245                // lower minimum release time
246                const float minReleaseTime = (float) MaxSamplesPerCycle / (float) SampleRate;
247                for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
248                    iterVoice->EG1.CalculateFadeOutCoeff(minReleaseTime, SampleRate);
249                }
250                pVoicePool->clear();
251            }
252    
253          // (re)create disk thread          // (re)create disk thread
254          if (this->pDiskThread) {          if (this->pDiskThread) {
# Line 266  namespace LinuxSampler { namespace gig { Line 273  namespace LinuxSampler { namespace gig {
273          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
274          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
275    
         // (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()];  
   
276          dmsg(1,("Starting disk thread..."));          dmsg(1,("Starting disk thread..."));
277          pDiskThread->StartThread();          pDiskThread->StartThread();
278          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
# Line 316  namespace LinuxSampler { namespace gig { Line 306  namespace LinuxSampler { namespace gig {
306       *                  current audio cycle       *                  current audio cycle
307       */       */
308      void Engine::ImportEvents(uint Samples) {      void Engine::ImportEvents(uint Samples) {
309          RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();          RingBuffer<Event,false>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
310          Event* pEvent;          Event* pEvent;
311          while (true) {          while (true) {
312              // get next event from input event queue              // get next event from input event queue
# Line 339  namespace LinuxSampler { namespace gig { Line 329  namespace LinuxSampler { namespace gig {
329      }      }
330    
331      /**      /**
332       *  Let this engine proceed to render the given amount of sample points. The       * Let this engine proceed to render the given amount of sample points.
333       *  calculated audio data of all voices of this engine will be placed into       * The engine will iterate through all engine channels and render audio
334       *  the engine's audio sum buffer which has to be copied and eventually be       * for each engine channel independently. The calculated audio data of
335       *  converted to the appropriate value range by the audio output class (e.g.       * all voices of each engine channel will be placed into the audio sum
336       *  AlsaIO or JackIO) right after.       * buffers of the respective audio output device, connected to the
337         * respective engine channel.
338       *       *
339       *  @param Samples - number of sample points to be rendered       *  @param Samples - number of sample points to be rendered
340       *  @returns       0 on success       *  @returns       0 on success
341       */       */
342      int Engine::RenderAudio(uint Samples) {      int Engine::RenderAudio(uint Samples) {
343          dmsg(5,("RenderAudio(Samples=%d)\n", Samples));          dmsg(7,("RenderAudio(Samples=%d)\n", Samples));
344    
345          // return if engine disabled          // return if engine disabled
346          if (EngineDisabled.Pop()) {          if (EngineDisabled.Pop()) {
# Line 360  namespace LinuxSampler { namespace gig { Line 351  namespace LinuxSampler { namespace gig {
351          // 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)
352          pEventGenerator->UpdateFragmentTime(Samples);          pEventGenerator->UpdateFragmentTime(Samples);
353    
354            // We only allow a maximum of CONFIG_MAX_VOICES voices to be spawned
355            // in each audio fragment. All subsequent request for spawning new
356            // voices in the same audio fragment will be ignored.
357            VoiceSpawnsLeft = CONFIG_MAX_VOICES;
358    
359          // 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
360          // (these are usually just SysEx messages)          // (these are usually just SysEx messages)
361          ImportEvents(Samples);          ImportEvents(Samples);
# Line 378  namespace LinuxSampler { namespace gig { Line 374  namespace LinuxSampler { namespace gig {
374              }              }
375          }          }
376    
         // We only allow a maximum of CONFIG_MAX_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 = CONFIG_MAX_VOICES;  
   
377          // reset internal voice counter (just for statistic of active voices)          // reset internal voice counter (just for statistic of active voices)
378          ActiveVoiceCountTemp = 0;          ActiveVoiceCountTemp = 0;
379    
   
380          // handle events on all engine channels          // handle events on all engine channels
381          for (int i = 0; i < engineChannels.size(); i++) {          for (int i = 0; i < engineChannels.size(); i++) {
382              if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded              if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
# Line 482  namespace LinuxSampler { namespace gig { Line 472  namespace LinuxSampler { namespace gig {
472       *                         this audio fragment cycle       *                         this audio fragment cycle
473       */       */
474      void Engine::RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {      void Engine::RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {
475            #if !CONFIG_PROCESS_MUTED_CHANNELS
476            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
477            #endif
478    
479          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
480          RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();          RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
481          while (iuiKey != end) { // iterate through all active keys          while (iuiKey != end) { // iterate through all active keys
# Line 520  namespace LinuxSampler { namespace gig { Line 514  namespace LinuxSampler { namespace gig {
514          for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {          for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
515              EngineChannel* pEngineChannel = (EngineChannel*) itVoiceStealEvent->pEngineChannel;              EngineChannel* pEngineChannel = (EngineChannel*) itVoiceStealEvent->pEngineChannel;
516              Pool<Voice>::Iterator itNewVoice =              Pool<Voice>::Iterator itNewVoice =
517                  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);
518              if (itNewVoice) {              if (itNewVoice) {
519                  itNewVoice->Render(Samples);                  itNewVoice->Render(Samples);
520                  if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active                  if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active
# Line 610  namespace LinuxSampler { namespace gig { Line 604  namespace LinuxSampler { namespace gig {
604       *  @param itNoteOnEvent - key, velocity and time stamp of the event       *  @param itNoteOnEvent - key, velocity and time stamp of the event
605       */       */
606      void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {      void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
607            #if !CONFIG_PROCESS_MUTED_CHANNELS
608            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
609            #endif
610    
611          const int key = itNoteOnEvent->Param.Note.Key;          const int key = itNoteOnEvent->Param.Note.Key;
612            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];
613    
614            // move note on event to the key's own event list
615            RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
616    
617            // if Solo Mode then kill all already active voices
618            if (pEngineChannel->SoloMode) {
619                Pool<uint>::Iterator itYoungestKey = pEngineChannel->pActiveKeys->last();
620                if (itYoungestKey) {
621                    const int iYoungestKey = *itYoungestKey;
622                    const midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[iYoungestKey];
623                    if (pOtherKey->Active) {
624                        // get final portamento position of currently active voice
625                        if (pEngineChannel->PortamentoMode) {
626                            RTList<Voice>::Iterator itVoice = pOtherKey->pActiveVoices->last();
627                            if (itVoice) itVoice->UpdatePortamentoPos(itNoteOnEventOnKeyList);
628                        }
629                        // kill all voices on the (other) key
630                        RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
631                        RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
632                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
633                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger)
634                                itVoiceToBeKilled->Kill(itNoteOnEventOnKeyList);
635                        }
636                    }
637                }
638                // set this key as 'currently active solo key'
639                pEngineChannel->SoloKey = key;
640            }
641    
642          // Change key dimension value if key is in keyswitching area          // Change key dimension value if key is in keyswitching area
643          {          {
644              const ::gig::Instrument* pInstrument = pEngineChannel->pInstrument;              const ::gig::Instrument* pInstrument = pEngineChannel->pInstrument;
645              if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high)              if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high)
646                  pEngineChannel->CurrentKeyDimension = ((key - pInstrument->DimensionKeyRange.low) * 128) /                  pEngineChannel->CurrentKeyDimension = float(key - pInstrument->DimensionKeyRange.low) /
647                      (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);                      (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);
648          }          }
649    
         midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];  
   
650          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
651          pKey->Velocity   = itNoteOnEvent->Param.Note.Velocity;          pKey->Velocity   = itNoteOnEventOnKeyList->Param.Note.Velocity;
652          pKey->NoteOnTime = FrameTime + itNoteOnEvent->FragmentPos(); // will be used to calculate note length          pKey->NoteOnTime = FrameTime + itNoteOnEventOnKeyList->FragmentPos(); // will be used to calculate note length
653    
654          // cancel release process of voices on this key if needed          // cancel release process of voices on this key if needed
655          if (pKey->Active && !pEngineChannel->SustainPedal) {          if (pKey->Active && !pEngineChannel->SustainPedal) {
656              RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();              RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
657              if (itCancelReleaseEvent) {              if (itCancelReleaseEvent) {
658                  *itCancelReleaseEvent = *itNoteOnEvent;                  // copy event                  *itCancelReleaseEvent = *itNoteOnEventOnKeyList;         // copy event
659                  itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type                  itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type
660              }              }
661              else dmsg(1,("Event pool emtpy!\n"));              else dmsg(1,("Event pool emtpy!\n"));
662          }          }
663    
         // move note on event to the key's own event list  
         RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);  
   
664          // allocate and trigger new voice(s) for the key          // allocate and trigger new voice(s) for the key
665          {          {
666              // first, get total amount of required voices (dependant on amount of layers)              // first, get total amount of required voices (dependant on amount of layers)
# Line 648  namespace LinuxSampler { namespace gig { Line 669  namespace LinuxSampler { namespace gig {
669                  int voicesRequired = pRegion->Layers;                  int voicesRequired = pRegion->Layers;
670                  // now launch the required amount of voices                  // now launch the required amount of voices
671                  for (int i = 0; i < voicesRequired; i++)                  for (int i = 0; i < voicesRequired; i++)
672                      LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true);                      LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true, true);
673              }              }
674          }          }
675    
# Line 656  namespace LinuxSampler { namespace gig { Line 677  namespace LinuxSampler { namespace gig {
677          if (!pKey->Active && !pKey->VoiceTheftsQueued)          if (!pKey->Active && !pKey->VoiceTheftsQueued)
678              pKey->pEvents->free(itNoteOnEventOnKeyList);              pKey->pEvents->free(itNoteOnEventOnKeyList);
679    
680            if (!pEngineChannel->SoloMode || pEngineChannel->PortamentoPos < 0.0f) pEngineChannel->PortamentoPos = (float) key;
681          pKey->RoundRobinIndex++;          pKey->RoundRobinIndex++;
682      }      }
683    
# Line 669  namespace LinuxSampler { namespace gig { Line 691  namespace LinuxSampler { namespace gig {
691       *  @param itNoteOffEvent - key, velocity and time stamp of the event       *  @param itNoteOffEvent - key, velocity and time stamp of the event
692       */       */
693      void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {      void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {
694          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];          #if !CONFIG_PROCESS_MUTED_CHANNELS
695            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
696            #endif
697    
698            const int iKey = itNoteOffEvent->Param.Note.Key;
699            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[iKey];
700          pKey->KeyPressed = false; // the MIDI key was now released          pKey->KeyPressed = false; // the MIDI key was now released
701    
702          // release voices on this key if needed          // move event to the key's own event list
703          if (pKey->Active && !pEngineChannel->SustainPedal) {          RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
704              itNoteOffEvent->Type = Event::type_release; // transform event type  
705            bool bShouldRelease = pKey->Active && ShouldReleaseVoice(pEngineChannel, itNoteOffEventOnKeyList->Param.Note.Key);
706    
707              // move event to the key's own event list          // in case Solo Mode is enabled, kill all voices on this key and respawn a voice on the highest pressed key (if any)
708              RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);          if (pEngineChannel->SoloMode) { //TODO: this feels like too much code just for handling solo mode :P
709                bool bOtherKeysPressed = false;
710                if (iKey == pEngineChannel->SoloKey) {
711                    pEngineChannel->SoloKey = -1;
712                    // if there's still a key pressed down, respawn a voice (group) on the highest key
713                    for (int i = 127; i > 0; i--) {
714                        midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[i];
715                        if (pOtherKey->KeyPressed) {
716                            bOtherKeysPressed = true;
717                            // make the other key the new 'currently active solo key'
718                            pEngineChannel->SoloKey = i;
719                            // get final portamento position of currently active voice
720                            if (pEngineChannel->PortamentoMode) {
721                                RTList<Voice>::Iterator itVoice = pKey->pActiveVoices->first();
722                                if (itVoice) itVoice->UpdatePortamentoPos(itNoteOffEventOnKeyList);
723                            }
724                            // create a pseudo note on event
725                            RTList<Event>::Iterator itPseudoNoteOnEvent = pOtherKey->pEvents->allocAppend();
726                            if (itPseudoNoteOnEvent) {
727                                // copy event
728                                *itPseudoNoteOnEvent = *itNoteOffEventOnKeyList;
729                                // transform event to a note on event
730                                itPseudoNoteOnEvent->Type                = Event::type_note_on;
731                                itPseudoNoteOnEvent->Param.Note.Key      = i;
732                                itPseudoNoteOnEvent->Param.Note.Velocity = pOtherKey->Velocity;
733                                // allocate and trigger new voice(s) for the other key
734                                {
735                                    // first, get total amount of required voices (dependant on amount of layers)
736                                    ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(i);
737                                    if (pRegion) {
738                                        int voicesRequired = pRegion->Layers;
739                                        // now launch the required amount of voices
740                                        for (int iLayer = 0; iLayer < voicesRequired; iLayer++)
741                                            LaunchVoice(pEngineChannel, itPseudoNoteOnEvent, iLayer, false, true, false);
742                                    }
743                                }
744                                // if neither a voice was spawned or postponed then remove note on event from key again
745                                if (!pOtherKey->Active && !pOtherKey->VoiceTheftsQueued)
746                                    pOtherKey->pEvents->free(itPseudoNoteOnEvent);
747    
748                            } else dmsg(1,("Could not respawn voice, no free event left\n"));
749                            break; // done
750                        }
751                    }
752                }
753                if (bOtherKeysPressed) {
754                    if (pKey->Active) { // kill all voices on this key
755                        bShouldRelease = false; // no need to release, as we kill it here
756                        RTList<Voice>::Iterator itVoiceToBeKilled = pKey->pActiveVoices->first();
757                        RTList<Voice>::Iterator end               = pKey->pActiveVoices->end();
758                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
759                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger)
760                                itVoiceToBeKilled->Kill(itNoteOffEventOnKeyList);
761                        }
762                    }
763                } else pEngineChannel->PortamentoPos = -1.0f;
764            }
765    
766            // if no solo mode (the usual case) or if solo mode and no other key pressed, then release voices on this key if needed
767            if (bShouldRelease) {
768                itNoteOffEventOnKeyList->Type = Event::type_release; // transform event type
769    
770              // spawn release triggered voice(s) if needed              // spawn release triggered voice(s) if needed
771              if (pKey->ReleaseTrigger) {              if (pKey->ReleaseTrigger) {
# Line 692  namespace LinuxSampler { namespace gig { Line 779  namespace LinuxSampler { namespace gig {
779    
780                      // now launch the required amount of voices                      // now launch the required amount of voices
781                      for (int i = 0; i < voicesRequired; i++)                      for (int i = 0; i < voicesRequired; i++)
782                          LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, i, true, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples                          LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, i, true, false, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
783                  }                  }
784                  pKey->ReleaseTrigger = false;                  pKey->ReleaseTrigger = false;
785              }              }
   
             // if neither a voice was spawned or postponed then remove note off event from key again  
             if (!pKey->Active && !pKey->VoiceTheftsQueued)  
                 pKey->pEvents->free(itNoteOffEventOnKeyList);  
786          }          }
787    
788            // if neither a voice was spawned or postponed on this key then remove note off event from key again
789            if (!pKey->Active && !pKey->VoiceTheftsQueued)
790                pKey->pEvents->free(itNoteOffEventOnKeyList);
791      }      }
792    
793      /**      /**
794       *  Moves pitchbend event from the general (input) event list to the pitch       *  Moves pitchbend event from the general (input) event list to the engine
795       *  event list.       *  channel's event list. It will actually processed later by the
796         *  respective voice.
797       *       *
798       *  @param pEngineChannel - engine channel on which this event occured on       *  @param pEngineChannel - engine channel on which this event occured on
799       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event
800       */       */
801      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {
802          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]);  
803      }      }
804    
805      /**      /**
# Line 729  namespace LinuxSampler { namespace gig { Line 816  namespace LinuxSampler { namespace gig {
816       *  @param VoiceStealing       - if voice stealing should be performed       *  @param VoiceStealing       - if voice stealing should be performed
817       *                               when there is no free voice       *                               when there is no free voice
818       *                               (optional, default = true)       *                               (optional, default = true)
819         *  @param HandleKeyGroupConflicts - if voices should be killed due to a
820         *                                   key group conflict
821       *  @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
822       *           if the voice wasn't triggered (for example when no region is       *           if the voice wasn't triggered (for example when no region is
823       *           defined for the given key).       *           defined for the given key).
824       */       */
825      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) {
826          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];          int MIDIKey            = itNoteOnEvent->Param.Note.Key;
827            midi_key_info_t* pKey  = &pEngineChannel->pMIDIKeyInfo[MIDIKey];
828            ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(MIDIKey);
829    
830            // if nothing defined for this key
831            if (!pRegion) return Pool<Voice>::Iterator(); // nothing to do
832    
833            // only mark the first voice of a layered voice (group) to be in a
834            // key group, so the layered voices won't kill each other
835            int iKeyGroup = (iLayer == 0 && !ReleaseTriggerVoice) ? pRegion->KeyGroup : 0;
836    
837            // handle key group (a.k.a. exclusive group) conflicts
838            if (HandleKeyGroupConflicts) {
839                if (iKeyGroup) { // if this voice / key belongs to a key group
840                    uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[iKeyGroup];
841                    if (*ppKeyGroup) { // if there's already an active key in that key group
842                        midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[**ppKeyGroup];
843                        // kill all voices on the (other) key
844                        RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
845                        RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
846                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
847                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger) {
848                                itVoiceToBeKilled->Kill(itNoteOnEvent);
849                                --VoiceSpawnsLeft; //FIXME: just a hack, we should better check in StealVoice() if the voice was killed due to key conflict
850                            }
851                        }
852                    }
853                }
854            }
855    
856            Voice::type_t VoiceType = Voice::type_normal;
857    
858            // get current dimension values to select the right dimension region
859            //TODO: for stolen voices this dimension region selection block is processed twice, this should be changed
860            //FIXME: controller values for selecting the dimension region here are currently not sample accurate
861            uint DimValues[8] = { 0 };
862            for (int i = pRegion->Dimensions - 1; i >= 0; i--) {
863                switch (pRegion->pDimensionDefinitions[i].dimension) {
864                    case ::gig::dimension_samplechannel:
865                        DimValues[i] = 0; //TODO: we currently ignore this dimension
866                        break;
867                    case ::gig::dimension_layer:
868                        DimValues[i] = iLayer;
869                        break;
870                    case ::gig::dimension_velocity:
871                        DimValues[i] = itNoteOnEvent->Param.Note.Velocity;
872                        break;
873                    case ::gig::dimension_channelaftertouch:
874                        DimValues[i] = pEngineChannel->ControllerTable[128];
875                        break;
876                    case ::gig::dimension_releasetrigger:
877                        VoiceType = (ReleaseTriggerVoice) ? Voice::type_release_trigger : (!iLayer) ? Voice::type_release_trigger_required : Voice::type_normal;
878                        DimValues[i] = (uint) ReleaseTriggerVoice;
879                        break;
880                    case ::gig::dimension_keyboard:
881                        DimValues[i] = (uint) (pEngineChannel->CurrentKeyDimension * pRegion->pDimensionDefinitions[i].zones);
882                        break;
883                    case ::gig::dimension_roundrobin:
884                        DimValues[i] = (uint) pEngineChannel->pMIDIKeyInfo[MIDIKey].RoundRobinIndex; // incremented for each note on
885                        break;
886                    case ::gig::dimension_random:
887                        RandomSeed   = RandomSeed * 1103515245 + 12345; // classic pseudo random number generator
888                        DimValues[i] = (uint) RandomSeed >> (32 - pRegion->pDimensionDefinitions[i].bits); // highest bits are most random
889                        break;
890                    case ::gig::dimension_modwheel:
891                        DimValues[i] = pEngineChannel->ControllerTable[1];
892                        break;
893                    case ::gig::dimension_breath:
894                        DimValues[i] = pEngineChannel->ControllerTable[2];
895                        break;
896                    case ::gig::dimension_foot:
897                        DimValues[i] = pEngineChannel->ControllerTable[4];
898                        break;
899                    case ::gig::dimension_portamentotime:
900                        DimValues[i] = pEngineChannel->ControllerTable[5];
901                        break;
902                    case ::gig::dimension_effect1:
903                        DimValues[i] = pEngineChannel->ControllerTable[12];
904                        break;
905                    case ::gig::dimension_effect2:
906                        DimValues[i] = pEngineChannel->ControllerTable[13];
907                        break;
908                    case ::gig::dimension_genpurpose1:
909                        DimValues[i] = pEngineChannel->ControllerTable[16];
910                        break;
911                    case ::gig::dimension_genpurpose2:
912                        DimValues[i] = pEngineChannel->ControllerTable[17];
913                        break;
914                    case ::gig::dimension_genpurpose3:
915                        DimValues[i] = pEngineChannel->ControllerTable[18];
916                        break;
917                    case ::gig::dimension_genpurpose4:
918                        DimValues[i] = pEngineChannel->ControllerTable[19];
919                        break;
920                    case ::gig::dimension_sustainpedal:
921                        DimValues[i] = pEngineChannel->ControllerTable[64];
922                        break;
923                    case ::gig::dimension_portamento:
924                        DimValues[i] = pEngineChannel->ControllerTable[65];
925                        break;
926                    case ::gig::dimension_sostenutopedal:
927                        DimValues[i] = pEngineChannel->ControllerTable[66];
928                        break;
929                    case ::gig::dimension_softpedal:
930                        DimValues[i] = pEngineChannel->ControllerTable[67];
931                        break;
932                    case ::gig::dimension_genpurpose5:
933                        DimValues[i] = pEngineChannel->ControllerTable[80];
934                        break;
935                    case ::gig::dimension_genpurpose6:
936                        DimValues[i] = pEngineChannel->ControllerTable[81];
937                        break;
938                    case ::gig::dimension_genpurpose7:
939                        DimValues[i] = pEngineChannel->ControllerTable[82];
940                        break;
941                    case ::gig::dimension_genpurpose8:
942                        DimValues[i] = pEngineChannel->ControllerTable[83];
943                        break;
944                    case ::gig::dimension_effect1depth:
945                        DimValues[i] = pEngineChannel->ControllerTable[91];
946                        break;
947                    case ::gig::dimension_effect2depth:
948                        DimValues[i] = pEngineChannel->ControllerTable[92];
949                        break;
950                    case ::gig::dimension_effect3depth:
951                        DimValues[i] = pEngineChannel->ControllerTable[93];
952                        break;
953                    case ::gig::dimension_effect4depth:
954                        DimValues[i] = pEngineChannel->ControllerTable[94];
955                        break;
956                    case ::gig::dimension_effect5depth:
957                        DimValues[i] = pEngineChannel->ControllerTable[95];
958                        break;
959                    case ::gig::dimension_none:
960                        std::cerr << "gig::Engine::LaunchVoice() Error: dimension=none\n" << std::flush;
961                        break;
962                    default:
963                        std::cerr << "gig::Engine::LaunchVoice() Error: Unknown dimension\n" << std::flush;
964                }
965            }
966            ::gig::DimensionRegion* pDimRgn = pRegion->GetDimensionRegionByValue(DimValues);
967    
968            // no need to continue if sample is silent
969            if (!pDimRgn->pSample || !pDimRgn->pSample->SamplesTotal) return Pool<Voice>::Iterator();
970    
971          // allocate a new voice for the key          // allocate a new voice for the key
972          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
973          if (itNewVoice) {          if (itNewVoice) {
974              // launch the new voice              // launch the new voice
975              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pEngineChannel->pInstrument, iLayer, ReleaseTriggerVoice, VoiceStealing) < 0) {              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pDimRgn, VoiceType, iKeyGroup) < 0) {
976                  dmsg(4,("Voice not triggered\n"));                  dmsg(4,("Voice not triggered\n"));
977                  pKey->pActiveVoices->free(itNewVoice);                  pKey->pActiveVoices->free(itNewVoice);
978              }              }
979              else { // on success              else { // on success
980                  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);  
                         }  
                     }  
                 }  
981                  if (!pKey->Active) { // mark as active key                  if (!pKey->Active) { // mark as active key
982                      pKey->Active = true;                      pKey->Active = true;
983                      pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();                      pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();
984                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
985                  }                  }
986                  if (itNewVoice->KeyGroup) {                  if (itNewVoice->KeyGroup) {
987                        uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup];
988                      *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
989                  }                  }
990                  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 800  namespace LinuxSampler { namespace gig { Line 1021  namespace LinuxSampler { namespace gig {
1021       *  @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
1022       */       */
1023      int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {      int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
1024          if (!VoiceTheftsLeft) {          if (VoiceSpawnsLeft <= 0) {
1025              dmsg(1,("Max. voice thefts per audio fragment reached (you may raise CONFIG_MAX_VOICES).\n"));              dmsg(1,("Max. voice thefts per audio fragment reached (you may raise CONFIG_MAX_VOICES).\n"));
1026              return -1;              return -1;
1027          }          }
# Line 819  namespace LinuxSampler { namespace gig { Line 1040  namespace LinuxSampler { namespace gig {
1040                      midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];                      midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
1041                      itSelectedVoice = pSelectedKey->pActiveVoices->first();                      itSelectedVoice = pSelectedKey->pActiveVoices->first();
1042                      // proceed iterating if voice was created in this fragment cycle                      // proceed iterating if voice was created in this fragment cycle
1043                      while (itSelectedVoice && !itSelectedVoice->hasRendered()) ++itSelectedVoice;                      while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1044                      // if we haven't found a voice then proceed with algorithm 'oldestkey'                      // if we haven't found a voice then proceed with algorithm 'oldestkey'
1045                      if (itSelectedVoice && itSelectedVoice->hasRendered()) break;                      if (itSelectedVoice && itSelectedVoice->IsStealable()) break;
1046                  } // no break - intentional !                  } // no break - intentional !
1047    
1048                  // try to pick the oldest voice on the oldest active key                  // try to pick the oldest voice on the oldest active key
# Line 833  namespace LinuxSampler { namespace gig { Line 1054  namespace LinuxSampler { namespace gig {
1054                          itSelectedVoice = this->itLastStolenVoice;                          itSelectedVoice = this->itLastStolenVoice;
1055                          do {                          do {
1056                              ++itSelectedVoice;                              ++itSelectedVoice;
1057                          } while (itSelectedVoice && !itSelectedVoice->hasRendered()); // proceed iterating if voice was created in this fragment cycle                          } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1058                          // found a "stealable" voice ?                          // found a "stealable" voice ?
1059                          if (itSelectedVoice && itSelectedVoice->hasRendered()) {                          if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1060                              // remember which voice we stole, so we can simply proceed on next voice stealing                              // remember which voice we stole, so we can simply proceed on next voice stealing
1061                              this->itLastStolenVoice = itSelectedVoice;                              this->itLastStolenVoice = itSelectedVoice;
1062                              break; // selection succeeded                              break; // selection succeeded
# Line 847  namespace LinuxSampler { namespace gig { Line 1068  namespace LinuxSampler { namespace gig {
1068                          midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];                          midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];
1069                          itSelectedVoice = pSelectedKey->pActiveVoices->first();                          itSelectedVoice = pSelectedKey->pActiveVoices->first();
1070                          // proceed iterating if voice was created in this fragment cycle                          // proceed iterating if voice was created in this fragment cycle
1071                          while (itSelectedVoice && !itSelectedVoice->hasRendered()) ++itSelectedVoice;                          while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1072                          // found a "stealable" voice ?                          // found a "stealable" voice ?
1073                          if (itSelectedVoice && itSelectedVoice->hasRendered()) {                          if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1074                              // remember which voice on which key we stole, so we can simply proceed on next voice stealing                              // remember which voice on which key we stole, so we can simply proceed on next voice stealing
1075                              this->iuiLastStolenKey  = iuiSelectedKey;                              this->iuiLastStolenKey  = iuiSelectedKey;
1076                              this->itLastStolenVoice = itSelectedVoice;                              this->itLastStolenVoice = itSelectedVoice;
# Line 871  namespace LinuxSampler { namespace gig { Line 1092  namespace LinuxSampler { namespace gig {
1092              // if we couldn't steal a voice from the same engine channel then              // if we couldn't steal a voice from the same engine channel then
1093              // steal oldest voice on the oldest key from any other engine channel              // steal oldest voice on the oldest key from any other engine channel
1094              // (the smaller engine channel number, the higher priority)              // (the smaller engine channel number, the higher priority)
1095              if (!itSelectedVoice || !itSelectedVoice->hasRendered()) {              if (!itSelectedVoice || !itSelectedVoice->IsStealable()) {
1096                  EngineChannel* pSelectedChannel;                  EngineChannel* pSelectedChannel;
1097                  int            iChannelIndex;                  int            iChannelIndex;
1098                  // select engine channel                  // select engine channel
# Line 882  namespace LinuxSampler { namespace gig { Line 1103  namespace LinuxSampler { namespace gig {
1103                      iChannelIndex    = (pEngineChannel->iEngineIndexSelf + 1) % engineChannels.size();                      iChannelIndex    = (pEngineChannel->iEngineIndexSelf + 1) % engineChannels.size();
1104                      pSelectedChannel = engineChannels[iChannelIndex];                      pSelectedChannel = engineChannels[iChannelIndex];
1105                  }                  }
1106                  // iterate through engine channels  
1107                  while (true) {                  // if we already stole in this fragment, try to proceed on same key
1108                      // if we already stole in this fragment, try to proceed on same key                  if (this->itLastStolenVoiceGlobally) {
1109                      if (this->itLastStolenVoiceGlobally) {                      itSelectedVoice = this->itLastStolenVoiceGlobally;
1110                          itSelectedVoice = this->itLastStolenVoiceGlobally;                      do {
1111                          do {                          ++itSelectedVoice;
1112                              ++itSelectedVoice;                      } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1113                          } while (itSelectedVoice && !itSelectedVoice->hasRendered()); // proceed iterating if voice was created in this fragment cycle                  }
1114                          // break if selection succeeded  
1115                          if (itSelectedVoice && itSelectedVoice->hasRendered()) {                  #if CONFIG_DEVMODE
1116                              // remember which voice we stole, so we can simply proceed on next voice stealing                  EngineChannel* pBegin = pSelectedChannel; // to detect endless loop
1117                              this->itLastStolenVoiceGlobally = itSelectedVoice;                  #endif // CONFIG_DEVMODE
1118                              break; // selection succeeded  
1119                          }                  // did we find a 'stealable' voice?
1120                      }                  if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1121                        // remember which voice we stole, so we can simply proceed on next voice stealing
1122                        this->itLastStolenVoiceGlobally = itSelectedVoice;
1123                    } else while (true) { // iterate through engine channels
1124                      // get (next) oldest key                      // get (next) oldest key
1125                      RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKey) ? ++this->iuiLastStolenKey : pSelectedChannel->pActiveKeys->first();                      RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKeyGlobally) ? ++this->iuiLastStolenKeyGlobally : pSelectedChannel->pActiveKeys->first();
1126                        this->iuiLastStolenKeyGlobally = RTList<uint>::Iterator(); // to prevent endless loop (see line above)
1127                      while (iuiSelectedKey) {                      while (iuiSelectedKey) {
1128                          midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];                          midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];
1129                          itSelectedVoice = pSelectedKey->pActiveVoices->first();                          itSelectedVoice = pSelectedKey->pActiveVoices->first();
1130                          // proceed iterating if voice was created in this fragment cycle                          // proceed iterating if voice was created in this fragment cycle
1131                          while (itSelectedVoice && !itSelectedVoice->hasRendered()) ++itSelectedVoice;                          while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1132                          // found a "stealable" voice ?                          // found a "stealable" voice ?
1133                          if (itSelectedVoice && itSelectedVoice->hasRendered()) {                          if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1134                              // remember which voice on which key on which engine channel we stole, so we can simply proceed on next voice stealing                              // remember which voice on which key on which engine channel we stole, so we can simply proceed on next voice stealing
1135                              this->iuiLastStolenKeyGlobally  = iuiSelectedKey;                              this->iuiLastStolenKeyGlobally  = iuiSelectedKey;
1136                              this->itLastStolenVoiceGlobally = itSelectedVoice;                              this->itLastStolenVoiceGlobally = itSelectedVoice;
1137                              this->pLastStolenChannel        = pSelectedChannel;                              this->pLastStolenChannel        = pSelectedChannel;
1138                              break; // selection succeeded                              goto stealable_voice_found; // selection succeeded
1139                          }                          }
1140                          ++iuiSelectedKey; // get next key on current engine channel                          ++iuiSelectedKey; // get next key on current engine channel
1141                      }                      }
1142                      // get next engine channel                      // get next engine channel
1143                      iChannelIndex    = (iChannelIndex + 1) % engineChannels.size();                      iChannelIndex    = (iChannelIndex + 1) % engineChannels.size();
1144                      pSelectedChannel = engineChannels[iChannelIndex];                      pSelectedChannel = engineChannels[iChannelIndex];
1145    
1146                        #if CONFIG_DEVMODE
1147                        if (pSelectedChannel == pBegin) {
1148                            dmsg(1,("FATAL ERROR: voice stealing endless loop!\n"));
1149                            dmsg(1,("VoiceSpawnsLeft=%d.\n", VoiceSpawnsLeft));
1150                            dmsg(1,("Exiting.\n"));
1151                            exit(-1);
1152                        }
1153                        #endif // CONFIG_DEVMODE
1154                  }                  }
1155              }              }
1156    
1157                // jump point if a 'stealable' voice was found
1158                stealable_voice_found:
1159    
1160              #if CONFIG_DEVMODE              #if CONFIG_DEVMODE
1161              if (!itSelectedVoice->IsActive()) {              if (!itSelectedVoice->IsActive()) {
1162                  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"));
# Line 930  namespace LinuxSampler { namespace gig { Line 1167  namespace LinuxSampler { namespace gig {
1167              // now kill the selected voice              // now kill the selected voice
1168              itSelectedVoice->Kill(itNoteOnEvent);              itSelectedVoice->Kill(itNoteOnEvent);
1169    
1170              --VoiceTheftsLeft;              --VoiceSpawnsLeft;
1171    
1172              return 0; // success              return 0; // success
1173          }          }
# Line 999  namespace LinuxSampler { namespace gig { Line 1236  namespace LinuxSampler { namespace gig {
1236          // update controller value in the engine channel's controller table          // update controller value in the engine channel's controller table
1237          pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;          pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
1238    
1239          // move event from the unsorted event list to the control change event list          switch (itControlChangeEvent->Param.CC.Controller) {
1240          Pool<Event>::Iterator itControlChangeEventOnCCList = itControlChangeEvent.moveToEndOf(pEngineChannel->pCCEvents);              case 5: { // portamento time
1241                    pEngineChannel->PortamentoTime = (float) itControlChangeEvent->Param.CC.Value / 127.0f * (float) CONFIG_PORTAMENTO_TIME_MAX + (float) CONFIG_PORTAMENTO_TIME_MIN;
1242          switch (itControlChangeEventOnCCList->Param.CC.Controller) {                  break;
1243                }
1244              case 7: { // volume              case 7: { // volume
1245                  //TODO: not sample accurate yet                  //TODO: not sample accurate yet
1246                  pEngineChannel->GlobalVolume = (float) itControlChangeEventOnCCList->Param.CC.Value / 127.0f;                  pEngineChannel->MidiVolume = VolumeCurve[itControlChangeEvent->Param.CC.Value];
1247                    pEngineChannel->bStatusChanged = true; // engine channel status has changed, so set notify flag
1248                  break;                  break;
1249              }              }
1250              case 10: { // panpot              case 10: { // panpot
1251                  //TODO: not sample accurate yet                  //TODO: not sample accurate yet
1252                  const int pan = (int) itControlChangeEventOnCCList->Param.CC.Value - 64;                  pEngineChannel->GlobalPanLeft  = PanCurve[128 - itControlChangeEvent->Param.CC.Value];
1253                  pEngineChannel->GlobalPanLeft  = 1.0f - float(RTMath::Max(pan, 0)) /  63.0f;                  pEngineChannel->GlobalPanRight = PanCurve[itControlChangeEvent->Param.CC.Value];
                 pEngineChannel->GlobalPanRight = 1.0f - float(RTMath::Min(pan, 0)) / -64.0f;  
1254                  break;                  break;
1255              }              }
1256              case 64: { // sustain              case 64: { // sustain
1257                  if (itControlChangeEventOnCCList->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {
1258                      dmsg(4,("PEDAL DOWN\n"));                      dmsg(4,("DAMPER (RIGHT) PEDAL DOWN\n"));
1259                      pEngineChannel->SustainPedal = true;                      pEngineChannel->SustainPedal = true;
1260    
1261                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1262                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1263                        #endif
1264    
1265                      // cancel release process of voices if necessary                      // cancel release process of voices if necessary
1266                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1267                      for (; iuiKey; ++iuiKey) {                      for (; iuiKey; ++iuiKey) {
# Line 1027  namespace LinuxSampler { namespace gig { Line 1269  namespace LinuxSampler { namespace gig {
1269                          if (!pKey->KeyPressed) {                          if (!pKey->KeyPressed) {
1270                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1271                              if (itNewEvent) {                              if (itNewEvent) {
1272                                  *itNewEvent = *itControlChangeEventOnCCList; // copy event to the key's own event list                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1273                                  itNewEvent->Type = Event::type_cancel_release; // transform event type                                  itNewEvent->Type = Event::type_cancel_release; // transform event type
1274                              }                              }
1275                              else dmsg(1,("Event pool emtpy!\n"));                              else dmsg(1,("Event pool emtpy!\n"));
1276                          }                          }
1277                      }                      }
1278                  }                  }
1279                  if (itControlChangeEventOnCCList->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {
1280                      dmsg(4,("PEDAL UP\n"));                      dmsg(4,("DAMPER (RIGHT) PEDAL UP\n"));
1281                      pEngineChannel->SustainPedal = false;                      pEngineChannel->SustainPedal = false;
1282    
1283                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1284                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1285                        #endif
1286    
1287                      // release voices if their respective key is not pressed                      // release voices if their respective key is not pressed
1288                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1289                      for (; iuiKey; ++iuiKey) {                      for (; iuiKey; ++iuiKey) {
1290                          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];                          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1291                          if (!pKey->KeyPressed) {                          if (!pKey->KeyPressed && ShouldReleaseVoice(pEngineChannel, *iuiKey)) {
1292                                RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1293                                if (itNewEvent) {
1294                                    *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1295                                    itNewEvent->Type = Event::type_release; // transform event type
1296                                }
1297                                else dmsg(1,("Event pool emtpy!\n"));
1298                            }
1299                        }
1300                    }
1301                    break;
1302                }
1303                case 65: { // portamento on / off
1304                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1305                    pEngineChannel->PortamentoMode = itControlChangeEvent->Param.CC.Value >= 64;
1306                    break;
1307                }
1308                case 66: { // sostenuto
1309                    if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SostenutoPedal) {
1310                        dmsg(4,("SOSTENUTO (CENTER) PEDAL DOWN\n"));
1311                        pEngineChannel->SostenutoPedal = true;
1312    
1313                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1314                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1315                        #endif
1316    
1317                        SostenutoKeyCount = 0;
1318                        // Remeber the pressed keys
1319                        RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1320                        for (; iuiKey; ++iuiKey) {
1321                            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1322                            if (pKey->KeyPressed && SostenutoKeyCount < 128) SostenutoKeys[SostenutoKeyCount++] = *iuiKey;
1323                        }
1324                    }
1325                    if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SostenutoPedal) {
1326                        dmsg(4,("SOSTENUTO (CENTER) PEDAL UP\n"));
1327                        pEngineChannel->SostenutoPedal = false;
1328    
1329                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1330                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1331                        #endif
1332    
1333                        // release voices if the damper pedal is up and their respective key is not pressed
1334                        for (int i = 0; i < SostenutoKeyCount; i++) {
1335                            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[SostenutoKeys[i]];
1336                            if (!pKey->KeyPressed && !pEngineChannel->SustainPedal) {
1337                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1338                              if (itNewEvent) {                              if (itNewEvent) {
1339                                  *itNewEvent = *itControlChangeEventOnCCList; // copy event to the key's own event list                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1340                                  itNewEvent->Type = Event::type_release; // transform event type                                  itNewEvent->Type = Event::type_release; // transform event type
1341                              }                              }
1342                              else dmsg(1,("Event pool emtpy!\n"));                              else dmsg(1,("Event pool emtpy!\n"));
# Line 1059  namespace LinuxSampler { namespace gig { Line 1350  namespace LinuxSampler { namespace gig {
1350              // Channel Mode Messages              // Channel Mode Messages
1351    
1352              case 120: { // all sound off              case 120: { // all sound off
1353                  KillAllVoices(pEngineChannel, itControlChangeEventOnCCList);                  KillAllVoices(pEngineChannel, itControlChangeEvent);
1354                  break;                  break;
1355              }              }
1356              case 121: { // reset all controllers              case 121: { // reset all controllers
# Line 1067  namespace LinuxSampler { namespace gig { Line 1358  namespace LinuxSampler { namespace gig {
1358                  break;                  break;
1359              }              }
1360              case 123: { // all notes off              case 123: { // all notes off
1361                  ReleaseAllVoices(pEngineChannel, itControlChangeEventOnCCList);                  #if CONFIG_PROCESS_ALL_NOTES_OFF
1362                    ReleaseAllVoices(pEngineChannel, itControlChangeEvent);
1363                    #endif // CONFIG_PROCESS_ALL_NOTES_OFF
1364                    break;
1365                }
1366                case 126: { // mono mode on
1367                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1368                    pEngineChannel->SoloMode = true;
1369                    break;
1370                }
1371                case 127: { // poly mode on
1372                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1373                    pEngineChannel->SoloMode = false;
1374                  break;                  break;
1375              }              }
1376          }          }
# Line 1079  namespace LinuxSampler { namespace gig { Line 1382  namespace LinuxSampler { namespace gig {
1382       *  @param itSysexEvent - sysex data size and time stamp of the sysex event       *  @param itSysexEvent - sysex data size and time stamp of the sysex event
1383       */       */
1384      void Engine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) {      void Engine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) {
1385          RingBuffer<uint8_t>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();          RingBuffer<uint8_t,false>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();
1386    
1387          uint8_t exclusive_status, id;          uint8_t exclusive_status, id;
1388          if (!reader.pop(&exclusive_status)) goto free_sysex_data;          if (!reader.pop(&exclusive_status)) goto free_sysex_data;
# Line 1098  namespace LinuxSampler { namespace gig { Line 1401  namespace LinuxSampler { namespace gig {
1401    
1402                  // command address                  // command address
1403                  uint8_t addr[3]; // 2 byte addr MSB, followed by 1 byte addr LSB)                  uint8_t addr[3]; // 2 byte addr MSB, followed by 1 byte addr LSB)
1404                  const RingBuffer<uint8_t>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later                  const RingBuffer<uint8_t,false>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later
1405                  if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;                  if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;
1406                  if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters                  if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters
1407                      dmsg(3,("\tSystem Parameter\n"));                      dmsg(3,("\tSystem Parameter\n"));
# Line 1145  namespace LinuxSampler { namespace gig { Line 1448  namespace LinuxSampler { namespace gig {
1448       *                     question       *                     question
1449       * @param DataSize   - size of the GS message data (in bytes)       * @param DataSize   - size of the GS message data (in bytes)
1450       */       */
1451      uint8_t Engine::GSCheckSum(const RingBuffer<uint8_t>::NonVolatileReader AddrReader, uint DataSize) {      uint8_t Engine::GSCheckSum(const RingBuffer<uint8_t,false>::NonVolatileReader AddrReader, uint DataSize) {
1452          RingBuffer<uint8_t>::NonVolatileReader reader = AddrReader;          RingBuffer<uint8_t,false>::NonVolatileReader reader = AddrReader;
1453          uint bytes = 3 /*addr*/ + DataSize;          uint bytes = 3 /*addr*/ + DataSize;
1454          uint8_t addr_and_data[bytes];          uint8_t addr_and_data[bytes];
1455          reader.read(&addr_and_data[0], bytes);          reader.read(&addr_and_data[0], bytes);
# Line 1205  namespace LinuxSampler { namespace gig { Line 1508  namespace LinuxSampler { namespace gig {
1508              RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();              RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
1509              for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key              for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
1510                  itVoice->Kill(itKillEvent);                  itVoice->Kill(itKillEvent);
1511                    --VoiceSpawnsLeft; //FIXME: just a temporary workaround, we should check the cause in StealVoice() instead
1512              }              }
1513          }          }
1514      }      }
1515    
1516      /**      /**
1517       * Initialize the parameter sequence for the modulation destination given by       * Determines whether the specified voice should be released.
1518       * by 'dst' with the constant value given by val.       *
1519         * @param pEngineChannel - The engine channel on which the voice should be checked
1520         * @param Key - The key number
1521         * @returns true if the specified should be released, false otherwise.
1522       */       */
1523      void Engine::ResetSynthesisParameters(Event::destination_t dst, float val) {      bool Engine::ShouldReleaseVoice(EngineChannel* pEngineChannel, int Key) {
1524          int maxsamples = pAudioOutputDevice->MaxSamplesPerCycle();          if (pEngineChannel->SustainPedal) return false;
1525          float* m = &pSynthesisParameters[dst][0];  
1526          for (int i = 0; i < maxsamples; i += 4) {          if (pEngineChannel->SostenutoPedal) {
1527             m[i]   = val;              for (int i = 0; i < SostenutoKeyCount; i++)
1528             m[i+1] = val;                  if (Key == SostenutoKeys[i]) return false;
            m[i+2] = val;  
            m[i+3] = val;  
1529          }          }
1530    
1531            return true;
1532      }      }
1533    
1534      uint Engine::VoiceCount() {      uint Engine::VoiceCount() {
# Line 1261  namespace LinuxSampler { namespace gig { Line 1568  namespace LinuxSampler { namespace gig {
1568      }      }
1569    
1570      String Engine::Version() {      String Engine::Version() {
1571          String s = "$Revision: 1.42 $";          String s = "$Revision: 1.67 $";
1572          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
1573      }      }
1574    
1575        InstrumentManager* Engine::GetInstrumentManager() {
1576            return &instruments;
1577        }
1578    
1579        // static constant initializers
1580        const float* Engine::VolumeCurve(InitVolumeCurve());
1581        const float* Engine::PanCurve(InitPanCurve());
1582        const float* Engine::CrossfadeCurve(InitCrossfadeCurve());
1583    
1584        float* Engine::InitVolumeCurve() {
1585            // line-segment approximation
1586            const float segments[] = {
1587                0, 0, 2, 0.0046, 16, 0.016, 31, 0.051, 45, 0.115, 54.5, 0.2,
1588                64.5, 0.39, 74, 0.74, 92, 1.03, 114, 1.94, 119.2, 2.2, 127, 2.2
1589            };
1590            return InitCurve(segments);
1591        }
1592    
1593        float* Engine::InitPanCurve() {
1594            // line-segment approximation
1595            const float segments[] = {
1596                0, 0, 1, 0,
1597                2, 0.05, 31.5, 0.7, 51, 0.851, 74.5, 1.12,
1598                127, 1.41, 128, 1.41
1599            };
1600            return InitCurve(segments, 129);
1601        }
1602    
1603        float* Engine::InitCrossfadeCurve() {
1604            // line-segment approximation
1605            const float segments[] = {
1606                0, 0, 1, 0.03, 10, 0.1, 51, 0.58, 127, 1
1607            };
1608            return InitCurve(segments);
1609        }
1610    
1611        float* Engine::InitCurve(const float* segments, int size) {
1612            float* y = new float[size];
1613            for (int x = 0 ; x < size ; x++) {
1614                if (x > segments[2]) segments += 2;
1615                y[x] = segments[1] + (x - segments[0]) *
1616                    (segments[3] - segments[1]) / (segments[2] - segments[0]);
1617            }
1618            return y;
1619        }
1620    
1621  }} // namespace LinuxSampler::gig  }} // namespace LinuxSampler::gig

Legend:
Removed from v.659  
changed lines
  Added in v.970

  ViewVC Help
Powered by ViewVC