/[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 716 by iliev, Sun Jul 24 06:57:30 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();          ResetScaleTuning();
124      }      }
# Line 126  namespace LinuxSampler { namespace gig { Line 127  namespace LinuxSampler { namespace gig {
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 139  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 178  namespace LinuxSampler { namespace gig { Line 177  namespace LinuxSampler { namespace gig {
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 203  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      /**      /**
# Line 232  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 249  namespace LinuxSampler { namespace gig { Line 256  namespace LinuxSampler { namespace gig {
256              // lower minimum release time              // lower minimum release time
257              const float minReleaseTime = (float) MaxSamplesPerCycle / (float) SampleRate;              const float minReleaseTime = (float) MaxSamplesPerCycle / (float) SampleRate;
258              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()) {
259                  iterVoice->pEG1->CalculateFadeOutCoeff(minReleaseTime, SampleRate);                  iterVoice->EG1.CalculateFadeOutCoeff(minReleaseTime, SampleRate);
260              }              }
261              pVoicePool->clear();              pVoicePool->clear();
262          }          }
# Line 261  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 277  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 327  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 350  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 397  namespace LinuxSampler { namespace gig { Line 389  namespace LinuxSampler { namespace gig {
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 533  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, false);                  LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false, false);
567              if (itNewVoice) {              if (itNewVoice) {
# Line 552  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 628  namespace LinuxSampler { namespace gig { Line 709  namespace LinuxSampler { namespace gig {
709          if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted          if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
710          #endif          #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 673  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 690  namespace LinuxSampler { namespace gig { Line 798  namespace LinuxSampler { namespace gig {
798          if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted          if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
799          #endif          #endif
800    
801          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];          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 716  namespace LinuxSampler { namespace gig { Line 886  namespace LinuxSampler { namespace gig {
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 804  namespace LinuxSampler { namespace gig { Line 974  namespace LinuxSampler { namespace gig {
974                      DimValues[i] = itNoteOnEvent->Param.Note.Velocity;                      DimValues[i] = itNoteOnEvent->Param.Note.Velocity;
975                      break;                      break;
976                  case ::gig::dimension_channelaftertouch:                  case ::gig::dimension_channelaftertouch:
977                      DimValues[i] = 0; //TODO: we currently ignore this dimension                      DimValues[i] = pEngineChannel->ControllerTable[128];
978                      break;                      break;
979                  case ::gig::dimension_releasetrigger:                  case ::gig::dimension_releasetrigger:
980                      VoiceType = (ReleaseTriggerVoice) ? Voice::type_release_trigger : (!iLayer) ? Voice::type_release_trigger_required : Voice::type_normal;                      VoiceType = (ReleaseTriggerVoice) ? Voice::type_release_trigger : (!iLayer) ? Voice::type_release_trigger_required : Voice::type_normal;
981                      DimValues[i] = (uint) ReleaseTriggerVoice;                      DimValues[i] = (uint) ReleaseTriggerVoice;
982                      break;                      break;
983                  case ::gig::dimension_keyboard:                  case ::gig::dimension_keyboard:
984                      DimValues[i] = (uint) pEngineChannel->CurrentKeyDimension;                      DimValues[i] = (uint) (pEngineChannel->CurrentKeyDimension * pRegion->pDimensionDefinitions[i].zones);
985                      break;                      break;
986                  case ::gig::dimension_roundrobin:                  case ::gig::dimension_roundrobin:
987                      DimValues[i] = (uint) pEngineChannel->pMIDIKeyInfo[MIDIKey].RoundRobinIndex; // incremented for each note on                      DimValues[i] = (uint) pEngineChannel->pMIDIKeyInfo[MIDIKey].RoundRobinIndex; // incremented for each note on
# Line 896  namespace LinuxSampler { namespace gig { Line 1066  namespace LinuxSampler { namespace gig {
1066                      std::cerr << "gig::Engine::LaunchVoice() Error: Unknown dimension\n" << std::flush;                      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);          ::gig::DimensionRegion* pDimRgn = pRegion->GetDimensionRegionByValue(DimValues);
1076    
1077          // no need to continue if sample is silent          // no need to continue if sample is silent
# Line 1125  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 1169  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                  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                      #if !CONFIG_PROCESS_MUTED_CHANNELS
# Line 1202  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                      #if !CONFIG_PROCESS_MUTED_CHANNELS
# Line 1221  namespace LinuxSampler { namespace gig { Line 1405  namespace LinuxSampler { namespace gig {
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();
1410                                if (itNewEvent) {
1411                                    *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();                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1455                              if (itNewEvent) {                              if (itNewEvent) {
1456                                  *itNewEvent = *itControlChangeEventOnCCList; // copy event to the key's own event list                                  *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 1238  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 1246  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;                  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;
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    
# Line 1258  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 1277  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 1324  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 1390  namespace LinuxSampler { namespace gig { Line 1640  namespace LinuxSampler { namespace gig {
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      void Engine::ResetSynthesisParameters(Event::destination_t dst, float val) {       * @param Key - The key number
1647          int maxsamples = pAudioOutputDevice->MaxSamplesPerCycle();       * @returns true if the specified should be released, false otherwise.
1648          float* m = &pSynthesisParameters[dst][0];       */
1649          for (int i = 0; i < maxsamples; i += 4) {      bool Engine::ShouldReleaseVoice(EngineChannel* pEngineChannel, int Key) {
1650             m[i]   = val;          if (pEngineChannel->SustainPedal) return false;
1651             m[i+1] = val;  
1652             m[i+2] = val;          if (pEngineChannel->SostenutoPedal) {
1653             m[i+3] = val;              for (int i = 0; i < SostenutoKeyCount; i++)
1654                    if (Key == SostenutoKeys[i]) return false;
1655          }          }
1656    
1657            return true;
1658      }      }
1659    
1660      uint Engine::VoiceCount() {      uint Engine::VoiceCount() {
# Line 1441  namespace LinuxSampler { namespace gig { Line 1694  namespace LinuxSampler { namespace gig {
1694      }      }
1695    
1696      String Engine::Version() {      String Engine::Version() {
1697          String s = "$Revision: 1.51 $";          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.716  
changed lines
  Added in v.1038

  ViewVC Help
Powered by ViewVC