/[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 649 by schoenebeck, Wed Jun 15 00:01:28 2005 UTC revision 1038 by persson, Sat Feb 3 15:33:00 2007 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
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-2007 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 63  namespace LinuxSampler { namespace gig { Line 57  namespace LinuxSampler { namespace gig {
57              pEngine->Connect(pDevice);              pEngine->Connect(pDevice);
58              engines[pDevice] = pEngine;              engines[pDevice] = pEngine;
59          }          }
60    
61          // register engine channel to the engine instance          // register engine channel to the engine instance
62    
63            // Disable the engine while the new engine channel is added
64            // and initialized. The engine will be enabled again in
65            // EngineChannel::Connect.
66            pEngine->DisableAndLock();
67    
68          pEngine->engineChannels.add(pChannel);          pEngine->engineChannels.add(pChannel);
69          // remember index in the ArrayList          // remember index in the ArrayList
70          pChannel->iEngineIndexSelf = pEngine->engineChannels.size() - 1;          pChannel->iEngineIndexSelf = pEngine->engineChannels.size() - 1;
# Line 103  namespace LinuxSampler { namespace gig { Line 104  namespace LinuxSampler { namespace gig {
104          pAudioOutputDevice = NULL;          pAudioOutputDevice = NULL;
105          pDiskThread        = NULL;          pDiskThread        = NULL;
106          pEventGenerator    = NULL;          pEventGenerator    = NULL;
107          pSysexBuffer       = new RingBuffer<uint8_t>(CONFIG_SYSEX_BUFFER_SIZE, 0);          pSysexBuffer       = new RingBuffer<uint8_t,false>(CONFIG_SYSEX_BUFFER_SIZE, 0);
108          pEventQueue        = new RingBuffer<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);          pEventQueue        = new RingBuffer<Event,false>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);
109          pEventPool         = new Pool<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT);          pEventPool         = new Pool<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT);
110          pVoicePool         = new Pool<Voice>(CONFIG_MAX_VOICES);          pVoicePool         = new Pool<Voice>(CONFIG_MAX_VOICES);
111            pDimRegionsInUse   = new ::gig::DimensionRegion*[CONFIG_MAX_VOICES + 1];
112          pVoiceStealingQueue = new RTList<Event>(pEventPool);          pVoiceStealingQueue = new RTList<Event>(pEventPool);
113          pGlobalEvents      = new RTList<Event>(pEventPool);          pGlobalEvents      = new RTList<Event>(pEventPool);
114            InstrumentChangeQueue      = new RingBuffer<instrument_change_command_t,false>(1, 0);
115            InstrumentChangeReplyQueue = new RingBuffer<instrument_change_reply_t,false>(1, 0);
116    
117          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()) {
118              iterVoice->SetEngine(this);              iterVoice->SetEngine(this);
119          }          }
120          pVoicePool->clear();          pVoicePool->clear();
121    
         pSynthesisParameters[0] = NULL; // we allocate when an audio device is connected  
         pBasicFilterParameters  = NULL;  
         pMainFilterParameters   = NULL;  
   
