/[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 271 by schoenebeck, Fri Oct 8 20:51:39 2004 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-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 23  Line 24 
24  #include <sstream>  #include <sstream>
25  #include "DiskThread.h"  #include "DiskThread.h"
26  #include "Voice.h"  #include "Voice.h"
27    #include "EGADSR.h"
28    #include "../EngineFactory.h"
29    
30  #include "Engine.h"  #include "Engine.h"
31    
32  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
33    
34      InstrumentResourceManager Engine::Instruments;      InstrumentResourceManager Engine::instruments;
35    
36        std::map<AudioOutputDevice*,Engine*> Engine::engines;
37    
38        /**
39         * Get a gig::Engine object for the given gig::EngineChannel and the
40         * given AudioOutputDevice. All engine channels which are connected to
41         * the same audio output device will use the same engine instance. This
42         * method will be called by a gig::EngineChannel whenever it's
43         * connecting to a audio output device.
44         *
45         * @param pChannel - engine channel which acquires an engine object
46         * @param pDevice  - the audio output device \a pChannel is connected to
47         */
48        Engine* Engine::AcquireEngine(LinuxSampler::gig::EngineChannel* pChannel, AudioOutputDevice* pDevice) {
49            Engine* pEngine = NULL;
50            // check if there's already an engine for the given audio output device
51            if (engines.count(pDevice)) {
52                dmsg(4,("Using existing gig::Engine.\n"));
53                pEngine = engines[pDevice];
54            } else { // create a new engine (and disk thread) instance for the given audio output device
55                dmsg(4,("Creating new gig::Engine.\n"));
56                pEngine = (Engine*) EngineFactory::Create("gig");
57                pEngine->Connect(pDevice);
58                engines[pDevice] = pEngine;
59            }
60    
61            // 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);
69            // remember index in the ArrayList
70            pChannel->iEngineIndexSelf = pEngine->engineChannels.size() - 1;
71            dmsg(4,("This gig::Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));
72            return pEngine;
73        }
74    
75        /**
76         * Once an engine channel is disconnected from an audio output device,
77         * it wil immediately call this method to unregister itself from the
78         * engine instance and if that engine instance is not used by any other
79         * engine channel anymore, then that engine instance will be destroyed.
80         *
81         * @param pChannel - engine channel which wants to disconnect from it's
82         *                   engine instance
83         * @param pDevice  - audio output device \a pChannel was connected to
84         */
85        void Engine::FreeEngine(LinuxSampler::gig::EngineChannel* pChannel, AudioOutputDevice* pDevice) {
86            dmsg(4,("Disconnecting EngineChannel from gig::Engine.\n"));
87            Engine* pEngine = engines[pDevice];
88            // unregister EngineChannel from the Engine instance
89            pEngine->engineChannels.remove(pChannel);
90            // if the used Engine instance is not used anymore, then destroy it
91            if (pEngine->engineChannels.empty()) {
92                pDevice->Disconnect(pEngine);
93                engines.erase(pDevice);
94                delete pEngine;
95                dmsg(4,("Destroying gig::Engine.\n"));
96            }
97            else dmsg(4,("This gig::Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));
98        }
99    
100        /**
101         * Constructor
102         */
103      Engine::Engine() {      Engine::Engine() {
         pRIFF              = NULL;  
         pGig               = NULL;  
         pInstrument        = NULL;  
104          pAudioOutputDevice = NULL;          pAudioOutputDevice = NULL;
105          pDiskThread        = NULL;          pDiskThread        = NULL;
106          pEventGenerator    = NULL;          pEventGenerator    = NULL;
107          pSysexBuffer       = new RingBuffer<uint8_t>(SYSEX_BUFFER_SIZE, 0);          pSysexBuffer       = new RingBuffer<uint8_t,false>(CONFIG_SYSEX_BUFFER_SIZE, 0);
108          pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT, 0);          pEventQueue        = new RingBuffer<Event,false>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);
109          pEventPool         = new Pool<Event>(MAX_EVENTS_PER_FRAGMENT);          pEventPool         = new Pool<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT);
110          pVoicePool         = new Pool<Voice>(MAX_AUDIO_VOICES);          pVoicePool         = new Pool<Voice>(CONFIG_MAX_VOICES);
111          pActiveKeys        = new Pool<uint>(128);          pDimRegionsInUse   = new ::gig::DimensionRegion*[CONFIG_MAX_VOICES + 1];
112          pVoiceStealingQueue = new RTList<Event>(pEventPool);          pVoiceStealingQueue = new RTList<Event>(pEventPool);
113          pEvents            = new RTList<Event>(pEventPool);          pGlobalEvents      = new RTList<Event>(pEventPool);
114          pCCEvents          = new RTList<Event>(pEventPool);          InstrumentChangeQueue      = new RingBuffer<instrument_change_command_t,false>(1, 0);
115          for (uint i = 0; i < Event::destination_count; i++) {          InstrumentChangeReplyQueue = new RingBuffer<instrument_change_reply_t,false>(1, 0);
116              pSynthesisEvents[i] = new RTList<Event>(pEventPool);  
         }  
         for (uint i = 0; i < 128; i++) {  
             pMIDIKeyInfo[i].pActiveVoices  = new RTList<Voice>(pVoicePool);  
             pMIDIKeyInfo[i].KeyPressed     = false;  
             pMIDIKeyInfo[i].Active         = false;  
             pMIDIKeyInfo[i].ReleaseTrigger = false;  
             pMIDIKeyInfo[i].pEvents        = new RTList<Event>(pEventPool);  
         }  
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;  
   
         InstrumentIdx = -1;  
         InstrumentStat = -1;  
   
         AudioDeviceChannelLeft  = -1;  
         AudioDeviceChannelRight = -1;  
   
122          ResetInternal();          ResetInternal();
123            ResetScaleTuning();
124      }      }
125    
126        /**
127         * Destructor
128         */
129      Engine::~Engine() {      Engine::~Engine() {
130            MidiInputPort::RemoveSysexListener(this);
131          if (pDiskThread) {          if (pDiskThread) {
132                dmsg(1,("Stopping disk thread..."));
133              pDiskThread->StopThread();              pDiskThread->StopThread();
134              delete pDiskThread;              delete pDiskThread;
135                dmsg(1,("OK\n"));
136          }          }
         if (pGig)  delete pGig;  
         if (pRIFF) delete pRIFF;  
         for (uint i = 0; i < 128; i++) {  
             if (pMIDIKeyInfo[i].pActiveVoices) delete pMIDIKeyInfo[i].pActiveVoices;  
             if (pMIDIKeyInfo[i].pEvents)       delete pMIDIKeyInfo[i].pEvents;  
         }  
         for (uint i = 0; i < Event::destination_count; i++) {  
             if (pSynthesisEvents[i]) delete pSynthesisEvents[i];  
         }  
         delete[] pSynthesisEvents;  
         if (pEvents)     delete pEvents;  
         if (pCCEvents)   delete pCCEvents;  
137          if (pEventQueue) delete pEventQueue;          if (pEventQueue) delete pEventQueue;
138          if (pEventPool)  delete pEventPool;          if (pEventPool)  delete pEventPool;
139          if (pVoicePool)  delete pVoicePool;          if (pVoicePool) {
140          if (pActiveKeys) delete pActiveKeys;              pVoicePool->clear();
141          if (pSysexBuffer) delete pSysexBuffer;              delete pVoicePool;
142            }
143          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
         if (pMainFilterParameters) delete[] pMainFilterParameters;  
         if (pBasicFilterParameters) delete[] pBasicFilterParameters;  
         if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];  
144          if (pVoiceStealingQueue) delete pVoiceStealingQueue;          if (pVoiceStealingQueue) delete pVoiceStealingQueue;
145            if (pSysexBuffer) delete pSysexBuffer;
146            Unregister();
147      }      }
148    
149      void Engine::Enable() {      void Engine::Enable() {
# Line 126  namespace LinuxSampler { namespace gig { Line 170  namespace LinuxSampler { namespace gig {
170       */       */
171      void Engine::Reset() {      void Engine::Reset() {
172          DisableAndLock();          DisableAndLock();
   
         //if (pAudioOutputDevice->IsPlaying()) { // if already running  
             /*  
             // signal audio thread not to enter render part anymore  
             SuspensionRequested = true;  
             // sleep until wakened by audio thread  
             pthread_mutex_lock(&__render_state_mutex);  
             pthread_cond_wait(&__render_exit_condition, &__render_state_mutex);  
             pthread_mutex_unlock(&__render_state_mutex);  
             */  
         //}  
   
         //if (wasplaying) pAudioOutputDevice->Stop();  
   
173          ResetInternal();          ResetInternal();
174            ResetScaleTuning();
         // signal audio thread to continue with rendering  
         //SuspensionRequested = false;  
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          Pitch               = 0;          ResetInternalMutex.Lock();
184          SustainPedal        = false;  
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;
         GlobalVolume        = 1.0;  
190    
191          // reset voice stealing parameters          // reset voice stealing parameters
         itLastStolenVoice = RTList<Voice>::Iterator();  
         iuiLastStolenKey  = RTList<uint>::Iterator();  
192          pVoiceStealingQueue->clear();          pVoiceStealingQueue->clear();
193            itLastStolenVoice          = RTList<Voice>::Iterator();
194          // reset to normal chromatic scale (means equal temper)          itLastStolenVoiceGlobally  = RTList<Voice>::Iterator();
195          memset(&ScaleTuning[0], 0x00, 12);          iuiLastStolenKey           = RTList<uint>::Iterator();
196            iuiLastStolenKeyGlobally   = RTList<uint>::Iterator();
197          // set all MIDI controller values to zero          pLastStolenChannel         = NULL;
         memset(ControllerTable, 0x00, 128);  
   
         // reset key info  
         for (uint i = 0; i < 128; i++) {  
             pMIDIKeyInfo[i].pActiveVoices->clear();  
             pMIDIKeyInfo[i].pEvents->clear();  
             pMIDIKeyInfo[i].KeyPressed     = false;  
             pMIDIKeyInfo[i].Active         = false;  
             pMIDIKeyInfo[i].ReleaseTrigger = false;  
             pMIDIKeyInfo[i].itSelf         = Pool<uint>::Iterator();  
         }  
   
         // reset all key groups  
         map<uint,uint*>::iterator iter = ActiveKeyGroups.begin();  
         for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;  
198    
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()) {
# Line 189  namespace LinuxSampler { namespace gig { Line 202  namespace LinuxSampler { namespace gig {
202          }          }
203          pVoicePool->clear();          pVoicePool->clear();
204    
         // free all active keys  
         pActiveKeys->clear();  
   
205          // reset disk thread          // reset disk thread
206          if (pDiskThread) pDiskThread->Reset();          if (pDiskThread) pDiskThread->Reset();
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       *  Load an instrument from a .gig file.       * Reset to normal, chromatic scale (means equal tempered).
      *  
      *  @param FileName   - file name of the Gigasampler instrument file  
      *  @param Instrument - index of the instrument in the .gig file  
      *  @throws LinuxSamplerException  on error  
      *  @returns          detailed description of the method call result  
217       */       */
218      void Engine::LoadInstrument(const char* FileName, uint Instrument) {      void Engine::ResetScaleTuning() {
219            memset(&ScaleTuning[0], 0x00, 12);
         DisableAndLock();  
   
         ResetInternal(); // reset engine  
   
         // free old instrument  
         if (pInstrument) {  
             // give old instrument back to instrument manager  
             Instruments.HandBack(pInstrument, this);  
         }  
   
         InstrumentFile = FileName;  
         InstrumentIdx = Instrument;  
         InstrumentStat = 0;  
   
         // delete all key groups  
         ActiveKeyGroups.clear();  
   
         // request gig instrument from instrument manager  
         try {  
             instrument_id_t instrid;  
             instrid.FileName    = FileName;  
             instrid.iInstrument = Instrument;  
             pInstrument = Instruments.Borrow(instrid, this);  
             if (!pInstrument) {  
                 InstrumentStat = -1;  
                 dmsg(1,("no instrument loaded!!!\n"));  
                 exit(EXIT_FAILURE);  
             }  
         }  
         catch (RIFF::Exception e) {  
             InstrumentStat = -2;  
             String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;  
             throw LinuxSamplerException(msg);  
         }  
         catch (InstrumentResourceManagerException e) {  
             InstrumentStat = -3;  
             String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();  
             throw LinuxSamplerException(msg);  
         }  
         catch (...) {  
             InstrumentStat = -4;  
             throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");  
         }  
   
         // rebuild ActiveKeyGroups map with key groups of current instrument  
         for (::gig::Region* pRegion = pInstrument->GetFirstRegion(); pRegion; pRegion = pInstrument->GetNextRegion())  
             if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL;  
   
         InstrumentStat = 100;  
   
         // inform audio driver for the need of two channels  
         try {  
             if (pAudioOutputDevice) pAudioOutputDevice->AcquireChannels(2); // gig Engine only stereo  
         }  
         catch (AudioOutputException e) {  
             String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();  
             throw LinuxSamplerException(msg);  
         }  
   
         Enable();  
     }  
   
     /**  
      * Will be called by the InstrumentResourceManager when the instrument  
      * we are currently using in this engine is going to be updated, so we  
      * can stop playback before that happens.  
      */  
     void Engine::ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {  
         dmsg(3,("gig::Engine: Received instrument update message.\n"));  
         DisableAndLock();  
         ResetInternal();  
         this->pInstrument = NULL;  
220      }      }
221    
222      /**      /**
223       * Will be called by the InstrumentResourceManager when the instrument       * Connect this engine instance with the given audio output device.
224       * update process was completed, so we can continue with playback.       * This method will be called when an Engine instance is created.
225         * All of the engine's data structures which are dependant to the used
226         * audio output device / driver will be (re)allocated and / or
227         * adjusted appropriately.
228         *
229         * @param pAudioOut - audio output device to connect to
230       */       */
     void Engine::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {  
         this->pInstrument = pNewResource; //TODO: there are couple of engine parameters we should update here as well if the instrument was updated (see LoadInstrument())  
         Enable();  
     }  
   
231      void Engine::Connect(AudioOutputDevice* pAudioOut) {      void Engine::Connect(AudioOutputDevice* pAudioOut) {
232          pAudioOutputDevice = pAudioOut;          pAudioOutputDevice = pAudioOut;
233    
# Line 303  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->AudioDeviceChannelLeft  = 0;          this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle();
246          this->AudioDeviceChannelRight = 1;          this->SampleRate         = pAudioOutputDevice->SampleRate();
247          this->pOutputLeft             = pAudioOutputDevice->Channel(0)->Buffer();  
248          this->pOutputRight            = pAudioOutputDevice->Channel(1)->Buffer();          // FIXME: audio drivers with varying fragment sizes might be a problem here
249          this->MaxSamplesPerCycle      = pAudioOutputDevice->MaxSamplesPerCycle();          MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * CONFIG_EG_MIN_RELEASE_TIME) - 1;
250          this->SampleRate              = pAudioOutputDevice->SampleRate();          if (MaxFadeOutPos < 0) {
251                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) {
266                dmsg(1,("Stopping disk thread..."));
267              this->pDiskThread->StopThread();              this->pDiskThread->StopThread();
268              delete this->pDiskThread;              delete this->pDiskThread;
269                dmsg(1,("OK\n"));
270          }          }
271          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << CONFIG_MAX_PITCH) << 1) + 6, //FIXME: assuming stereo
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 334  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]) delete[] pSynthesisParameters[0];  
         pSynthesisParameters[0] = new float[Event::destination_count * pAudioOut->MaxSamplesPerCycle()];  
         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 358  namespace LinuxSampler { namespace gig { Line 297  namespace LinuxSampler { namespace gig {
297          }          }
298      }      }
299    
300      void Engine::DisconnectAudioOutputDevice() {      /**
301          if (pAudioOutputDevice) { // if clause to prevent disconnect loops       * Clear all engine global event lists.
302              AudioOutputDevice* olddevice = pAudioOutputDevice;       */
303              pAudioOutputDevice = NULL;      void Engine::ClearEventLists() {
304              olddevice->Disconnect(this);          pGlobalEvents->clear();
305              AudioDeviceChannelLeft  = -1;      }
306              AudioDeviceChannelRight = -1;  
307        /**
308         * Copy all events from the engine's global input queue buffer to the
309         * engine's internal event list. This will be done at the beginning of
310         * each audio cycle (that is each RenderAudio() call) to distinguish
311         * all global events which have to be processed in the current audio
312         * cycle. These events are usually just SysEx messages. Every
313         * EngineChannel has it's own input event queue buffer and event list
314         * to handle common events like NoteOn, NoteOff and ControlChange
315         * events.
316         *
317         * @param Samples - number of sample points to be processed in the
318         *                  current audio cycle
319         */
320        void Engine::ImportEvents(uint Samples) {
321            RingBuffer<Event,false>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
322            Event* pEvent;
323            while (true) {
324                // get next event from input event queue
325                if (!(pEvent = eventQueueReader.pop())) break;
326                // if younger event reached, ignore that and all subsequent ones for now
327                if (pEvent->FragmentPos() >= Samples) {
328                    eventQueueReader--;
329                    dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
330                    pEvent->ResetFragmentPos();
331                    break;
332                }
333                // copy event to internal event list
334                if (pGlobalEvents->poolIsEmpty()) {
335                    dmsg(1,("Event pool emtpy!\n"));
336                    break;
337                }
338                *pGlobalEvents->allocAppend() = *pEvent;
339          }          }
340            eventQueueReader.free(); // free all copied events from input queue
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 no instrument loaded or engine disabled          // return if engine disabled
358          if (EngineDisabled.Pop()) {          if (EngineDisabled.Pop()) {
359              dmsg(5,("gig::Engine: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));              dmsg(5,("gig::Engine: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));
360              return 0;              return 0;
361          }          }
         if (!pInstrument) {  
             dmsg(5,("gig::Engine: no instrument loaded\n"));  
             return 0;  
         }  
   
   
         // empty the event lists for the new fragment  
         pEvents->clear();  
         pCCEvents->clear();  
         for (uint i = 0; i < Event::destination_count; i++) {  
             pSynthesisEvents[i]->clear();  
         }  
         {  
             RTList<uint>::Iterator iuiKey = pActiveKeys->first();  
             RTList<uint>::Iterator end    = pActiveKeys->end();  
             for(; iuiKey != end; ++iuiKey) {  
                 pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key  
             }  
         }  
   
         // read and copy events from input queue  
         Event event = pEventGenerator->CreateEvent();  
         while (true) {  
             if (!pEventQueue->pop(&event) || pEvents->poolIsEmpty()) break;  
             *pEvents->allocAppend() = event;  
         }  
   
362    
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
372            // (these are usually just SysEx messages)
373            ImportEvents(Samples);
374    
375          // process events          // process engine global events (these are currently only MIDI System Exclusive messages)
376          {          {
377              RTList<Event>::Iterator itEvent = pEvents->first();              RTList<Event>::Iterator itEvent = pGlobalEvents->first();
378              RTList<Event>::Iterator end     = pEvents->end();              RTList<Event>::Iterator end     = pGlobalEvents->end();
379              for (; itEvent != end; ++itEvent) {              for (; itEvent != end; ++itEvent) {
380                  switch (itEvent->Type) {                  switch (itEvent->Type) {
                     case Event::type_note_on:  
                         dmsg(5,("Engine: Note on received\n"));  
                         ProcessNoteOn(itEvent);  
                         break;  
                     case Event::type_note_off:  
                         dmsg(5,("Engine: Note off received\n"));  
                         ProcessNoteOff(itEvent);  
                         break;  
                     case Event::type_control_change:  
                         dmsg(5,("Engine: MIDI CC received\n"));  
                         ProcessControlChange(itEvent);  
                         break;  
                     case Event::type_pitchbend:  
                         dmsg(5,("Engine: Pitchbend received\n"));  
                         ProcessPitchbend(itEvent);  
                         break;  
381                      case Event::type_sysex:                      case Event::type_sysex:
382                          dmsg(5,("Engine: Sysex received\n"));                          dmsg(5,("Engine: Sysex received\n"));
383                          ProcessSysex(itEvent);                          ProcessSysex(itEvent);
# Line 448  namespace LinuxSampler { namespace gig { Line 386  namespace LinuxSampler { namespace gig {
386              }              }
387          }          }
388    
389            // reset internal voice counter (just for statistic of active voices)
390            ActiveVoiceCountTemp = 0;
391    
392          int active_voices = 0;          // handle instrument change commands
393            instrument_change_command_t command;
394          // render audio from all active voices          if (InstrumentChangeQueue->pop(&command) > 0) {
395          {              EngineChannel* pEngineChannel = command.pEngineChannel;
396              RTList<uint>::Iterator iuiKey = pActiveKeys->first();              pEngineChannel->pInstrument = command.pInstrument;
397              RTList<uint>::Iterator end    = pActiveKeys->end();  
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              while (iuiKey != end) { // iterate through all active keys
406                  midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];                  midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
407                  ++iuiKey;                  ++iuiKey;
408    
409                  RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();                  RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
410                  RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();                  RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
411                  for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key                  for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
412                      // now render current voice                      if (!itVoice->Orphan) {
413                      itVoice->Render(Samples);                          itVoice->Orphan = true;
414                      if (itVoice->IsActive()) active_voices++; // still active                          pDimRegionsInUse[i++] = itVoice->pDimRgn;
                     else { // voice reached end, is now inactive  
                         KillVoiceImmediately(itVoice); // remove voice from the list of active voices  
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
426            for (int i = 0; i < engineChannels.size(); i++) {
427                ProcessEvents(engineChannels[i], Samples);
428            }
429    
430          // now render all postponed voices from voice stealing          // render all 'normal', active voices on all engine channels
431          {          for (int i = 0; i < engineChannels.size(); i++) {
432              RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();              RenderActiveVoices(engineChannels[i], Samples);
             RTList<Event>::Iterator end               = pVoiceStealingQueue->end();  
             for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {  
                 Pool<Voice>::Iterator itNewVoice = LaunchVoice(itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false);  
                 if (itNewVoice) {  
                     itNewVoice->Render(Samples);  
                     if (itNewVoice->IsActive()) active_voices++; // still active  
                     else { // voice reached end, is now inactive  
                         KillVoiceImmediately(itNewVoice); // remove voice from the list of active voices  
                     }  
                 }  
                 else dmsg(1,("Ouch, voice stealing didn't work out!\n"));  
             }  
433          }          }
         // reset voice stealing for the new fragment  
         pVoiceStealingQueue->clear();  
         itLastStolenVoice = RTList<Voice>::Iterator();  
         iuiLastStolenKey  = RTList<uint>::Iterator();  
434    
435            // now that all ordinary voices on ALL engine channels are rendered, render new stolen voices
436            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          // write that to the disk thread class so that it can print it          // handle cleanup on all engine channels for the next audio fragment
445          // on the console for debugging purposes          for (int i = 0; i < engineChannels.size(); i++) {
446          ActiveVoiceCount = active_voices;              PostProcess(engineChannels[i]);
447            }
448    
449    
450            // empty the engine's event list for the next audio fragment
451            ClearEventLists();
452    
453            // reset voice stealing for the next audio fragment
454            pVoiceStealingQueue->clear();
455    
456            // just some statistics about this engine instance
457            ActiveVoiceCount = ActiveVoiceCountTemp;
458          if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;          if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;
459    
460            FrameTime += Samples;
461    
462          return 0;          return 0;
463      }      }
464    
465      /**      /**
466       *  Will be called by the MIDIIn Thread to let the audio thread trigger a new       * Dispatch and handle all events in this audio fragment for the given
467       *  voice for the given key.       * engine channel.
468       *       *
469       *  @param Key      - MIDI key number of the triggered key       * @param pEngineChannel - engine channel on which events should be
470       *  @param Velocity - MIDI velocity value of the triggered key       *                         processed
471       */       * @param Samples        - amount of sample points to be processed in
472      void Engine::SendNoteOn(uint8_t Key, uint8_t Velocity) {       *                         this audio fragment cycle
473          Event event               = pEventGenerator->CreateEvent();       */
474          event.Type                = Event::type_note_on;      void Engine::ProcessEvents(EngineChannel* pEngineChannel, uint Samples) {
475          event.Param.Note.Key      = Key;          // get all events from the engine channels's input event queue which belong to the current fragment
476          event.Param.Note.Velocity = Velocity;          // (these are the common events like NoteOn, NoteOff, ControlChange, etc.)
477          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          pEngineChannel->ImportEvents(Samples);
478          else dmsg(1,("Engine: Input event queue full!"));  
479            // process events
480            {
481                RTList<Event>::Iterator itEvent = pEngineChannel->pEvents->first();
482                RTList<Event>::Iterator end     = pEngineChannel->pEvents->end();
483                for (; itEvent != end; ++itEvent) {
484                    switch (itEvent->Type) {
485                        case Event::type_note_on:
486                            dmsg(5,("Engine: Note on received\n"));
487                            ProcessNoteOn((EngineChannel*)itEvent->pEngineChannel, itEvent);
488                            break;
489                        case Event::type_note_off:
490                            dmsg(5,("Engine: Note off received\n"));
491                            ProcessNoteOff((EngineChannel*)itEvent->pEngineChannel, itEvent);
492                            break;
493                        case Event::type_control_change:
494                            dmsg(5,("Engine: MIDI CC received\n"));
495                            ProcessControlChange((EngineChannel*)itEvent->pEngineChannel, itEvent);
496                            break;
497                        case Event::type_pitchbend:
498                            dmsg(5,("Engine: Pitchbend received\n"));
499                            ProcessPitchbend((EngineChannel*)itEvent->pEngineChannel, itEvent);
500                            break;
501                    }
502                }
503            }
504    
505            // reset voice stealing for the next engine channel (or next audio fragment)
506            itLastStolenVoice         = RTList<Voice>::Iterator();
507            itLastStolenVoiceGlobally = RTList<Voice>::Iterator();
508            iuiLastStolenKey          = RTList<uint>::Iterator();
509            iuiLastStolenKeyGlobally  = RTList<uint>::Iterator();
510            pLastStolenChannel        = NULL;
511      }      }
512    
513      /**      /**
514       *  Will be called by the MIDIIn Thread to signal the audio thread to release       * Render all 'normal' voices (that is voices which were not stolen in
515       *  voice(s) on the given key.       * this fragment) on the given engine channel.
516       *       *
517       *  @param Key      - MIDI key number of the released key       * @param pEngineChannel - engine channel on which audio should be
518       *  @param Velocity - MIDI release velocity value of the released key       *                         rendered
519       */       * @param Samples        - amount of sample points to be rendered in
520      void Engine::SendNoteOff(uint8_t Key, uint8_t Velocity) {       *                         this audio fragment cycle
521          Event event               = pEventGenerator->CreateEvent();       */
522          event.Type                = Event::type_note_off;      void Engine::RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {
523          event.Param.Note.Key      = Key;          #if !CONFIG_PROCESS_MUTED_CHANNELS
524          event.Param.Note.Velocity = Velocity;          if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
525          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          #endif
526          else dmsg(1,("Engine: Input event queue full!"));  
527            RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
528            RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
529            while (iuiKey != end) { // iterate through all active keys
530                midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
531                ++iuiKey;
532    
533                RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
534                RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
535                for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
536                    // now render current voice
537                    itVoice->Render(Samples);
538                    if (itVoice->IsActive()) ActiveVoiceCountTemp++; // still active
539                    else { // voice reached end, is now inactive
540                        FreeVoice(pEngineChannel, itVoice); // remove voice from the list of active voices
541                    }
542                }
543            }
544        }
545    
546        /**
547         * Render all stolen voices (only voices which were stolen in this
548         * fragment) on the given engine channel. Stolen voices are rendered
549         * after all normal voices have been rendered; this is needed to render
550         * audio of those voices which were selected for voice stealing until
551         * the point were the stealing (that is the take over of the voice)
552         * actually happened.
553         *
554         * @param pEngineChannel - engine channel on which audio should be
555         *                         rendered
556         * @param Samples        - amount of sample points to be rendered in
557         *                         this audio fragment cycle
558         */
559        void Engine::RenderStolenVoices(uint Samples) {
560            RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();
561            RTList<Event>::Iterator end               = pVoiceStealingQueue->end();
562            for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
563                EngineChannel* pEngineChannel = (EngineChannel*) itVoiceStealEvent->pEngineChannel;
564                if (!pEngineChannel->pInstrument) continue; // ignore if no instrument loaded
565                Pool<Voice>::Iterator itNewVoice =
566                    LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false, false);
567                if (itNewVoice) {
568                    itNewVoice->Render(Samples);
569                    if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active
570                    else { // voice reached end, is now inactive
571                        FreeVoice(pEngineChannel, itNewVoice); // remove voice from the list of active voices
572                    }
573                }
574                else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));
575    
576                // we need to clear the key's event list explicitly here in case key was never active
577                midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itVoiceStealEvent->Param.Note.Key];
578                pKey->VoiceTheftsQueued--;
579                if (!pKey->Active && !pKey->VoiceTheftsQueued) pKey->pEvents->clear();
580            }
581      }      }
582    
583      /**      /**
584       *  Will be called by the MIDIIn Thread to signal the audio thread to change       * Will be called in case the respective engine channel sports FX send
585       *  the pitch value for all voices.       * 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 Pitch - MIDI pitch value (-8192 ... +8191)       * @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::SendPitchbend(int Pitch) {      void Engine::RouteAudio(EngineChannel* pEngineChannel, uint Samples) {
597          Event event             = pEventGenerator->CreateEvent();          // route master signal
598          event.Type              = Event::type_pitchbend;          {
599          event.Param.Pitch.Pitch = Pitch;              AudioChannel* pDstL = pAudioOutputDevice->Channel(pEngineChannel->AudioDeviceChannelLeft);
600          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);              AudioChannel* pDstR = pAudioOutputDevice->Channel(pEngineChannel->AudioDeviceChannelRight);
601          else dmsg(1,("Engine: Input event queue full!"));              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       *  Will be called by the MIDIIn Thread to signal the audio thread that a       * Free all keys which have turned inactive in this audio fragment, from
637       *  continuous controller value has changed.       * the list of active keys and clear all event lists on that engine
638         * channel.
639       *       *
640       *  @param Controller - MIDI controller number of the occured control change       * @param pEngineChannel - engine channel to cleanup
      *  @param Value      - value of the control change  
641       */       */
642      void Engine::SendControlChange(uint8_t Controller, uint8_t Value) {      void Engine::PostProcess(EngineChannel* pEngineChannel) {
643          Event event               = pEventGenerator->CreateEvent();          // free all keys which have no active voices left
644          event.Type                = Event::type_control_change;          {
645          event.Param.CC.Controller = Controller;              RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
646          event.Param.CC.Value      = Value;              RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
647          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);              while (iuiKey != end) { // iterate through all active keys
648          else dmsg(1,("Engine: Input event queue full!"));                  midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
649                    ++iuiKey;
650                    if (pKey->pActiveVoices->isEmpty()) FreeKey(pEngineChannel, pKey);
651                    #if CONFIG_DEVMODE
652                    else { // just a sanity check for debugging
653                        RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
654                        RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
655                        for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
656                            if (itVoice->itKillEvent) {
657                                dmsg(1,("gig::Engine: ERROR, killed voice survived !!!\n"));
658                            }
659                        }
660                    }
661                    #endif // CONFIG_DEVMODE
662                }
663            }
664    
665            // empty the engine channel's own event lists
666            pEngineChannel->ClearEventLists();
667      }      }
668    
669      /**      /**
# Line 577  namespace LinuxSampler { namespace gig { Line 677  namespace LinuxSampler { namespace gig {
677          Event event             = pEventGenerator->CreateEvent();          Event event             = pEventGenerator->CreateEvent();
678          event.Type              = Event::type_sysex;          event.Type              = Event::type_sysex;
679          event.Param.Sysex.Size  = Size;          event.Param.Sysex.Size  = Size;
680            event.pEngineChannel    = NULL; // as Engine global event
681          if (pEventQueue->write_space() > 0) {          if (pEventQueue->write_space() > 0) {
682              if (pSysexBuffer->write_space() >= Size) {              if (pSysexBuffer->write_space() >= Size) {
683                  // copy sysex data to input buffer                  // copy sysex data to input buffer
# Line 592  namespace LinuxSampler { namespace gig { Line 693  namespace LinuxSampler { namespace gig {
693                  // finally place sysex event into input event queue                  // finally place sysex event into input event queue
694                  pEventQueue->push(&event);                  pEventQueue->push(&event);
695              }              }
696              else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,SYSEX_BUFFER_SIZE));              else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,CONFIG_SYSEX_BUFFER_SIZE));
697          }          }
698          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
699      }      }
# Line 600  namespace LinuxSampler { namespace gig { Line 701  namespace LinuxSampler { namespace gig {
701      /**      /**
702       *  Assigns and triggers a new voice for the respective MIDI key.       *  Assigns and triggers a new voice for the respective MIDI key.
703       *       *
704         *  @param pEngineChannel - engine channel on which this event occured on
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(Pool<Event>::Iterator& itNoteOnEvent) {      void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
708          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];          #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;
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
746            {
747                const ::gig::Instrument* pInstrument = pEngineChannel->pInstrument;
748                if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high)
749                    pEngineChannel->CurrentKeyDimension = float(key - pInstrument->DimensionKeyRange.low) /
750                        (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);
751            }
752    
753          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
754            pKey->Velocity   = itNoteOnEventOnKeyList->Param.Note.Velocity;
755            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 && !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    
767          // move note on event to the key's own event list          // allocate and trigger new voice(s) for the key
768          RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);          {
769                // first, get total amount of required voices (dependant on amount of layers)
770                ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOnEventOnKeyList->Param.Note.Key);
771                if (pRegion) {
772                    int voicesRequired = pRegion->Layers;
773                    // now launch the required amount of voices
774                    for (int i = 0; i < voicesRequired; i++)
775                        LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true, true);
776                }
777            }
778    
779            // if neither a voice was spawned or postponed then remove note on event from key again
780            if (!pKey->Active && !pKey->VoiceTheftsQueued)
781                pKey->pEvents->free(itNoteOnEventOnKeyList);
782    
783          // allocate and trigger a new voice for the key          if (!pEngineChannel->SoloMode || pEngineChannel->PortamentoPos < 0.0f) pEngineChannel->PortamentoPos = (float) key;
784          LaunchVoice(itNoteOnEventOnKeyList);          pKey->RoundRobinIndex++;
785      }      }
786    
787      /**      /**
# Line 630  namespace LinuxSampler { namespace gig { Line 790  namespace LinuxSampler { namespace gig {
790       *  sustain pedal will be released or voice turned inactive by itself (e.g.       *  sustain pedal will be released or voice turned inactive by itself (e.g.
791       *  due to completion of sample playback).       *  due to completion of sample playback).
792       *       *
793         *  @param pEngineChannel - engine channel on which this event occured on
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(Pool<Event>::Iterator& itNoteOffEvent) {      void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {
797          midi_key_info_t* pKey = &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    
         // release voices on this key if needed  
         if (pKey->Active && !SustainPedal) {  
             itNoteOffEvent->Type = Event::type_release; // transform event type  
         }  
   
805          // move event to the key's own event list          // move event to the key's own event list
806          RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);          RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
807    
808          // spawn release triggered voice(s) if needed          bool bShouldRelease = pKey->Active && ShouldReleaseVoice(pEngineChannel, itNoteOffEventOnKeyList->Param.Note.Key);
809          if (pKey->ReleaseTrigger) {  
810              LaunchVoice(itNoteOffEventOnKeyList, 0, true);          // in case Solo Mode is enabled, kill all voices on this key and respawn a voice on the highest pressed key (if any)
811              pKey->ReleaseTrigger = false;          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
874                if (pKey->ReleaseTrigger && pEngineChannel->pInstrument) {
875                    // first, get total amount of required voices (dependant on amount of layers)
876                    ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOffEventOnKeyList->Param.Note.Key);
877                    if (pRegion) {
878                        int voicesRequired = pRegion->Layers;
879    
880                        // MIDI note-on velocity is used instead of note-off velocity
881                        itNoteOffEventOnKeyList->Param.Note.Velocity = pKey->Velocity;
882    
883                        // now launch the required amount of voices
884                        for (int i = 0; i < voicesRequired; i++)
885                            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;
888                }
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
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(Pool<Event>::Iterator& itPitchbendEvent) {      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {
905          this->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value          pEngineChannel->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value
         itPitchbendEvent.moveToEndOf(pSynthesisEvents[Event::destination_vco]);  
906      }      }
907    
908      /**      /**
# Line 668  namespace LinuxSampler { namespace gig { Line 910  namespace LinuxSampler { namespace gig {
910       *  called by the ProcessNoteOn() method and by the voices itself       *  called by the ProcessNoteOn() method and by the voices itself
911       *  (e.g. to spawn further voices on the same key for layered sounds).       *  (e.g. to spawn further voices on the same key for layered sounds).
912       *       *
913         *  @param pEngineChannel      - engine channel on which this event occured on
914       *  @param itNoteOnEvent       - key, velocity and time stamp of the event       *  @param itNoteOnEvent       - key, velocity and time stamp of the event
915       *  @param iLayer              - layer index for the new voice (optional - only       *  @param iLayer              - layer index for the new voice (optional - only
916       *                               in case of layered sounds of course)       *                               in case of layered sounds of course)
# Line 676  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 an error occured while trying to trigger the new voice       *           if the voice wasn't triggered (for example when no region is
926         *           defined for the given key).
927       */       */
928      Pool<Voice>::Iterator Engine::LaunchVoice(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 = &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(itNoteOnEvent, this->Pitch, this->pInstrument, iLayer, ReleaseTriggerVoice) < 0) {              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pDimRgn, VoiceType, iKeyGroup) < 0) {
1085                  dmsg(1,("Triggering new voice failed!\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 = &ActiveKeyGroups[itNewVoice->KeyGroup];  
                     if (*ppKeyGroup) { // if there's already an active key in that key group  
                         midi_key_info_t* pOtherKey = &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 = 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)
1100                  return itNewVoice; // success                  return itNewVoice; // success
1101              }              }
1102          }          }
1103          else if (VoiceStealing) StealVoice(itNoteOnEvent, iLayer, ReleaseTriggerVoice); // no free voice left, so steal one          else if (VoiceStealing) {
1104                // try to steal one voice
1105                int result = StealVoice(pEngineChannel, itNoteOnEvent);
1106                if (!result) { // voice stolen successfully
1107                    // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died
1108                    RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();
1109                    if (itStealEvent) {
1110                        *itStealEvent = *itNoteOnEvent; // copy event
1111                        itStealEvent->Param.Note.Layer = iLayer;
1112                        itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;
1113                        pKey->VoiceTheftsQueued++;
1114                    }
1115                    else dmsg(1,("Voice stealing queue full!\n"));
1116                }
1117            }
1118    
1119          return Pool<Voice>::Iterator(); // no free voice or error          return Pool<Voice>::Iterator(); // no free voice or error
1120      }      }
# Line 727  namespace LinuxSampler { namespace gig { Line 1125  namespace LinuxSampler { namespace gig {
1125       *  voice stealing and postpone the note-on event until the selected       *  voice stealing and postpone the note-on event until the selected
1126       *  voice actually died.       *  voice actually died.
1127       *       *
1128       *  @param itNoteOnEvent       - key, velocity and time stamp of the event       *  @param pEngineChannel - engine channel on which this event occured on
1129       *  @param iLayer              - layer index for the new voice       *  @param itNoteOnEvent - key, velocity and time stamp of the event
1130       *  @param ReleaseTriggerVoice - if new voice is a release triggered voice       *  @returns 0 on success, a value < 0 if no active voice could be picked for voice stealing
1131       */       */
1132      void Engine::StealVoice(Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice) {      int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
1133            if (VoiceSpawnsLeft <= 0) {
1134                dmsg(1,("Max. voice thefts per audio fragment reached (you may raise CONFIG_MAX_VOICES).\n"));
1135                return -1;
1136            }
1137          if (!pEventPool->poolIsEmpty()) {          if (!pEventPool->poolIsEmpty()) {
1138    
1139              RTList<uint>::Iterator  iuiOldestKey;              RTList<Voice>::Iterator itSelectedVoice;
             RTList<Voice>::Iterator itOldestVoice;  
1140    
1141              // Select one voice for voice stealing              // Select one voice for voice stealing
1142              switch (VOICE_STEAL_ALGORITHM) {              switch (CONFIG_VOICE_STEAL_ALGO) {
1143    
1144                  // try to pick the oldest voice on the key where the new                  // try to pick the oldest voice on the key where the new
1145                  // voice should be spawned, if there is no voice on that                  // voice should be spawned, if there is no voice on that
1146                  // key, or no voice left to kill there, then procceed with                  // key, or no voice left to kill, then procceed with
1147                  // 'oldestkey' algorithm                  // 'oldestkey' algorithm
1148                  case voice_steal_algo_keymask: {                  case voice_steal_algo_oldestvoiceonkey: {
1149                      midi_key_info_t* pOldestKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];                      midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
1150                      if (itLastStolenVoice) {                      itSelectedVoice = pSelectedKey->pActiveVoices->first();
1151                          itOldestVoice = itLastStolenVoice;                      // proceed iterating if voice was created in this fragment cycle
1152                          ++itOldestVoice;                      while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1153                      }                      // if we haven't found a voice then proceed with algorithm 'oldestkey'
1154                      else { // no voice stolen in this audio fragment cycle yet                      if (itSelectedVoice && itSelectedVoice->IsStealable()) break;
                         itOldestVoice = pOldestKey->pActiveVoices->first();  
                     }  
                     if (itOldestVoice) {  
                         iuiOldestKey = pOldestKey->itSelf;  
                         break; // selection succeeded  
                     }  
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
1158                  // (caution: must stay after 'keymask' algorithm !)                  // from the same engine channel
1159                    // (caution: must stay after 'oldestvoiceonkey' algorithm !)
1160                  case voice_steal_algo_oldestkey: {                  case voice_steal_algo_oldestkey: {
1161                      if (itLastStolenVoice) {                      // if we already stole in this fragment, try to proceed on same key
1162                          midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiLastStolenKey];                      if (this->itLastStolenVoice) {
1163                          itOldestVoice = itLastStolenVoice;                          itSelectedVoice = this->itLastStolenVoice;
1164                          ++itOldestVoice;                          do {
1165                          if (!itOldestVoice) {                              ++itSelectedVoice;
1166                              iuiOldestKey = iuiLastStolenKey;                          } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1167                              ++iuiOldestKey;                          // found a "stealable" voice ?
1168                              if (iuiOldestKey) {                          if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1169                                  midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiOldestKey];                              // remember which voice we stole, so we can simply proceed on next voice stealing
1170                                  itOldestVoice = pOldestKey->pActiveVoices->first();                              this->itLastStolenVoice = itSelectedVoice;
1171                              }                              break; // selection succeeded
                             else { // too less voices, even for voice stealing  
                                 dmsg(1,("Voice overflow! - You might recompile with higher MAX_AUDIO_VOICES!\n"));  
                                 return;  
                             }  
1172                          }                          }
                         else iuiOldestKey = iuiLastStolenKey;  
1173                      }                      }
1174                      else { // no voice stolen in this audio fragment cycle yet                      // get (next) oldest key
1175                          iuiOldestKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKey) ? ++this->iuiLastStolenKey : pEngineChannel->pActiveKeys->first();
1176                          midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiOldestKey];                      while (iuiSelectedKey) {
1177                          itOldestVoice = pOldestKey->pActiveVoices->first();                          midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];
1178                            itSelectedVoice = pSelectedKey->pActiveVoices->first();
1179                            // proceed iterating if voice was created in this fragment cycle
1180                            while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1181                            // found a "stealable" voice ?
1182                            if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1183                                // remember which voice on which key we stole, so we can simply proceed on next voice stealing
1184                                this->iuiLastStolenKey  = iuiSelectedKey;
1185                                this->itLastStolenVoice = itSelectedVoice;
1186                                break; // selection succeeded
1187                            }
1188                            ++iuiSelectedKey; // get next oldest key
1189                      }                      }
1190                      break;                      break;
1191                  }                  }
# Line 792  namespace LinuxSampler { namespace gig { Line 1194  namespace LinuxSampler { namespace gig {
1194                  case voice_steal_algo_none:                  case voice_steal_algo_none:
1195                  default: {                  default: {
1196                      dmsg(1,("No free voice (voice stealing disabled)!\n"));                      dmsg(1,("No free voice (voice stealing disabled)!\n"));
1197                      return;                      return -1;
1198                  }                  }
1199              }              }
1200    
1201              // now kill the selected voice              // if we couldn't steal a voice from the same engine channel then
1202              itOldestVoice->Kill(itNoteOnEvent);              // steal oldest voice on the oldest key from any other engine channel
1203              // remember which voice on which key we stole, so we can simply proceed for the next voice stealing              // (the smaller engine channel number, the higher priority)
1204              this->itLastStolenVoice = itOldestVoice;              if (!itSelectedVoice || !itSelectedVoice->IsStealable()) {
1205              this->iuiLastStolenKey = iuiOldestKey;                  EngineChannel* pSelectedChannel;
1206              // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died                  int            iChannelIndex;
1207              RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();                  // select engine channel
1208              if (itStealEvent) {                  if (pLastStolenChannel) {
1209                  *itStealEvent = *itNoteOnEvent; // copy event                      pSelectedChannel = pLastStolenChannel;
1210                  itStealEvent->Param.Note.Layer = iLayer;                      iChannelIndex    = pSelectedChannel->iEngineIndexSelf;
1211                  itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;                  } else { // pick the engine channel followed by this engine channel
1212                        iChannelIndex    = (pEngineChannel->iEngineIndexSelf + 1) % engineChannels.size();
1213                        pSelectedChannel = engineChannels[iChannelIndex];
1214                    }
1215    
1216                    // if we already stole in this fragment, try to proceed on same key
1217                    if (this->itLastStolenVoiceGlobally) {
1218                        itSelectedVoice = this->itLastStolenVoiceGlobally;
1219                        do {
1220                            ++itSelectedVoice;
1221                        } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1222                    }
1223    
1224                    #if CONFIG_DEVMODE
1225                    EngineChannel* pBegin = pSelectedChannel; // to detect endless loop
1226                    #endif // CONFIG_DEVMODE
1227    
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
1234                        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) {
1237                            midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];
1238                            itSelectedVoice = pSelectedKey->pActiveVoices->first();
1239                            // proceed iterating if voice was created in this fragment cycle
1240                            while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1241                            // found a "stealable" voice ?
1242                            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
1244                                this->iuiLastStolenKeyGlobally  = iuiSelectedKey;
1245                                this->itLastStolenVoiceGlobally = itSelectedVoice;
1246                                this->pLastStolenChannel        = pSelectedChannel;
1247                                goto stealable_voice_found; // selection succeeded
1248                            }
1249                            ++iuiSelectedKey; // get next key on current engine channel
1250                        }
1251                        // get next engine channel
1252                        iChannelIndex    = (iChannelIndex + 1) % engineChannels.size();
1253                        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
1270                if (!itSelectedVoice->IsActive()) {
1271                    dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
1272                    return -1;
1273              }              }
1274              else dmsg(1,("Voice stealing queue full!\n"));              #endif // CONFIG_DEVMODE
1275    
1276                // now kill the selected voice
1277                itSelectedVoice->Kill(itNoteOnEvent);
1278    
1279                --VoiceSpawnsLeft;
1280    
1281                return 0; // success
1282            }
1283            else {
1284                dmsg(1,("Event pool emtpy!\n"));
1285                return -1;
1286          }          }
         else dmsg(1,("Event pool emtpy!\n"));  