122          ResetInternal();          ResetInternal();
123            ResetScaleTuning();
124      }      }
125    
126      /**      /**
127       * Destructor       * Destructor
128       */       */
129      Engine::~Engine() {      Engine::~Engine() {
130            MidiInputPort::RemoveSysexListener(this);
131          if (pDiskThread) {          if (pDiskThread) {
132              dmsg(1,("Stopping disk thread..."));              dmsg(1,("Stopping disk thread..."));
133              pDiskThread->StopThread();              pDiskThread->StopThread();
# Line 138  namespace LinuxSampler { namespace gig { Line 141  namespace LinuxSampler { namespace gig {
141              delete pVoicePool;              delete pVoicePool;
142          }          }
143          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
         if (pMainFilterParameters) delete[] pMainFilterParameters;  
         if (pBasicFilterParameters) delete[] pBasicFilterParameters;  
         if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);  
144          if (pVoiceStealingQueue) delete pVoiceStealingQueue;          if (pVoiceStealingQueue) delete pVoiceStealingQueue;
145          if (pSysexBuffer) delete pSysexBuffer;          if (pSysexBuffer) delete pSysexBuffer;
146          EngineFactory::Destroy(this);          Unregister();
147      }      }
148    
149      void Engine::Enable() {      void Engine::Enable() {
# Line 171  namespace LinuxSampler { namespace gig { Line 171  namespace LinuxSampler { namespace gig {
171      void Engine::Reset() {      void Engine::Reset() {
172          DisableAndLock();          DisableAndLock();
173          ResetInternal();          ResetInternal();
174            ResetScaleTuning();
175          Enable();          Enable();
176      }      }
177    
178      /**      /**
179       *  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
180       *  control and status variables. This method is not thread safe!       *  control and status variables. This method is protected by a mutex.
181       */       */
182      void Engine::ResetInternal() {      void Engine::ResetInternal() {
183            ResetInternalMutex.Lock();
184    
185            // make sure that the engine does not get any sysex messages
186            // while it's reseting
187            bool sysexDisabled = MidiInputPort::RemoveSysexListener(this);
188          ActiveVoiceCount    = 0;          ActiveVoiceCount    = 0;
189          ActiveVoiceCountMax = 0;          ActiveVoiceCountMax = 0;
190    
# Line 190  namespace LinuxSampler { namespace gig { Line 196  namespace LinuxSampler { namespace gig {
196          iuiLastStolenKeyGlobally   = RTList<uint>::Iterator();          iuiLastStolenKeyGlobally   = RTList<uint>::Iterator();
197          pLastStolenChannel         = NULL;          pLastStolenChannel         = NULL;
198    
         // reset to normal chromatic scale (means equal temper)  
         memset(&ScaleTuning[0], 0x00, 12);  
   
199          // reset all voices          // reset all voices
200          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()) {
201              iterVoice->Reset();              iterVoice->Reset();
# Line 204  namespace LinuxSampler { namespace gig { Line 207  namespace LinuxSampler { namespace gig {
207    
208          // delete all input events          // delete all input events
209          pEventQueue->init();          pEventQueue->init();
210            pSysexBuffer->init();
211            if (sysexDisabled) MidiInputPort::AddSysexListener(this);
212            ResetInternalMutex.Unlock();
213        }
214    
215        /**
216         * Reset to normal, chromatic scale (means equal tempered).
217         */
218        void Engine::ResetScaleTuning() {
219            memset(&ScaleTuning[0], 0x00, 12);
220      }      }
221    
222      /**      /**
# Line 226  namespace LinuxSampler { namespace gig { Line 239  namespace LinuxSampler { namespace gig {
239          }          }
240          catch (AudioOutputException e) {          catch (AudioOutputException e) {
241              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();
242              throw LinuxSamplerException(msg);              throw Exception(msg);
243          }          }
244    
245          this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle();          this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle();
# Line 234  namespace LinuxSampler { namespace gig { Line 247  namespace LinuxSampler { namespace gig {
247    
248          // FIXME: audio drivers with varying fragment sizes might be a problem here          // FIXME: audio drivers with varying fragment sizes might be a problem here
249          MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * CONFIG_EG_MIN_RELEASE_TIME) - 1;          MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * CONFIG_EG_MIN_RELEASE_TIME) - 1;
250          if (MaxFadeOutPos < 0)          if (MaxFadeOutPos < 0) {
251              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 "
252                          << "too big for current audio fragment size & sampling rate! "
253                          << "May lead to click sounds if voice stealing chimes in!\n" << std::flush;
254                // force volume ramp downs at the beginning of each fragment
255                MaxFadeOutPos = 0;
256                // lower minimum release time
257                const float minReleaseTime = (float) MaxSamplesPerCycle / (float) SampleRate;
258                for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
259                    iterVoice->EG1.CalculateFadeOutCoeff(minReleaseTime, SampleRate);
260                }
261                pVoicePool->clear();
262            }
263    
264          // (re)create disk thread          // (re)create disk thread
265          if (this->pDiskThread) {          if (this->pDiskThread) {
# Line 244  namespace LinuxSampler { namespace gig { Line 268  namespace LinuxSampler { namespace gig {
268              delete this->pDiskThread;              delete this->pDiskThread;
269              dmsg(1,("OK\n"));              dmsg(1,("OK\n"));
270          }          }
271          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << CONFIG_MAX_PITCH) << 1) + 6); //FIXME: assuming stereo          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << CONFIG_MAX_PITCH) << 1) + 6, //FIXME: assuming stereo
272                                               &instruments);
273          if (!pDiskThread) {          if (!pDiskThread) {
274              dmsg(0,("gig::Engine  new diskthread = NULL\n"));              dmsg(0,("gig::Engine  new diskthread = NULL\n"));
275              exit(EXIT_FAILURE);              exit(EXIT_FAILURE);
# Line 260  namespace LinuxSampler { namespace gig { Line 285  namespace LinuxSampler { namespace gig {
285          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
286          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
287    
         // (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()];  
   
288          dmsg(1,("Starting disk thread..."));          dmsg(1,("Starting disk thread..."));
289          pDiskThread->StartThread();          pDiskThread->StartThread();
290          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
# Line 310  namespace LinuxSampler { namespace gig { Line 318  namespace LinuxSampler { namespace gig {
318       *                  current audio cycle       *                  current audio cycle
319       */       */
320      void Engine::ImportEvents(uint Samples) {      void Engine::ImportEvents(uint Samples) {
321          RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();          RingBuffer<Event,false>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
322          Event* pEvent;          Event* pEvent;
323          while (true) {          while (true) {
324              // get next event from input event queue              // get next event from input event queue
# Line 333  namespace LinuxSampler { namespace gig { Line 341  namespace LinuxSampler { namespace gig {
341      }      }
342    
343      /**      /**
344       *  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.
345       *  calculated audio data of all voices of this engine will be placed into       * The engine will iterate through all engine channels and render audio
346       *  the engine's audio sum buffer which has to be copied and eventually be       * for each engine channel independently. The calculated audio data of
347       *  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
348       *  AlsaIO or JackIO) right after.       * buffers of the respective audio output device, connected to the
349         * respective engine channel.
350       *       *
351       *  @param Samples - number of sample points to be rendered       *  @param Samples - number of sample points to be rendered
352       *  @returns       0 on success       *  @returns       0 on success
353       */       */
354      int Engine::RenderAudio(uint Samples) {      int Engine::RenderAudio(uint Samples) {
355          dmsg(5,("RenderAudio(Samples=%d)\n", Samples));          dmsg(7,("RenderAudio(Samples=%d)\n", Samples));
356    
357          // return if engine disabled          // return if engine disabled
358          if (EngineDisabled.Pop()) {          if (EngineDisabled.Pop()) {
# Line 354  namespace LinuxSampler { namespace gig { Line 363  namespace LinuxSampler { namespace gig {
363          // 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)
364          pEventGenerator->UpdateFragmentTime(Samples);          pEventGenerator->UpdateFragmentTime(Samples);
365    
366            // We only allow a maximum of CONFIG_MAX_VOICES voices to be spawned
367            // in each audio fragment. All subsequent request for spawning new
368            // voices in the same audio fragment will be ignored.
369            VoiceSpawnsLeft = CONFIG_MAX_VOICES;
370    
371          // 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
372          // (these are usually just SysEx messages)          // (these are usually just SysEx messages)
373          ImportEvents(Samples);          ImportEvents(Samples);
# Line 372  namespace LinuxSampler { namespace gig { Line 386  namespace LinuxSampler { namespace gig {
386              }              }
387          }          }
388    
         // 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;  
   
389          // reset internal voice counter (just for statistic of active voices)          // reset internal voice counter (just for statistic of active voices)
390          ActiveVoiceCountTemp = 0;          ActiveVoiceCountTemp = 0;
391    
392            // handle instrument change commands
393            instrument_change_command_t command;
394            if (InstrumentChangeQueue->pop(&command) > 0) {
395                EngineChannel* pEngineChannel = command.pEngineChannel;
396                pEngineChannel->pInstrument = command.pInstrument;
397    
398                // iterate through all active voices and mark their
399                // dimension regions as "in use". The instrument resource
400                // manager may delete all of the instrument except the
401                // dimension regions and samples that are in use.
402                int i = 0;
403                RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
404                RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
405                while (iuiKey != end) { // iterate through all active keys
406                    midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
407                    ++iuiKey;
408    
409                    RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
410                    RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
411                    for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
412                        if (!itVoice->Orphan) {
413                            itVoice->Orphan = true;
414                            pDimRegionsInUse[i++] = itVoice->pDimRgn;
415                        }
416                    }
417                }
418                pDimRegionsInUse[i] = 0; // end of list
419    
420                // send a reply to the calling thread, which is waiting
421                instrument_change_reply_t reply;
422                InstrumentChangeReplyQueue->push(&reply);
423            }
424    
425          // handle events on all engine channels          // handle events on all engine channels
426          for (int i = 0; i < engineChannels.size(); i++) {          for (int i = 0; i < engineChannels.size(); i++) {
             if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded  
427              ProcessEvents(engineChannels[i], Samples);              ProcessEvents(engineChannels[i], Samples);
428          }          }
429    
430          // render all 'normal', active voices on all engine channels          // render all 'normal', active voices on all engine channels
431          for (int i = 0; i < engineChannels.size(); i++) {          for (int i = 0; i < engineChannels.size(); i++) {
             if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded  
432              RenderActiveVoices(engineChannels[i], Samples);              RenderActiveVoices(engineChannels[i], Samples);
433          }          }
434    
435          // now that all ordinary voices on ALL engine channels are rendered, render new stolen voices          // now that all ordinary voices on ALL engine channels are rendered, render new stolen voices
436          RenderStolenVoices(Samples);          RenderStolenVoices(Samples);
437    
438            // handle audio routing for engine channels with FX sends
439            for (int i = 0; i < engineChannels.size(); i++) {
440                if (engineChannels[i]->fxSends.empty()) continue; // ignore if no FX sends
441                RouteAudio(engineChannels[i], Samples);
442            }
443    
444          // handle cleanup on all engine channels for the next audio fragment          // handle cleanup on all engine channels for the next audio fragment
445          for (int i = 0; i < engineChannels.size(); i++) {          for (int i = 0; i < engineChannels.size(); i++) {
             if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded  
446              PostProcess(engineChannels[i]);              PostProcess(engineChannels[i]);
447          }          }
448    
# Line 476  namespace LinuxSampler { namespace gig { Line 520  namespace LinuxSampler { namespace gig {
520       *                         this audio fragment cycle       *                         this audio fragment cycle
521       */       */
522      void Engine::RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {      void Engine::RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {
523            #if !CONFIG_PROCESS_MUTED_CHANNELS
524            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
525            #endif
526    
527          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
528          RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();          RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
529          while (iuiKey != end) { // iterate through all active keys          while (iuiKey != end) { // iterate through all active keys
# Line 513  namespace LinuxSampler { namespace gig { Line 561  namespace LinuxSampler { namespace gig {
561          RTList<Event>::Iterator end               = pVoiceStealingQueue->end();          RTList<Event>::Iterator end               = pVoiceStealingQueue->end();
562          for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {          for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
563              EngineChannel* pEngineChannel = (EngineChannel*) itVoiceStealEvent->pEngineChannel;              EngineChannel* pEngineChannel = (EngineChannel*) itVoiceStealEvent->pEngineChannel;
564                if (!pEngineChannel->pInstrument) continue; // ignore if no instrument loaded
565              Pool<Voice>::Iterator itNewVoice =              Pool<Voice>::Iterator itNewVoice =
566                  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);
567              if (itNewVoice) {              if (itNewVoice) {
568                  itNewVoice->Render(Samples);                  itNewVoice->Render(Samples);
569                  if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active                  if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active
# Line 532  namespace LinuxSampler { namespace gig { Line 581  namespace LinuxSampler { namespace gig {
581      }      }
582    
583      /**      /**
584         * Will be called in case the respective engine channel sports FX send
585         * channels. In this particular case, engine channel local buffers are
586         * used to render and mix all voices to. This method is responsible for
587         * copying the audio data from those local buffers to the master audio
588         * output channels as well as to the FX send audio output channels with
589         * their respective FX send levels.
590         *
591         * @param pEngineChannel - engine channel from which audio should be
592         *                         routed
593         * @param Samples        - amount of sample points to be routed in
594         *                         this audio fragment cycle
595         */
596        void Engine::RouteAudio(EngineChannel* pEngineChannel, uint Samples) {
597            // route master signal
598            {
599                AudioChannel* pDstL = pAudioOutputDevice->Channel(pEngineChannel->AudioDeviceChannelLeft);
600                AudioChannel* pDstR = pAudioOutputDevice->Channel(pEngineChannel->AudioDeviceChannelRight);
601                pEngineChannel->pChannelLeft->MixTo(pDstL, Samples);
602                pEngineChannel->pChannelRight->MixTo(pDstR, Samples);
603            }
604            // route FX send signal
605            {
606                for (int iFxSend = 0; iFxSend < pEngineChannel->GetFxSendCount(); iFxSend++) {
607                    FxSend* pFxSend = pEngineChannel->GetFxSend(iFxSend);
608                    // left channel
609                    const int iDstL = pFxSend->DestinationChannel(0);
610                    if (iDstL < 0) {
611                        dmsg(1,("Engine::RouteAudio() Error: invalid FX send (L) destination channel"));
612                    } else {
613                        AudioChannel* pDstL = pAudioOutputDevice->Channel(iDstL);
614                        if (!pDstL) {
615                            dmsg(1,("Engine::RouteAudio() Error: invalid FX send (L) destination channel"));
616                        } else pEngineChannel->pChannelLeft->MixTo(pDstL, Samples, pFxSend->Level());
617                    }
618                    // right channel
619                    const int iDstR = pFxSend->DestinationChannel(1);
620                    if (iDstR < 0) {
621                        dmsg(1,("Engine::RouteAudio() Error: invalid FX send (R) destination channel"));
622                    } else {
623                        AudioChannel* pDstR = pAudioOutputDevice->Channel(iDstR);
624                        if (!pDstR) {
625                            dmsg(1,("Engine::RouteAudio() Error: invalid FX send (R) destination channel"));
626                        } else pEngineChannel->pChannelRight->MixTo(pDstR, Samples, pFxSend->Level());
627                    }
628                }
629            }
630            // reset buffers with silence (zero out) for the next audio cycle
631            pEngineChannel->pChannelLeft->Clear();
632            pEngineChannel->pChannelRight->Clear();
633        }
634    
635        /**
636       * Free all keys which have turned inactive in this audio fragment, from       * Free all keys which have turned inactive in this audio fragment, from
637       * the list of active keys and clear all event lists on that engine       * the list of active keys and clear all event lists on that engine
638       * channel.       * channel.
# Line 604  namespace LinuxSampler { namespace gig { Line 705  namespace LinuxSampler { namespace gig {
705       *  @param itNoteOnEvent - key, velocity and time stamp of the event       *  @param itNoteOnEvent - key, velocity and time stamp of the event
706       */       */
707      void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {      void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
708            #if !CONFIG_PROCESS_MUTED_CHANNELS
709            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
710            #endif
711    
712            if (!pEngineChannel->pInstrument) return; // ignore if no instrument loaded
713    
714          const int key = itNoteOnEvent->Param.Note.Key;          const int key = itNoteOnEvent->Param.Note.Key;
715            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];
716    
717            // move note on event to the key's own event list
718            RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
719    
720            // if Solo Mode then kill all already active voices
721            if (pEngineChannel->SoloMode) {
722                Pool<uint>::Iterator itYoungestKey = pEngineChannel->pActiveKeys->last();
723                if (itYoungestKey) {
724                    const int iYoungestKey = *itYoungestKey;
725                    const midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[iYoungestKey];
726                    if (pOtherKey->Active) {
727                        // get final portamento position of currently active voice
728                        if (pEngineChannel->PortamentoMode) {
729                            RTList<Voice>::Iterator itVoice = pOtherKey->pActiveVoices->last();
730                            if (itVoice) itVoice->UpdatePortamentoPos(itNoteOnEventOnKeyList);
731                        }
732                        // kill all voices on the (other) key
733                        RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
734                        RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
735                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
736                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger)
737                                itVoiceToBeKilled->Kill(itNoteOnEventOnKeyList);
738                        }
739                    }
740                }
741                // set this key as 'currently active solo key'
742                pEngineChannel->SoloKey = key;
743            }
744    
745          // Change key dimension value if key is in keyswitching area          // Change key dimension value if key is in keyswitching area
746          {          {
747              const ::gig::Instrument* pInstrument = pEngineChannel->pInstrument;              const ::gig::Instrument* pInstrument = pEngineChannel->pInstrument;
748              if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high)              if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high)
749                  pEngineChannel->CurrentKeyDimension = ((key - pInstrument->DimensionKeyRange.low) * 128) /                  pEngineChannel->CurrentKeyDimension = float(key - pInstrument->DimensionKeyRange.low) /
750                      (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);                      (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);
751          }          }
752    
         midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];  
   
753          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
754          pKey->Velocity   = itNoteOnEvent->Param.Note.Velocity;          pKey->Velocity   = itNoteOnEventOnKeyList->Param.Note.Velocity;
755          pKey->NoteOnTime = FrameTime + itNoteOnEvent->FragmentPos(); // will be used to calculate note length          pKey->NoteOnTime = FrameTime + itNoteOnEventOnKeyList->FragmentPos(); // will be used to calculate note length
756    
757          // cancel release process of voices on this key if needed          // cancel release process of voices on this key if needed
758          if (pKey->Active && !pEngineChannel->SustainPedal) {          if (pKey->Active && !pEngineChannel->SustainPedal) {
759              RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();              RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
760              if (itCancelReleaseEvent) {              if (itCancelReleaseEvent) {
761                  *itCancelReleaseEvent = *itNoteOnEvent;                  // copy event                  *itCancelReleaseEvent = *itNoteOnEventOnKeyList;         // copy event
762                  itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type                  itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type
763              }              }
764              else dmsg(1,("Event pool emtpy!\n"));              else dmsg(1,("Event pool emtpy!\n"));
765          }          }
766    
         // move note on event to the key's own event list  
         RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);  
   