1287      }      }
1288    
1289      /**      /**
1290       *  Immediately kills the voice given with pVoice (no matter if sustain is       *  Removes the given voice from the MIDI key's list of active voices.
1291       *  pressed or not) and removes it from the MIDI key's list of active voice.       *  This method will be called when a voice went inactive, e.g. because
1292       *  This method will e.g. be called if a voice went inactive by itself.       *  it finished to playback its sample, finished its release stage or
1293         *  just was killed.
1294       *       *
1295       *  @param itVoice - points to the voice to be killed       *  @param pEngineChannel - engine channel on which this event occured on
1296         *  @param itVoice - points to the voice to be freed
1297       */       */
1298      void Engine::KillVoiceImmediately(Pool<Voice>::Iterator& itVoice) {      void Engine::FreeVoice(EngineChannel* pEngineChannel, Pool<Voice>::Iterator& itVoice) {
1299          if (itVoice) {          if (itVoice) {
1300              if (itVoice->IsActive()) itVoice->KillImmediately();              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itVoice->MIDIKey];
   
             midi_key_info_t* pKey = &pMIDIKeyInfo[itVoice->MIDIKey];  
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    
1314              // check if there are no voices left on the MIDI key and update the key info if so              // if no other voices left and member of a key group, remove from key group
1315              if (pKey->pActiveVoices->isEmpty()) {              if (pKey->pActiveVoices->isEmpty() && keygroup) {
1316                  if (keygroup) { // if voice / key belongs to a key group                  uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[keygroup];
1317                      uint** ppKeyGroup = &ActiveKeyGroups[keygroup];                  if (*ppKeyGroup == &*pKey->itSelf) *ppKeyGroup = NULL; // remove key from key group
                     if (*ppKeyGroup == &*pKey->itSelf) *ppKeyGroup = NULL; // remove key from key group  
                 }  
                 pKey->Active = false;  
                 pActiveKeys->free(pKey->itSelf); // remove key from list of active keys  
                 pKey->itSelf = RTList<uint>::Iterator();  
                 pKey->ReleaseTrigger = false;  
                 pKey->pEvents->clear();  
                 dmsg(3,("Key has no more voices now\n"));  
1318              }              }
1319          }          }
1320          else std::cerr << "Couldn't release voice! (pVoice == NULL)\n" << std::flush;          else std::cerr << "Couldn't release voice! (!itVoice)\n" << std::flush;
1321        }
1322    
1323        /**
1324         *  Called when there's no more voice left on a key, this call will
1325         *  update the key info respectively.
1326         *
1327         *  @param pEngineChannel - engine channel on which this event occured on
1328         *  @param pKey - key which is now inactive
1329         */
1330        void Engine::FreeKey(EngineChannel* pEngineChannel, midi_key_info_t* pKey) {
1331            if (pKey->pActiveVoices->isEmpty()) {
1332                pKey->Active = false;
1333                pEngineChannel->pActiveKeys->free(pKey->itSelf); // remove key from list of active keys
1334                pKey->itSelf = RTList<uint>::Iterator();
1335                pKey->ReleaseTrigger = false;
1336                pKey->pEvents->clear();
1337                dmsg(3,("Key has no more voices now\n"));
1338            }
1339            else dmsg(1,("gig::Engine: Oops, tried to free a key which contains voices.\n"));
1340      }      }
1341    
1342      /**      /**
1343       *  Reacts on supported control change commands (e.g. pitch bend wheel,       *  Reacts on supported control change commands (e.g. pitch bend wheel,
1344       *  modulation wheel, aftertouch).       *  modulation wheel, aftertouch).
1345       *       *
1346         *  @param pEngineChannel - engine channel on which this event occured on
1347       *  @param itControlChangeEvent - controller, value and time stamp of the event       *  @param itControlChangeEvent - controller, value and time stamp of the event
1348       */       */
1349      void Engine::ProcessControlChange(Pool<Event>::Iterator& itControlChangeEvent) {      void Engine::ProcessControlChange(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itControlChangeEvent) {
1350          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", itControlChangeEvent->Param.CC.Controller, itControlChangeEvent->Param.CC.Value));          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", itControlChangeEvent->Param.CC.Controller, itControlChangeEvent->Param.CC.Value));
1351    
1352            // update controller value in the engine channel's controller table
1353            pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
1354    
1355            // handle hard coded MIDI controllers
1356          switch (itControlChangeEvent->Param.CC.Controller) {          switch (itControlChangeEvent->Param.CC.Controller) {
1357              case 64: {              case 5: { // portamento time
1358                  if (itControlChangeEvent->Param.CC.Value >= 64 && !SustainPedal) {                  pEngineChannel->PortamentoTime = (float) itControlChangeEvent->Param.CC.Value / 127.0f * (float) CONFIG_PORTAMENTO_TIME_MAX + (float) CONFIG_PORTAMENTO_TIME_MIN;
1359                      dmsg(4,("PEDAL DOWN\n"));                  break;
1360                      SustainPedal = true;              }
1361                case 7: { // volume
1362                    //TODO: not sample accurate yet
1363                    pEngineChannel->MidiVolume = VolumeCurve[itControlChangeEvent->Param.CC.Value];
1364                    pEngineChannel->bStatusChanged = true; // engine channel status has changed, so set notify flag
1365                    break;
1366                }
1367                case 10: { // panpot
1368                    //TODO: not sample accurate yet
1369                    pEngineChannel->GlobalPanLeft  = PanCurve[128 - itControlChangeEvent->Param.CC.Value];
1370                    pEngineChannel->GlobalPanRight = PanCurve[itControlChangeEvent->Param.CC.Value];
1371                    break;
1372                }
1373                case 64: { // sustain
1374                    if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {
1375                        dmsg(4,("DAMPER (RIGHT) PEDAL DOWN\n"));
1376                        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 = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1384                      if (iuiKey) {                      for (; iuiKey; ++iuiKey) {
1385                          itControlChangeEvent->Type = Event::type_cancel_release; // transform event type                          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1386                          while (iuiKey) {                          if (!pKey->KeyPressed) {
1387                              midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1388                              ++iuiKey;                              if (itNewEvent) {
1389                              if (!pKey->KeyPressed) {                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1390                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();                                  itNewEvent->Type = Event::type_cancel_release; // transform event type
                                 if (itNewEvent) *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list  
                                 else dmsg(1,("Event pool emtpy!\n"));  
1391                              }                              }
1392                                else dmsg(1,("Event pool emtpy!\n"));
1393                          }                          }
1394                      }                      }
1395                  }                  }
1396                  if (itControlChangeEvent->Param.CC.Value < 64 && SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {
1397                      dmsg(4,("PEDAL UP\n"));                      dmsg(4,("DAMPER (RIGHT) PEDAL UP\n"));
1398                      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 = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1406                      if (iuiKey) {                      for (; iuiKey; ++iuiKey) {
1407                          itControlChangeEvent->Type = Event::type_release; // transform event type                          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1408                          while (iuiKey) {                          if (!pKey->KeyPressed && ShouldReleaseVoice(pEngineChannel, *iuiKey)) {
1409                              midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1410                              ++iuiKey;                              if (itNewEvent) {
1411                              if (!pKey->KeyPressed) {                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1412                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();                                  itNewEvent->Type = Event::type_release; // transform event type
                                 if (itNewEvent) *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list  
                                 else dmsg(1,("Event pool emtpy!\n"));  
1413                              }                              }
1414                                else dmsg(1,("Event pool emtpy!\n"));
1415                          }                          }
1416                      }                      }
1417                  }                  }
1418                  break;                  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
1458                                }
1459                                else dmsg(1,("Event pool emtpy!\n"));
1460                            }
1461                        }
1462                    }
1463                    break;
1464                }
1465    
1466    
1467          // update controller value in the engine's controller table              // Channel Mode Messages
1468          ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;  
1469                case 120: { // all sound off
1470                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1471                    break;
1472                }
1473                case 121: { // reset all controllers
1474                    pEngineChannel->ResetControllers();
1475                    break;
1476                }
1477                case 123: { // all notes off
1478                    #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;
1492                }
1493            }
1494    
1495          // move event from the unsorted event list to the control change event list          // handle FX send controllers
1496          itControlChangeEvent.moveToEndOf(pCCEvents);          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 914  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 923  namespace LinuxSampler { namespace gig { Line 1517  namespace LinuxSampler { namespace gig {
1517    
1518          switch (id) {          switch (id) {
1519              case 0x41: { // Roland              case 0x41: { // Roland
1520                    dmsg(3,("Roland Sysex\n"));
1521                  uint8_t device_id, model_id, cmd_id;                  uint8_t device_id, model_id, cmd_id;
1522                  if (!reader.pop(&device_id)) goto free_sysex_data;                  if (!reader.pop(&device_id)) goto free_sysex_data;
1523                  if (!reader.pop(&model_id))  goto free_sysex_data;                  if (!reader.pop(&model_id))  goto free_sysex_data;
# Line 932  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"));
1534                  }                  }
1535                  else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters                  else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters
1536                        dmsg(3,("\tCommon Parameter\n"));
1537                  }                  }
1538                  else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)                  else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)
1539                      switch (addr[3]) {                      dmsg(3,("\tPart Parameter\n"));
1540                        switch (addr[2]) {
1541                          case 0x40: { // scale tuning                          case 0x40: { // scale tuning
1542                                dmsg(3,("\t\tScale Tuning\n"));
1543                              uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave                              uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave
1544                              if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;                              if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;
1545                              uint8_t checksum;                              uint8_t checksum;
1546                              if (!reader.pop(&checksum))                      goto free_sysex_data;                              if (!reader.pop(&checksum)) goto free_sysex_data;
1547                              if (GSCheckSum(checksum_reader, 12) != checksum) goto free_sysex_data;                              #if CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1548                                if (GSCheckSum(checksum_reader, 12)) goto free_sysex_data;
1549                                #endif // CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1550                              for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;                              for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;
1551                              AdjustScale((int8_t*) scale_tunes);                              AdjustScale((int8_t*) scale_tunes);
1552                                dmsg(3,("\t\t\tNew scale applied.\n"));
1553                              break;                              break;
1554                          }                          }
1555                      }                      }
# Line 972  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 992  namespace LinuxSampler { namespace gig { Line 1594  namespace LinuxSampler { namespace gig {
1594      }      }
1595    
1596      /**      /**
1597       * Initialize the parameter sequence for the modulation destination given by       * Releases all voices on an engine channel. All voices will go into
1598       * by 'dst' with the constant value given by val.       * the release stage and thus it might take some time (e.g. dependant to
1599         * their envelope release time) until they actually die.
1600         *
1601         * @param pEngineChannel - engine channel on which all voices should be released
1602         * @param itReleaseEvent - event which caused this releasing of all voices
1603       */       */
1604      void Engine::ResetSynthesisParameters(Event::destination_t dst, float val) {      void Engine::ReleaseAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itReleaseEvent) {
1605          int maxsamples = pAudioOutputDevice->MaxSamplesPerCycle();          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1606          float* m = &pSynthesisParameters[dst][0];          while (iuiKey) {
1607          for (int i = 0; i < maxsamples; i += 4) {              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1608             m[i]   = val;              ++iuiKey;
1609             m[i+1] = val;              // append a 'release' event to the key's own event list
1610             m[i+2] = val;              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1611             m[i+3] = val;              if (itNewEvent) {
1612                    *itNewEvent = *itReleaseEvent; // copy original event (to the key's event list)
1613                    itNewEvent->Type = Event::type_release; // transform event type
1614                }
1615                else dmsg(1,("Event pool emtpy!\n"));
1616          }          }
1617      }      }
1618    
1619      float Engine::Volume() {      /**
1620          return GlobalVolume;       * Kills all voices on an engine channel as soon as possible. Voices
1621      }       * won't get into release state, their volume level will be ramped down
1622         * as fast as possible.
1623      void Engine::Volume(float f) {       *
1624          GlobalVolume = f;       * @param pEngineChannel - engine channel on which all voices should be killed
1625      }       * @param itKillEvent    - event which caused this killing of all voices
1626         */
1627      uint Engine::Channels() {      void Engine::KillAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itKillEvent) {
1628          return 2;          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1629      }          RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
1630            while (iuiKey != end) { // iterate through all active keys
1631      void Engine::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) {              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1632          AudioChannel* pChannel = pAudioOutputDevice->Channel(AudioDeviceChannel);              ++iuiKey;
1633          if (!pChannel) throw AudioOutputException("Invalid audio output device channel " + ToString(AudioDeviceChannel));              RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
1634          switch (EngineAudioChannel) {              RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
1635              case 0: // left output channel              for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
1636                  pOutputLeft = pChannel->Buffer();                  itVoice->Kill(itKillEvent);
1637                  AudioDeviceChannelLeft = AudioDeviceChannel;                  --VoiceSpawnsLeft; //FIXME: just a temporary workaround, we should check the cause in StealVoice() instead
1638                  break;              }
             case 1: // right output channel  
                 pOutputRight = pChannel->Buffer();  
                 AudioDeviceChannelRight = AudioDeviceChannel;  
                 break;  
             default:  
                 throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));  
1639          }          }
1640      }      }
1641    
1642      int Engine::OutputChannel(uint EngineAudioChannel) {      /**
1643          switch (EngineAudioChannel) {       * Determines whether the specified voice should be released.
1644              case 0: // left channel       *
1645                  return AudioDeviceChannelLeft;       * @param pEngineChannel - The engine channel on which the voice should be checked
1646              case 1: // right channel       * @param Key - The key number
1647                  return AudioDeviceChannelRight;       * @returns true if the specified should be released, false otherwise.
1648              default:       */
1649                  throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));      bool Engine::ShouldReleaseVoice(EngineChannel* pEngineChannel, int Key) {
1650            if (pEngineChannel->SustainPedal) return false;
1651    
1652            if (pEngineChannel->SostenutoPedal) {
1653                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 1075  namespace LinuxSampler { namespace gig { Line 1686  namespace LinuxSampler { namespace gig {
1686      }      }
1687    
1688      String Engine::EngineName() {      String Engine::EngineName() {
1689          return "GigEngine";          return LS_GIG_ENGINE_NAME;
1690      }      }
1691    
1692      String Engine::InstrumentFileName() {      String Engine::Description() {
1693          return InstrumentFile;          return "Gigasampler Engine";
1694      }      }
1695    
1696      int Engine::InstrumentIndex() {      String Engine::Version() {
1697          return InstrumentIdx;          String s = "$Revision: 1.71 $";
1698            return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword
1699      }      }
1700    
1701      int Engine::InstrumentStatus() {      InstrumentManager* Engine::GetInstrumentManager() {
1702          return InstrumentStat;          return &instruments;
1703      }      }
1704    
1705      String Engine::Description() {      // static constant initializers
1706          return "Gigasampler Engine";      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      String Engine::Version() {      float* Engine::InitPanCurve() {
1720          String s = "$Revision: 1.15 $";          // line-segment approximation
1721          return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword          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.271  
changed lines
  Added in v.1038

  ViewVC Help
Powered by ViewVC