767          // allocate and trigger new voice(s) for the key          // allocate and trigger new voice(s) for the key
768          {          {
769              // 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 642  namespace LinuxSampler { namespace gig { Line 772  namespace LinuxSampler { namespace gig {
772                  int voicesRequired = pRegion->Layers;                  int voicesRequired = pRegion->Layers;
773                  // now launch the required amount of voices                  // now launch the required amount of voices
774                  for (int i = 0; i < voicesRequired; i++)                  for (int i = 0; i < voicesRequired; i++)
775                      LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true);                      LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true, true);
776              }              }
777          }          }
778    
# Line 650  namespace LinuxSampler { namespace gig { Line 780  namespace LinuxSampler { namespace gig {
780          if (!pKey->Active && !pKey->VoiceTheftsQueued)          if (!pKey->Active && !pKey->VoiceTheftsQueued)
781              pKey->pEvents->free(itNoteOnEventOnKeyList);              pKey->pEvents->free(itNoteOnEventOnKeyList);
782    
783            if (!pEngineChannel->SoloMode || pEngineChannel->PortamentoPos < 0.0f) pEngineChannel->PortamentoPos = (float) key;
784          pKey->RoundRobinIndex++;          pKey->RoundRobinIndex++;
785      }      }
786    
# Line 663  namespace LinuxSampler { namespace gig { Line 794  namespace LinuxSampler { namespace gig {
794       *  @param itNoteOffEvent - key, velocity and time stamp of the event       *  @param itNoteOffEvent - key, velocity and time stamp of the event
795       */       */
796      void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {      void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {
797          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];          #if !CONFIG_PROCESS_MUTED_CHANNELS
798            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
799            #endif
800    
801            const int iKey = itNoteOffEvent->Param.Note.Key;
802            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[iKey];
803          pKey->KeyPressed = false; // the MIDI key was now released          pKey->KeyPressed = false; // the MIDI key was now released
804    
805          // release voices on this key if needed          // move event to the key's own event list
806          if (pKey->Active && !pEngineChannel->SustainPedal) {          RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
             itNoteOffEvent->Type = Event::type_release; // transform event type  
807    
808              // move event to the key's own event list          bool bShouldRelease = pKey->Active && ShouldReleaseVoice(pEngineChannel, itNoteOffEventOnKeyList->Param.Note.Key);
809              RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);  
810            // in case Solo Mode is enabled, kill all voices on this key and respawn a voice on the highest pressed key (if any)
811            if (pEngineChannel->SoloMode && pEngineChannel->pInstrument) { //TODO: this feels like too much code just for handling solo mode :P
812                bool bOtherKeysPressed = false;
813                if (iKey == pEngineChannel->SoloKey) {
814                    pEngineChannel->SoloKey = -1;
815                    // if there's still a key pressed down, respawn a voice (group) on the highest key
816                    for (int i = 127; i > 0; i--) {
817                        midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[i];
818                        if (pOtherKey->KeyPressed) {
819                            bOtherKeysPressed = true;
820                            // make the other key the new 'currently active solo key'
821                            pEngineChannel->SoloKey = i;
822                            // get final portamento position of currently active voice
823                            if (pEngineChannel->PortamentoMode) {
824                                RTList<Voice>::Iterator itVoice = pKey->pActiveVoices->first();
825                                if (itVoice) itVoice->UpdatePortamentoPos(itNoteOffEventOnKeyList);
826                            }
827                            // create a pseudo note on event
828                            RTList<Event>::Iterator itPseudoNoteOnEvent = pOtherKey->pEvents->allocAppend();
829                            if (itPseudoNoteOnEvent) {
830                                // copy event
831                                *itPseudoNoteOnEvent = *itNoteOffEventOnKeyList;
832                                // transform event to a note on event
833                                itPseudoNoteOnEvent->Type                = Event::type_note_on;
834                                itPseudoNoteOnEvent->Param.Note.Key      = i;
835                                itPseudoNoteOnEvent->Param.Note.Velocity = pOtherKey->Velocity;
836                                // allocate and trigger new voice(s) for the other key
837                                {
838                                    // first, get total amount of required voices (dependant on amount of layers)
839                                    ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(i);
840                                    if (pRegion) {
841                                        int voicesRequired = pRegion->Layers;
842                                        // now launch the required amount of voices
843                                        for (int iLayer = 0; iLayer < voicesRequired; iLayer++)
844                                            LaunchVoice(pEngineChannel, itPseudoNoteOnEvent, iLayer, false, true, false);
845                                    }
846                                }
847                                // if neither a voice was spawned or postponed then remove note on event from key again
848                                if (!pOtherKey->Active && !pOtherKey->VoiceTheftsQueued)
849                                    pOtherKey->pEvents->free(itPseudoNoteOnEvent);
850    
851                            } else dmsg(1,("Could not respawn voice, no free event left\n"));
852                            break; // done
853                        }
854                    }
855                }
856                if (bOtherKeysPressed) {
857                    if (pKey->Active) { // kill all voices on this key
858                        bShouldRelease = false; // no need to release, as we kill it here
859                        RTList<Voice>::Iterator itVoiceToBeKilled = pKey->pActiveVoices->first();
860                        RTList<Voice>::Iterator end               = pKey->pActiveVoices->end();
861                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
862                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger)
863                                itVoiceToBeKilled->Kill(itNoteOffEventOnKeyList);
864                        }
865                    }
866                } else pEngineChannel->PortamentoPos = -1.0f;
867            }
868    
869            // if no solo mode (the usual case) or if solo mode and no other key pressed, then release voices on this key if needed
870            if (bShouldRelease) {
871                itNoteOffEventOnKeyList->Type = Event::type_release; // transform event type
872    
873              // spawn release triggered voice(s) if needed              // spawn release triggered voice(s) if needed
874              if (pKey->ReleaseTrigger) {              if (pKey->ReleaseTrigger && pEngineChannel->pInstrument) {
875                  // first, get total amount of required voices (dependant on amount of layers)                  // first, get total amount of required voices (dependant on amount of layers)
876                  ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOffEventOnKeyList->Param.Note.Key);                  ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOffEventOnKeyList->Param.Note.Key);
877                  if (pRegion) {                  if (pRegion) {
# Line 686  namespace LinuxSampler { namespace gig { Line 882  namespace LinuxSampler { namespace gig {
882    
883                      // now launch the required amount of voices                      // now launch the required amount of voices
884                      for (int i = 0; i < voicesRequired; i++)                      for (int i = 0; i < voicesRequired; i++)
885                          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
886                  }                  }
887                  pKey->ReleaseTrigger = false;                  pKey->ReleaseTrigger = false;
888              }              }
   
             // 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);  
889          }          }
890    
891            // if neither a voice was spawned or postponed on this key then remove note off event from key again
892            if (!pKey->Active && !pKey->VoiceTheftsQueued)
893                pKey->pEvents->free(itNoteOffEventOnKeyList);
894      }      }
895    
896      /**      /**
897       *  Moves pitchbend event from the general (input) event list to the pitch       *  Moves pitchbend event from the general (input) event list to the engine
898       *  event list.       *  channel's event list. It will actually processed later by the
899         *  respective voice.
900       *       *
901       *  @param pEngineChannel - engine channel on which this event occured on       *  @param pEngineChannel - engine channel on which this event occured on
902       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event
903       */       */
904      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {
905          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]);  
906      }      }
907    
908      /**      /**
# Line 723  namespace LinuxSampler { namespace gig { Line 919  namespace LinuxSampler { namespace gig {
919       *  @param VoiceStealing       - if voice stealing should be performed       *  @param VoiceStealing       - if voice stealing should be performed
920       *                               when there is no free voice       *                               when there is no free voice
921       *                               (optional, default = true)       *                               (optional, default = true)
922         *  @param HandleKeyGroupConflicts - if voices should be killed due to a
923         *                                   key group conflict
924       *  @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
925       *           if the voice wasn't triggered (for example when no region is       *           if the voice wasn't triggered (for example when no region is
926       *           defined for the given key).       *           defined for the given key).
927       */       */
928      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) {
929          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];          int MIDIKey            = itNoteOnEvent->Param.Note.Key;
930            midi_key_info_t* pKey  = &pEngineChannel->pMIDIKeyInfo[MIDIKey];
931            ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(MIDIKey);
932    
933            // if nothing defined for this key
934            if (!pRegion) return Pool<Voice>::Iterator(); // nothing to do
935    
936            // only mark the first voice of a layered voice (group) to be in a
937            // key group, so the layered voices won't kill each other
938            int iKeyGroup = (iLayer == 0 && !ReleaseTriggerVoice) ? pRegion->KeyGroup : 0;
939    
940            // handle key group (a.k.a. exclusive group) conflicts
941            if (HandleKeyGroupConflicts) {
942                if (iKeyGroup) { // if this voice / key belongs to a key group
943                    uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[iKeyGroup];
944                    if (*ppKeyGroup) { // if there's already an active key in that key group
945                        midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[**ppKeyGroup];
946                        // kill all voices on the (other) key
947                        RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
948                        RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
949                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
950                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger) {
951                                itVoiceToBeKilled->Kill(itNoteOnEvent);
952                                --VoiceSpawnsLeft; //FIXME: just a hack, we should better check in StealVoice() if the voice was killed due to key conflict
953                            }
954                        }
955                    }
956                }
957            }
958    
959            Voice::type_t VoiceType = Voice::type_normal;
960    
961            // get current dimension values to select the right dimension region
962            //TODO: for stolen voices this dimension region selection block is processed twice, this should be changed
963            //FIXME: controller values for selecting the dimension region here are currently not sample accurate
964            uint DimValues[8] = { 0 };
965            for (int i = pRegion->Dimensions - 1; i >= 0; i--) {
966                switch (pRegion->pDimensionDefinitions[i].dimension) {
967                    case ::gig::dimension_samplechannel:
968                        DimValues[i] = 0; //TODO: we currently ignore this dimension
969                        break;
970                    case ::gig::dimension_layer:
971                        DimValues[i] = iLayer;
972                        break;
973                    case ::gig::dimension_velocity:
974                        DimValues[i] = itNoteOnEvent->Param.Note.Velocity;
975                        break;
976                    case ::gig::dimension_channelaftertouch:
977                        DimValues[i] = pEngineChannel->ControllerTable[128];
978                        break;
979                    case ::gig::dimension_releasetrigger:
980                        VoiceType = (ReleaseTriggerVoice) ? Voice::type_release_trigger : (!iLayer) ? Voice::type_release_trigger_required : Voice::type_normal;
981                        DimValues[i] = (uint) ReleaseTriggerVoice;
982                        break;
983                    case ::gig::dimension_keyboard:
984                        DimValues[i] = (uint) (pEngineChannel->CurrentKeyDimension * pRegion->pDimensionDefinitions[i].zones);
985                        break;
986                    case ::gig::dimension_roundrobin:
987                        DimValues[i] = (uint) pEngineChannel->pMIDIKeyInfo[MIDIKey].RoundRobinIndex; // incremented for each note on
988                        break;
989                    case ::gig::dimension_random:
990                        RandomSeed   = RandomSeed * 1103515245 + 12345; // classic pseudo random number generator
991                        DimValues[i] = (uint) RandomSeed >> (32 - pRegion->pDimensionDefinitions[i].bits); // highest bits are most random
992                        break;
993                    case ::gig::dimension_modwheel:
994                        DimValues[i] = pEngineChannel->ControllerTable[1];
995                        break;
996                    case ::gig::dimension_breath:
997                        DimValues[i] = pEngineChannel->ControllerTable[2];
998                        break;
999                    case ::gig::dimension_foot:
1000                        DimValues[i] = pEngineChannel->ControllerTable[4];
1001                        break;
1002                    case ::gig::dimension_portamentotime:
1003                        DimValues[i] = pEngineChannel->ControllerTable[5];
1004                        break;
1005                    case ::gig::dimension_effect1:
1006                        DimValues[i] = pEngineChannel->ControllerTable[12];
1007                        break;
1008                    case ::gig::dimension_effect2:
1009                        DimValues[i] = pEngineChannel->ControllerTable[13];
1010                        break;
1011                    case ::gig::dimension_genpurpose1:
1012                        DimValues[i] = pEngineChannel->ControllerTable[16];
1013                        break;
1014                    case ::gig::dimension_genpurpose2:
1015                        DimValues[i] = pEngineChannel->ControllerTable[17];
1016                        break;
1017                    case ::gig::dimension_genpurpose3:
1018                        DimValues[i] = pEngineChannel->ControllerTable[18];
1019                        break;
1020                    case ::gig::dimension_genpurpose4:
1021                        DimValues[i] = pEngineChannel->ControllerTable[19];
1022                        break;
1023                    case ::gig::dimension_sustainpedal:
1024                        DimValues[i] = pEngineChannel->ControllerTable[64];
1025                        break;
1026                    case ::gig::dimension_portamento:
1027                        DimValues[i] = pEngineChannel->ControllerTable[65];
1028                        break;
1029                    case ::gig::dimension_sostenutopedal:
1030                        DimValues[i] = pEngineChannel->ControllerTable[66];
1031                        break;
1032                    case ::gig::dimension_softpedal:
1033                        DimValues[i] = pEngineChannel->ControllerTable[67];
1034                        break;
1035                    case ::gig::dimension_genpurpose5:
1036                        DimValues[i] = pEngineChannel->ControllerTable[80];
1037                        break;
1038                    case ::gig::dimension_genpurpose6:
1039                        DimValues[i] = pEngineChannel->ControllerTable[81];
1040                        break;
1041                    case ::gig::dimension_genpurpose7:
1042                        DimValues[i] = pEngineChannel->ControllerTable[82];
1043                        break;
1044                    case ::gig::dimension_genpurpose8:
1045                        DimValues[i] = pEngineChannel->ControllerTable[83];
1046                        break;
1047                    case ::gig::dimension_effect1depth:
1048                        DimValues[i] = pEngineChannel->ControllerTable[91];
1049                        break;
1050                    case ::gig::dimension_effect2depth:
1051                        DimValues[i] = pEngineChannel->ControllerTable[92];
1052                        break;
1053                    case ::gig::dimension_effect3depth:
1054                        DimValues[i] = pEngineChannel->ControllerTable[93];
1055                        break;
1056                    case ::gig::dimension_effect4depth:
1057                        DimValues[i] = pEngineChannel->ControllerTable[94];
1058                        break;
1059                    case ::gig::dimension_effect5depth:
1060                        DimValues[i] = pEngineChannel->ControllerTable[95];
1061                        break;
1062                    case ::gig::dimension_none:
1063                        std::cerr << "gig::Engine::LaunchVoice() Error: dimension=none\n" << std::flush;
1064                        break;
1065                    default:
1066                        std::cerr << "gig::Engine::LaunchVoice() Error: Unknown dimension\n" << std::flush;
1067                }
1068            }
1069    
1070            // return if this is a release triggered voice and there is no
1071            // releasetrigger dimension (could happen if an instrument
1072            // change has occured between note on and off)
1073            if (ReleaseTriggerVoice && VoiceType != Voice::type_release_trigger) return Pool<Voice>::Iterator();
1074    
1075            ::gig::DimensionRegion* pDimRgn = pRegion->GetDimensionRegionByValue(DimValues);
1076    
1077            // no need to continue if sample is silent
1078            if (!pDimRgn->pSample || !pDimRgn->pSample->SamplesTotal) return Pool<Voice>::Iterator();
1079    
1080          // allocate a new voice for the key          // allocate a new voice for the key
1081          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
1082          if (itNewVoice) {          if (itNewVoice) {
1083              // launch the new voice              // launch the new voice
1084              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pEngineChannel->pInstrument, iLayer, ReleaseTriggerVoice, VoiceStealing) < 0) {              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pDimRgn, VoiceType, iKeyGroup) < 0) {
1085                  dmsg(4,("Voice not triggered\n"));                  dmsg(4,("Voice not triggered\n"));
1086                  pKey->pActiveVoices->free(itNewVoice);                  pKey->pActiveVoices->free(itNewVoice);
1087              }              }
1088              else { // on success              else { // on success
1089                  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);  
                         }  
                     }  
                 }  
1090                  if (!pKey->Active) { // mark as active key                  if (!pKey->Active) { // mark as active key
1091                      pKey->Active = true;                      pKey->Active = true;
1092                      pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();                      pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();
1093                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
1094                  }                  }
1095                  if (itNewVoice->KeyGroup) {                  if (itNewVoice->KeyGroup) {
1096                        uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup];
1097                      *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
1098                  }                  }
1099                  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 794  namespace LinuxSampler { namespace gig { Line 1130  namespace LinuxSampler { namespace gig {
1130       *  @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
1131       */       */
1132      int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {      int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
1133          if (!VoiceTheftsLeft) {          if (VoiceSpawnsLeft <= 0) {
1134              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"));
1135              return -1;              return -1;
1136          }          }
# Line 813  namespace LinuxSampler { namespace gig { Line 1149  namespace LinuxSampler { namespace gig {
1149                      midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];                      midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
1150                      itSelectedVoice = pSelectedKey->pActiveVoices->first();                      itSelectedVoice = pSelectedKey->pActiveVoices->first();
1151                      // proceed iterating if voice was created in this fragment cycle                      // proceed iterating if voice was created in this fragment cycle
1152                      while (itSelectedVoice && !itSelectedVoice->hasRendered()) ++itSelectedVoice;                      while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1153                      // if we haven't found a voice then proceed with algorithm 'oldestkey'                      // if we haven't found a voice then proceed with algorithm 'oldestkey'
1154                      if (itSelectedVoice && itSelectedVoice->hasRendered()) break;                      if (itSelectedVoice && itSelectedVoice->IsStealable()) break;
1155                  } // no break - intentional !                  } // no break - intentional !
1156    
1157                  // try to pick the oldest voice on the oldest active key                  // try to pick the oldest voice on the oldest active key
# Line 827  namespace LinuxSampler { namespace gig { Line 1163  namespace LinuxSampler { namespace gig {
1163                          itSelectedVoice = this->itLastStolenVoice;                          itSelectedVoice = this->itLastStolenVoice;
1164                          do {                          do {
1165                              ++itSelectedVoice;                              ++itSelectedVoice;
1166                          } 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
1167                          // found a "stealable" voice ?                          // found a "stealable" voice ?
1168                          if (itSelectedVoice && itSelectedVoice->hasRendered()) {                          if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1169                              // 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
1170                              this->itLastStolenVoice = itSelectedVoice;                              this->itLastStolenVoice = itSelectedVoice;
1171                              break; // selection succeeded                              break; // selection succeeded
# Line 839  namespace LinuxSampler { namespace gig { Line 1175  namespace LinuxSampler { namespace gig {
1175                      RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKey) ? ++this->iuiLastStolenKey : pEngineChannel->pActiveKeys->first();                      RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKey) ? ++this->iuiLastStolenKey : pEngineChannel->pActiveKeys->first();
1176                      while (iuiSelectedKey) {                      while (iuiSelectedKey) {
1177                          midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];                          midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];
1178                          itSelectedVoice = pSelectedKey->pActiveVoices->first();                                                  itSelectedVoice = pSelectedKey->pActiveVoices->first();
1179                          // proceed iterating if voice was created in this fragment cycle                          // proceed iterating if voice was created in this fragment cycle
1180                          while (itSelectedVoice && !itSelectedVoice->hasRendered()) ++itSelectedVoice;                          while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1181                          // found a "stealable" voice ?                          // found a "stealable" voice ?
1182                          if (itSelectedVoice && itSelectedVoice->hasRendered()) {                          if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1183                              // 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
1184                              this->iuiLastStolenKey  = iuiSelectedKey;                              this->iuiLastStolenKey  = iuiSelectedKey;
1185                              this->itLastStolenVoice = itSelectedVoice;                              this->itLastStolenVoice = itSelectedVoice;
# Line 865  namespace LinuxSampler { namespace gig { Line 1201  namespace LinuxSampler { namespace gig {
1201              // 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
1202              // steal oldest voice on the oldest key from any other engine channel              // steal oldest voice on the oldest key from any other engine channel
1203              // (the smaller engine channel number, the higher priority)              // (the smaller engine channel number, the higher priority)
1204              if (!itSelectedVoice || !itSelectedVoice->hasRendered()) {              if (!itSelectedVoice || !itSelectedVoice->IsStealable()) {
1205                  EngineChannel* pSelectedChannel;                  EngineChannel* pSelectedChannel;
1206                  int            iChannelIndex;                  int            iChannelIndex;
1207                  // select engine channel                  // select engine channel
# Line 876  namespace LinuxSampler { namespace gig { Line 1212  namespace LinuxSampler { namespace gig {
1212                      iChannelIndex    = (pEngineChannel->iEngineIndexSelf + 1) % engineChannels.size();                      iChannelIndex    = (pEngineChannel->iEngineIndexSelf + 1) % engineChannels.size();
1213                      pSelectedChannel = engineChannels[iChannelIndex];                      pSelectedChannel = engineChannels[iChannelIndex];
1214                  }                  }
1215                  // iterate through engine channels  
1216                  while (true) {                  // if we already stole in this fragment, try to proceed on same key
1217                      // if we already stole in this fragment, try to proceed on same key                  if (this->itLastStolenVoiceGlobally) {
1218                      if (this->itLastStolenVoiceGlobally) {                      itSelectedVoice = this->itLastStolenVoiceGlobally;
1219                          itSelectedVoice = this->itLastStolenVoiceGlobally;                      do {
1220                          do {                          ++itSelectedVoice;
1221                              ++itSelectedVoice;                      } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1222                          } while (itSelectedVoice && !itSelectedVoice->hasRendered()); // proceed iterating if voice was created in this fragment cycle                  }
1223                          // break if selection succeeded  
1224                          if (itSelectedVoice && itSelectedVoice->hasRendered()) {                  #if CONFIG_DEVMODE
1225                              // remember which voice we stole, so we can simply proceed on next voice stealing                  EngineChannel* pBegin = pSelectedChannel; // to detect endless loop
1226                              this->itLastStolenVoiceGlobally = itSelectedVoice;                  #endif // CONFIG_DEVMODE
1227                              break; // selection succeeded  
1228                          }                  // did we find a 'stealable' voice?
1229                      }                  if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1230                        // remember which voice we stole, so we can simply proceed on next voice stealing
1231                        this->itLastStolenVoiceGlobally = itSelectedVoice;
1232                    } else while (true) { // iterate through engine channels
1233                      // get (next) oldest key                      // get (next) oldest key
1234                      RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKey) ? ++this->iuiLastStolenKey : pSelectedChannel->pActiveKeys->first();                      RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKeyGlobally) ? ++this->iuiLastStolenKeyGlobally : pSelectedChannel->pActiveKeys->first();
1235                        this->iuiLastStolenKeyGlobally = RTList<uint>::Iterator(); // to prevent endless loop (see line above)
1236                      while (iuiSelectedKey) {                      while (iuiSelectedKey) {
1237                          midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];                          midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];
1238                          itSelectedVoice = pSelectedKey->pActiveVoices->first();                          itSelectedVoice = pSelectedKey->pActiveVoices->first();
1239                          // proceed iterating if voice was created in this fragment cycle                          // proceed iterating if voice was created in this fragment cycle
1240                          while (itSelectedVoice && !itSelectedVoice->hasRendered()) ++itSelectedVoice;                          while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1241                          // found a "stealable" voice ?                          // found a "stealable" voice ?
1242                          if (itSelectedVoice && itSelectedVoice->hasRendered()) {                          if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1243                              // 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
1244                              this->iuiLastStolenKeyGlobally  = iuiSelectedKey;                              this->iuiLastStolenKeyGlobally  = iuiSelectedKey;
1245                              this->itLastStolenVoiceGlobally = itSelectedVoice;                              this->itLastStolenVoiceGlobally = itSelectedVoice;
1246                              this->pLastStolenChannel        = pSelectedChannel;                              this->pLastStolenChannel        = pSelectedChannel;
1247                              break; // selection succeeded                              goto stealable_voice_found; // selection succeeded
1248                          }                          }
1249                          ++iuiSelectedKey; // get next key on current engine channel                          ++iuiSelectedKey; // get next key on current engine channel
1250                      }                      }
1251                      // get next engine channel                      // get next engine channel
1252                      iChannelIndex    = (iChannelIndex + 1) % engineChannels.size();                      iChannelIndex    = (iChannelIndex + 1) % engineChannels.size();
1253                      pSelectedChannel = engineChannels[iChannelIndex];                      pSelectedChannel = engineChannels[iChannelIndex];
1254    
1255                        #if CONFIG_DEVMODE
1256                        if (pSelectedChannel == pBegin) {
1257                            dmsg(1,("FATAL ERROR: voice stealing endless loop!\n"));
1258                            dmsg(1,("VoiceSpawnsLeft=%d.\n", VoiceSpawnsLeft));
1259                            dmsg(1,("Exiting.\n"));
1260                            exit(-1);
1261                        }
1262                        #endif // CONFIG_DEVMODE
1263                  }                  }
1264              }              }
1265    
1266                // jump point if a 'stealable' voice was found
1267                stealable_voice_found:
1268    
1269              #if CONFIG_DEVMODE              #if CONFIG_DEVMODE
1270              if (!itSelectedVoice->IsActive()) {              if (!itSelectedVoice->IsActive()) {
1271                  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 922  namespace LinuxSampler { namespace gig { Line 1274  namespace LinuxSampler { namespace gig {
1274              #endif // CONFIG_DEVMODE              #endif // CONFIG_DEVMODE
1275    
1276              // now kill the selected voice              // now kill the selected voice
1277              itSelectedVoice->Kill(itNoteOnEvent);                          itSelectedVoice->Kill(itNoteOnEvent);
1278    
1279              --VoiceTheftsLeft;              --VoiceSpawnsLeft;
1280    
1281              return 0; // success              return 0; // success
1282          }          }
# Line 949  namespace LinuxSampler { namespace gig { Line 1301  namespace LinuxSampler { namespace gig {
1301    
1302              uint keygroup = itVoice->KeyGroup;              uint keygroup = itVoice->KeyGroup;
1303    
1304                // if the sample and dimension region belong to an
1305                // instrument that is unloaded, tell the disk thread to
1306                // release them
1307                if (itVoice->Orphan) {
1308                    pDiskThread->OrderDeletionOfDimreg(itVoice->pDimRgn);
1309                }
1310    
1311              // free the voice object              // free the voice object
1312              pVoicePool->free(itVoice);              pVoicePool->free(itVoice);
1313    
# Line 993  namespace LinuxSampler { namespace gig { Line 1352  namespace LinuxSampler { namespace gig {
1352          // update controller value in the engine channel's controller table          // update controller value in the engine channel's controller table
1353          pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;          pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
1354    
1355          // move event from the unsorted event list to the control change event list          // handle hard coded MIDI controllers
1356          Pool<Event>::Iterator itControlChangeEventOnCCList = itControlChangeEvent.moveToEndOf(pEngineChannel->pCCEvents);          switch (itControlChangeEvent->Param.CC.Controller) {
1357                case 5: { // portamento time
1358          switch (itControlChangeEventOnCCList->Param.CC.Controller) {                  pEngineChannel->PortamentoTime = (float) itControlChangeEvent->Param.CC.Value / 127.0f * (float) CONFIG_PORTAMENTO_TIME_MAX + (float) CONFIG_PORTAMENTO_TIME_MIN;
1359                    break;
1360                }
1361              case 7: { // volume              case 7: { // volume
1362                  //TODO: not sample accurate yet                  //TODO: not sample accurate yet
1363                  pEngineChannel->GlobalVolume = (float) itControlChangeEventOnCCList->Param.CC.Value / 127.0f;                  pEngineChannel->MidiVolume = VolumeCurve[itControlChangeEvent->Param.CC.Value];
1364                    pEngineChannel->bStatusChanged = true; // engine channel status has changed, so set notify flag
1365                  break;                  break;
1366              }              }
1367              case 10: { // panpot              case 10: { // panpot
1368                  //TODO: not sample accurate yet                  //TODO: not sample accurate yet
1369                  const int pan = (int) itControlChangeEventOnCCList->Param.CC.Value - 64;                  pEngineChannel->GlobalPanLeft  = PanCurve[128 - itControlChangeEvent->Param.CC.Value];
1370                  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;  
1371                  break;                  break;
1372              }              }
1373              case 64: { // sustain              case 64: { // sustain
1374                  if (itControlChangeEventOnCCList->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {
1375                      dmsg(4,("PEDAL DOWN\n"));                      dmsg(4,("DAMPER (RIGHT) PEDAL DOWN\n"));
1376                      pEngineChannel->SustainPedal = true;                      pEngineChannel->SustainPedal = true;
1377    
1378                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1379                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1380                        #endif
1381    
1382                      // cancel release process of voices if necessary                      // cancel release process of voices if necessary
1383                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1384                      for (; iuiKey; ++iuiKey) {                      for (; iuiKey; ++iuiKey) {
# Line 1021  namespace LinuxSampler { namespace gig { Line 1386  namespace LinuxSampler { namespace gig {
1386                          if (!pKey->KeyPressed) {                          if (!pKey->KeyPressed) {
1387                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1388                              if (itNewEvent) {                              if (itNewEvent) {
1389                                  *itNewEvent = *itControlChangeEventOnCCList; // copy event to the key's own event list                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1390                                  itNewEvent->Type = Event::type_cancel_release; // transform event type                                  itNewEvent->Type = Event::type_cancel_release; // transform event type
1391                              }                              }
1392                              else dmsg(1,("Event pool emtpy!\n"));                              else dmsg(1,("Event pool emtpy!\n"));
1393                          }                          }
1394                      }                      }
1395                  }                  }
1396                  if (itControlChangeEventOnCCList->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {
1397                      dmsg(4,("PEDAL UP\n"));                      dmsg(4,("DAMPER (RIGHT) PEDAL UP\n"));
1398                      pEngineChannel->SustainPedal = false;                      pEngineChannel->SustainPedal = false;
1399    
1400                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1401                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1402                        #endif
1403    
1404                      // release voices if their respective key is not pressed                      // release voices if their respective key is not pressed
1405                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1406                      for (; iuiKey; ++iuiKey) {                      for (; iuiKey; ++iuiKey) {
1407                          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];                          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1408                          if (!pKey->KeyPressed) {                          if (!pKey->KeyPressed && ShouldReleaseVoice(pEngineChannel, *iuiKey)) {
1409                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1410                              if (itNewEvent) {                              if (itNewEvent) {
1411                                  *itNewEvent = *itControlChangeEventOnCCList; // copy event to the key's own event list                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1412                                    itNewEvent->Type = Event::type_release; // transform event type
1413                                }
1414                                else dmsg(1,("Event pool emtpy!\n"));
1415                            }
1416                        }
1417                    }
1418                    break;
1419                }
1420                case 65: { // portamento on / off
1421                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1422                    pEngineChannel->PortamentoMode = itControlChangeEvent->Param.CC.Value >= 64;
1423                    break;
1424                }
1425                case 66: { // sostenuto
1426                    if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SostenutoPedal) {
1427                        dmsg(4,("SOSTENUTO (CENTER) PEDAL DOWN\n"));
1428                        pEngineChannel->SostenutoPedal = true;
1429    
1430                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1431                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1432                        #endif
1433    
1434                        SostenutoKeyCount = 0;
1435                        // Remeber the pressed keys
1436                        RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1437                        for (; iuiKey; ++iuiKey) {
1438                            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1439                            if (pKey->KeyPressed && SostenutoKeyCount < 128) SostenutoKeys[SostenutoKeyCount++] = *iuiKey;
1440                        }
1441                    }
1442                    if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SostenutoPedal) {
1443                        dmsg(4,("SOSTENUTO (CENTER) PEDAL UP\n"));
1444                        pEngineChannel->SostenutoPedal = false;
1445    
1446                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1447                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1448                        #endif
1449    
1450                        // release voices if the damper pedal is up and their respective key is not pressed
1451                        for (int i = 0; i < SostenutoKeyCount; i++) {
1452                            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[SostenutoKeys[i]];
1453                            if (!pKey->KeyPressed && !pEngineChannel->SustainPedal) {
1454                                RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1455                                if (itNewEvent) {
1456                                    *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1457                                  itNewEvent->Type = Event::type_release; // transform event type                                  itNewEvent->Type = Event::type_release; // transform event type
1458                              }                              }
1459                              else dmsg(1,("Event pool emtpy!\n"));                              else dmsg(1,("Event pool emtpy!\n"));
# Line 1053  namespace LinuxSampler { namespace gig { Line 1467  namespace LinuxSampler { namespace gig {
1467              // Channel Mode Messages              // Channel Mode Messages
1468    
1469              case 120: { // all sound off              case 120: { // all sound off
1470                  KillAllVoices(pEngineChannel, itControlChangeEventOnCCList);                  KillAllVoices(pEngineChannel, itControlChangeEvent);
1471                  break;                  break;
1472              }              }
1473              case 121: { // reset all controllers              case 121: { // reset all controllers
# Line 1061  namespace LinuxSampler { namespace gig { Line 1475  namespace LinuxSampler { namespace gig {
1475                  break;                  break;
1476              }              }
1477              case 123: { // all notes off              case 123: { // all notes off
1478                  ReleaseAllVoices(pEngineChannel, itControlChangeEventOnCCList);                  #if CONFIG_PROCESS_ALL_NOTES_OFF
1479                    ReleaseAllVoices(pEngineChannel, itControlChangeEvent);
1480                    #endif // CONFIG_PROCESS_ALL_NOTES_OFF
1481                    break;
1482                }
1483                case 126: { // mono mode on
1484                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1485                    pEngineChannel->SoloMode = true;
1486                    break;
1487                }
1488                case 127: { // poly mode on
1489                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1490                    pEngineChannel->SoloMode = false;
1491                  break;                  break;
1492              }              }
1493          }          }
1494    
1495            // handle FX send controllers
1496            if (!pEngineChannel->fxSends.empty()) {
1497                for (int iFxSend = 0; iFxSend < pEngineChannel->GetFxSendCount(); iFxSend++) {
1498                    FxSend* pFxSend = pEngineChannel->GetFxSend(iFxSend);
1499                    if (pFxSend->MidiController() == itControlChangeEvent->Param.CC.Controller)
1500                        pFxSend->SetLevel(itControlChangeEvent->Param.CC.Value);
1501                }
1502            }
1503      }      }
1504    
1505      /**      /**
# Line 1073  namespace LinuxSampler { namespace gig { Line 1508  namespace LinuxSampler { namespace gig {
1508       *  @param itSysexEvent - sysex data size and time stamp of the sysex event       *  @param itSysexEvent - sysex data size and time stamp of the sysex event
1509       */       */
1510      void Engine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) {      void Engine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) {
1511          RingBuffer<uint8_t>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();          RingBuffer<uint8_t,false>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();
1512    
1513          uint8_t exclusive_status, id;          uint8_t exclusive_status, id;
1514          if (!reader.pop(&exclusive_status)) goto free_sysex_data;          if (!reader.pop(&exclusive_status)) goto free_sysex_data;
# Line 1092  namespace LinuxSampler { namespace gig { Line 1527  namespace LinuxSampler { namespace gig {
1527    
1528                  // command address                  // command address
1529                  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)
1530                  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
1531                  if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;                  if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;
1532                  if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters                  if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters
1533                      dmsg(3,("\tSystem Parameter\n"));                      dmsg(3,("\tSystem Parameter\n"));
# Line 1139  namespace LinuxSampler { namespace gig { Line 1574  namespace LinuxSampler { namespace gig {
1574       *                     question       *                     question
1575       * @param DataSize   - size of the GS message data (in bytes)       * @param DataSize   - size of the GS message data (in bytes)
1576       */       */
1577      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) {
1578          RingBuffer<uint8_t>::NonVolatileReader reader = AddrReader;          RingBuffer<uint8_t,false>::NonVolatileReader reader = AddrReader;
1579          uint bytes = 3 /*addr*/ + DataSize;          uint bytes = 3 /*addr*/ + DataSize;
1580          uint8_t addr_and_data[bytes];          uint8_t addr_and_data[bytes];
1581          reader.read(&addr_and_data[0], bytes);          reader.read(&addr_and_data[0], bytes);
# Line 1199  namespace LinuxSampler { namespace gig { Line 1634  namespace LinuxSampler { namespace gig {
1634              RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();              RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
1635              for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key              for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
1636                  itVoice->Kill(itKillEvent);                  itVoice->Kill(itKillEvent);
1637                    --VoiceSpawnsLeft; //FIXME: just a temporary workaround, we should check the cause in StealVoice() instead
1638              }              }
1639          }          }
1640      }      }
1641    
1642      /**      /**
1643       * Initialize the parameter sequence for the modulation destination given by       * Determines whether the specified voice should be released.
1644       * by 'dst' with the constant value given by val.       *
1645         * @param pEngineChannel - The engine channel on which the voice should be checked
1646         * @param Key - The key number
1647         * @returns true if the specified should be released, false otherwise.
1648       */       */
1649      void Engine::ResetSynthesisParameters(Event::destination_t dst, float val) {      bool Engine::ShouldReleaseVoice(EngineChannel* pEngineChannel, int Key) {
1650          int maxsamples = pAudioOutputDevice->MaxSamplesPerCycle();          if (pEngineChannel->SustainPedal) return false;
1651          float* m = &pSynthesisParameters[dst][0];  
1652          for (int i = 0; i < maxsamples; i += 4) {          if (pEngineChannel->SostenutoPedal) {
1653             m[i]   = val;              for (int i = 0; i < SostenutoKeyCount; i++)
1654             m[i+1] = val;                  if (Key == SostenutoKeys[i]) return false;
            m[i+2] = val;  
            m[i+3] = val;  
1655          }          }
1656    
1657            return true;
1658      }      }
1659    
1660      uint Engine::VoiceCount() {      uint Engine::VoiceCount() {
# Line 1255  namespace LinuxSampler { namespace gig { Line 1694  namespace LinuxSampler { namespace gig {
1694      }      }
1695    
1696      String Engine::Version() {      String Engine::Version() {
1697          String s = "$Revision: 1.41 $";          String s = "$Revision: 1.71 $";
1698          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
1699      }      }
1700    
1701        InstrumentManager* Engine::GetInstrumentManager() {
1702            return &instruments;
1703        }
1704    
1705        // static constant initializers
1706        const float* Engine::VolumeCurve(InitVolumeCurve());
1707        const float* Engine::PanCurve(InitPanCurve());
1708        const float* Engine::CrossfadeCurve(InitCrossfadeCurve());
1709    
1710        float* Engine::InitVolumeCurve() {
1711            // line-segment approximation
1712            const float segments[] = {
1713                0, 0, 2, 0.0046, 16, 0.016, 31, 0.051, 45, 0.115, 54.5, 0.2,
1714                64.5, 0.39, 74, 0.74, 92, 1.03, 114, 1.94, 119.2, 2.2, 127, 2.2
1715            };
1716            return InitCurve(segments);
1717        }
1718    
1719        float* Engine::InitPanCurve() {
1720            // line-segment approximation
1721            const float segments[] = {
1722                0, 0, 1, 0,
1723                2, 0.05, 31.5, 0.7, 51, 0.851, 74.5, 1.12,
1724                127, 1.41, 128, 1.41
1725            };
1726            return InitCurve(segments, 129);
1727        }
1728    
1729        float* Engine::InitCrossfadeCurve() {
1730            // line-segment approximation
1731            const float segments[] = {
1732                0, 0, 1, 0.03, 10, 0.1, 51, 0.58, 127, 1
1733            };
1734            return InitCurve(segments);
1735        }
1736    
1737        float* Engine::InitCurve(const float* segments, int size) {
1738            float* y = new float[size];
1739            for (int x = 0 ; x < size ; x++) {
1740                if (x > segments[2]) segments += 2;
1741                y[x] = segments[1] + (x - segments[0]) *
1742                    (segments[3] - segments[1]) / (segments[2] - segments[0]);
1743            }
1744            return y;
1745        }
1746    
1747        /**
1748         * Changes the instrument for an engine channel.
1749         *
1750         * @param pEngineChannel - engine channel on which the instrument
1751         *                         should be changed
1752         * @param pInstrument - new instrument
1753         * @returns a list of dimension regions from the old instrument
1754         *          that are still in use
1755         */
1756        ::gig::DimensionRegion** Engine::ChangeInstrument(EngineChannel* pEngineChannel, ::gig::Instrument* pInstrument) {
1757            instrument_change_command_t command;
1758            command.pEngineChannel = pEngineChannel;
1759            command.pInstrument = pInstrument;
1760            InstrumentChangeQueue->push(&command);
1761    
1762            // wait for the audio thread to confirm that the instrument
1763            // change has been done
1764            instrument_change_reply_t reply;
1765            while (InstrumentChangeReplyQueue->pop(&reply) == 0) {
1766                usleep(10000);
1767            }
1768            return pDimRegionsInUse;
1769        }
1770    
1771  }} // namespace LinuxSampler::gig  }} // namespace LinuxSampler::gig

Legend:
Removed from v.649  
changed lines
  Added in v.1038

  ViewVC Help
Powered by ViewVC