/[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 53 by schoenebeck, Mon Apr 26 17:15:51 2004 UTC revision 880 by schoenebeck, Tue Jun 27 22:57:37 2006 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003 by Benno Senoner and Christian Schoenebeck         *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6     *   Copyright (C) 2005, 2006 Christian Schoenebeck                        *
7   *                                                                         *   *                                                                         *
8   *   This program is free software; you can redistribute it and/or modify  *   *   This program is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 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            // register engine channel to the engine instance
61            pEngine->engineChannels.add(pChannel);
62            // remember index in the ArrayList
63            pChannel->iEngineIndexSelf = pEngine->engineChannels.size() - 1;
64            dmsg(4,("This gig::Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));
65            return pEngine;
66        }
67    
68        /**
69         * Once an engine channel is disconnected from an audio output device,
70         * it wil immediately call this method to unregister itself from the
71         * engine instance and if that engine instance is not used by any other
72         * engine channel anymore, then that engine instance will be destroyed.
73         *
74         * @param pChannel - engine channel which wants to disconnect from it's
75         *                   engine instance
76         * @param pDevice  - audio output device \a pChannel was connected to
77         */
78        void Engine::FreeEngine(LinuxSampler::gig::EngineChannel* pChannel, AudioOutputDevice* pDevice) {
79            dmsg(4,("Disconnecting EngineChannel from gig::Engine.\n"));
80            Engine* pEngine = engines[pDevice];
81            // unregister EngineChannel from the Engine instance
82            pEngine->engineChannels.remove(pChannel);
83            // if the used Engine instance is not used anymore, then destroy it
84            if (pEngine->engineChannels.empty()) {
85                pDevice->Disconnect(pEngine);
86                engines.erase(pDevice);
87                delete pEngine;
88                dmsg(4,("Destroying gig::Engine.\n"));
89            }
90            else dmsg(4,("This gig::Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));
91        }
92    
93        /**
94         * Constructor
95         */
96      Engine::Engine() {      Engine::Engine() {
         pRIFF              = NULL;  
         pGig               = NULL;  
         pInstrument        = NULL;  
97          pAudioOutputDevice = NULL;          pAudioOutputDevice = NULL;
98          pDiskThread        = NULL;          pDiskThread        = NULL;
99          pEventGenerator    = NULL;          pEventGenerator    = NULL;
100          pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT);          pSysexBuffer       = new RingBuffer<uint8_t>(CONFIG_SYSEX_BUFFER_SIZE, 0);
101          pEventPool         = new RTELMemoryPool<Event>(MAX_EVENTS_PER_FRAGMENT);          pEventQueue        = new RingBuffer<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);
102          pVoicePool         = new RTELMemoryPool<Voice>(MAX_AUDIO_VOICES);          pEventPool         = new Pool<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT);
103          pActiveKeys        = new RTELMemoryPool<uint>(128);          pVoicePool         = new Pool<Voice>(CONFIG_MAX_VOICES);
104          pEvents            = new RTEList<Event>(pEventPool);          pVoiceStealingQueue = new RTList<Event>(pEventPool);
105          pCCEvents          = new RTEList<Event>(pEventPool);          pGlobalEvents      = new RTList<Event>(pEventPool);
106          for (uint i = 0; i < Event::destination_count; i++) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
107              pSynthesisEvents[i] = new RTEList<Event>(pEventPool);              iterVoice->SetEngine(this);
         }  
         for (uint i = 0; i < 128; i++) {  
             pMIDIKeyInfo[i].pActiveVoices = new RTEList<Voice>(pVoicePool);  
             pMIDIKeyInfo[i].KeyPressed    = false;  
             pMIDIKeyInfo[i].Active        = false;  
             pMIDIKeyInfo[i].pSelf         = NULL;  
             pMIDIKeyInfo[i].pEvents       = new RTEList<Event>(pEventPool);  
         }  
         for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {  
             pVoice->SetEngine(this);  
108          }          }
109          pVoicePool->clear();          pVoicePool->clear();
110    
         pSynthesisParameters[0] = NULL; // we allocate when an audio device is connected  
   
111          ResetInternal();          ResetInternal();
112            ResetScaleTuning();
113      }      }
114    
115        /**
116         * Destructor
117         */
118      Engine::~Engine() {      Engine::~Engine() {
119            MidiInputPort::RemoveSysexListener(this);
120          if (pDiskThread) {          if (pDiskThread) {
121                dmsg(1,("Stopping disk thread..."));
122              pDiskThread->StopThread();              pDiskThread->StopThread();
123              delete pDiskThread;              delete pDiskThread;
124                dmsg(1,("OK\n"));
125          }          }
         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;  
126          if (pEventQueue) delete pEventQueue;          if (pEventQueue) delete pEventQueue;
127          if (pEventPool)  delete pEventPool;          if (pEventPool)  delete pEventPool;
128          if (pVoicePool)  delete pVoicePool;          if (pVoicePool) {
129          if (pActiveKeys) delete pActiveKeys;              pVoicePool->clear();
130                delete pVoicePool;
131            }
132          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
133          if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];          if (pVoiceStealingQueue) delete pVoiceStealingQueue;
134            if (pSysexBuffer) delete pSysexBuffer;
135            EngineFactory::Destroy(this);
136      }      }
137    
138      void Engine::Enable() {      void Engine::Enable() {
139          dmsg(3,("gig::Engine: enabling\n"));          dmsg(3,("gig::Engine: enabling\n"));
140          EngineDisabled.PushAndUnlock(false, 2); // set condition object 'EngineDisabled' to false (wait max. 2s)          EngineDisabled.PushAndUnlock(false, 2); // set condition object 'EngineDisabled' to false (wait max. 2s)
141          dmsg(1,("gig::Engine: enabled (val=%d)\n", EngineDisabled.GetUnsafe()));          dmsg(3,("gig::Engine: enabled (val=%d)\n", EngineDisabled.GetUnsafe()));
142      }      }
143    
144      void Engine::Disable() {      void Engine::Disable() {
# Line 112  namespace LinuxSampler { namespace gig { Line 159  namespace LinuxSampler { namespace gig {
159       */       */
160      void Engine::Reset() {      void Engine::Reset() {
161          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();  
   
162          ResetInternal();          ResetInternal();
163            ResetScaleTuning();
         // signal audio thread to continue with rendering  
         //SuspensionRequested = false;  
164          Enable();          Enable();
165      }      }
166    
167      /**      /**
168       *  Reset all voices and disk thread and clear input event queue and all       *  Reset all voices and disk thread and clear input event queue and all
169       *  control and status variables. This method is not thread safe!       *  control and status variables. This method is protected by a mutex.
170       */       */
171      void Engine::ResetInternal() {      void Engine::ResetInternal() {
172          Pitch               = 0;          ResetInternalMutex.Lock();
173          SustainPedal        = false;  
174            // make sure that the engine does not get any sysex messages
175            // while it's reseting
176            bool sysexDisabled = MidiInputPort::RemoveSysexListener(this);
177          ActiveVoiceCount    = 0;          ActiveVoiceCount    = 0;
178          ActiveVoiceCountMax = 0;          ActiveVoiceCountMax = 0;
179    
180          // set all MIDI controller values to zero          // reset voice stealing parameters
181          memset(ControllerTable, 0x00, 128);          pVoiceStealingQueue->clear();
182            itLastStolenVoice          = RTList<Voice>::Iterator();
183          // reset key info          itLastStolenVoiceGlobally  = RTList<Voice>::Iterator();
184          for (uint i = 0; i < 128; i++) {          iuiLastStolenKey           = RTList<uint>::Iterator();
185              pMIDIKeyInfo[i].pActiveVoices->clear();          iuiLastStolenKeyGlobally   = RTList<uint>::Iterator();
186              pMIDIKeyInfo[i].pEvents->clear();          pLastStolenChannel         = NULL;
             pMIDIKeyInfo[i].KeyPressed = false;  
             pMIDIKeyInfo[i].Active     = false;  
             pMIDIKeyInfo[i].pSelf      = NULL;  
         }  
187    
188          // reset all voices          // reset all voices
189          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
190              pVoice->Reset();              iterVoice->Reset();
191          }          }
192          pVoicePool->clear();          pVoicePool->clear();
193    
         // free all active keys  
         pActiveKeys->clear();  
   
194          // reset disk thread          // reset disk thread
195          if (pDiskThread) pDiskThread->Reset();          if (pDiskThread) pDiskThread->Reset();
196    
197          // delete all input events          // delete all input events
198          pEventQueue->init();          pEventQueue->init();
199            pSysexBuffer->init();
200            if (sysexDisabled) MidiInputPort::AddSysexListener(this);
201            ResetInternalMutex.Unlock();
202      }      }
203    
204      /**      /**
205       *  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  
206       */       */
207      void Engine::LoadInstrument(const char* FileName, uint Instrument) {      void Engine::ResetScaleTuning() {
208            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);  
         }  
   
         // request gig instrument from instrument manager  
         try {  
             instrument_id_t instrid;  
             instrid.FileName    = FileName;  
             instrid.iInstrument = Instrument;  
             pInstrument = Instruments.Borrow(instrid, this);  
             if (!pInstrument) {  
                 dmsg(1,("no instrument loaded!!!\n"));  
                 exit(EXIT_FAILURE);  
             }  
         }  
         catch (RIFF::Exception e) {  
             String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;  
             throw LinuxSamplerException(msg);  
         }  
         catch (InstrumentResourceManagerException e) {  
             String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();  
             throw LinuxSamplerException(msg);  
         }  
         catch (...) {  
             throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");  
         }  
   
         // 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();  
209      }      }
210    
211      /**      /**
212       * Will be called by the InstrumentResourceManager when the instrument       * Connect this engine instance with the given audio output device.
213       * we are currently using in this engine is going to be updated, so we       * This method will be called when an Engine instance is created.
214       * can stop playback before that happens.       * All of the engine's data structures which are dependant to the used
215       */       * audio output device / driver will be (re)allocated and / or
216      void Engine::ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {       * adjusted appropriately.
217          dmsg(3,("gig::Engine: Received instrument update message.\n"));       *
218          DisableAndLock();       * @param pAudioOut - audio output device to connect to
         ResetInternal();  
         this->pInstrument = NULL;  
     }  
   
     /**  
      * Will be called by the InstrumentResourceManager when the instrument  
      * update process was completed, so we can continue with playback.  
219       */       */
     void Engine::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {  
         this->pInstrument = pNewResource;  
         Enable();  
     }  
   
220      void Engine::Connect(AudioOutputDevice* pAudioOut) {      void Engine::Connect(AudioOutputDevice* pAudioOut) {
221          pAudioOutputDevice = pAudioOut;          pAudioOutputDevice = pAudioOut;
222    
# Line 258  namespace LinuxSampler { namespace gig { Line 228  namespace LinuxSampler { namespace gig {
228          }          }
229          catch (AudioOutputException e) {          catch (AudioOutputException e) {
230              String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();              String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();
231              throw LinuxSamplerException(msg);              throw Exception(msg);
232            }
233    
234            this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle();
235            this->SampleRate         = pAudioOutputDevice->SampleRate();
236    
237            // FIXME: audio drivers with varying fragment sizes might be a problem here
238            MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * CONFIG_EG_MIN_RELEASE_TIME) - 1;
239            if (MaxFadeOutPos < 0) {
240                std::cerr << "gig::Engine: WARNING, CONFIG_EG_MIN_RELEASE_TIME "
241                          << "too big for current audio fragment size & sampling rate! "
242                          << "May lead to click sounds if voice stealing chimes in!\n" << std::flush;
243                // force volume ramp downs at the beginning of each fragment
244                MaxFadeOutPos = 0;
245                // lower minimum release time
246                const float minReleaseTime = (float) MaxSamplesPerCycle / (float) SampleRate;
247                for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
248                    iterVoice->EG1.CalculateFadeOutCoeff(minReleaseTime, SampleRate);
249                }
250                pVoicePool->clear();
251          }          }
252    
253          // (re)create disk thread          // (re)create disk thread
254          if (this->pDiskThread) {          if (this->pDiskThread) {
255                dmsg(1,("Stopping disk thread..."));
256              this->pDiskThread->StopThread();              this->pDiskThread->StopThread();
257              delete this->pDiskThread;              delete this->pDiskThread;
258                dmsg(1,("OK\n"));
259          }          }
260          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
261          if (!pDiskThread) {          if (!pDiskThread) {
262              dmsg(0,("gig::Engine  new diskthread = NULL\n"));              dmsg(0,("gig::Engine  new diskthread = NULL\n"));
263              exit(EXIT_FAILURE);              exit(EXIT_FAILURE);
264          }          }
265    
266          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
267              pVoice->pDiskThread = this->pDiskThread;              iterVoice->pDiskThread = this->pDiskThread;
             pVoice->SetOutput(pAudioOut);  
268              dmsg(3,("d"));              dmsg(3,("d"));
269          }          }
270          pVoicePool->clear();          pVoicePool->clear();
# Line 283  namespace LinuxSampler { namespace gig { Line 273  namespace LinuxSampler { namespace gig {
273          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
274          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
275    
         // (re)allocate synthesis parameter matrix  
         if (pSynthesisParameters[0]) 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();  
   
276          dmsg(1,("Starting disk thread..."));          dmsg(1,("Starting disk thread..."));
277          pDiskThread->StartThread();          pDiskThread->StartThread();
278          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
279    
280          for (Voice* pVoice = pVoicePool->first(); pVoice; pVoice = pVoicePool->next()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
281              if (!pVoice->pDiskThread) {              if (!iterVoice->pDiskThread) {
282                  dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));                  dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));
283                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
284              }              }
285          }          }
286      }      }
287    
288      void Engine::DisconnectAudioOutputDevice() {      /**
289          if (pAudioOutputDevice) { // if clause to prevent disconnect loops       * Clear all engine global event lists.
290              AudioOutputDevice* olddevice = pAudioOutputDevice;       */
291              pAudioOutputDevice = NULL;      void Engine::ClearEventLists() {
292              olddevice->Disconnect(this);          pGlobalEvents->clear();
293        }
294    
295        /**
296         * Copy all events from the engine's global input queue buffer to the
297         * engine's internal event list. This will be done at the beginning of
298         * each audio cycle (that is each RenderAudio() call) to distinguish
299         * all global events which have to be processed in the current audio
300         * cycle. These events are usually just SysEx messages. Every
301         * EngineChannel has it's own input event queue buffer and event list
302         * to handle common events like NoteOn, NoteOff and ControlChange
303         * events.
304         *
305         * @param Samples - number of sample points to be processed in the
306         *                  current audio cycle
307         */
308        void Engine::ImportEvents(uint Samples) {
309            RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
310            Event* pEvent;
311            while (true) {
312                // get next event from input event queue
313                if (!(pEvent = eventQueueReader.pop())) break;
314                // if younger event reached, ignore that and all subsequent ones for now
315                if (pEvent->FragmentPos() >= Samples) {
316                    eventQueueReader--;
317                    dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
318                    pEvent->ResetFragmentPos();
319                    break;
320                }
321                // copy event to internal event list
322                if (pGlobalEvents->poolIsEmpty()) {
323                    dmsg(1,("Event pool emtpy!\n"));
324                    break;
325                }
326                *pGlobalEvents->allocAppend() = *pEvent;
327          }          }
328            eventQueueReader.free(); // free all copied events from input queue
329      }      }
330    
331      /**      /**
# Line 322  namespace LinuxSampler { namespace gig { Line 341  namespace LinuxSampler { namespace gig {
341      int Engine::RenderAudio(uint Samples) {      int Engine::RenderAudio(uint Samples) {
342          dmsg(5,("RenderAudio(Samples=%d)\n", Samples));          dmsg(5,("RenderAudio(Samples=%d)\n", Samples));
343    
344          // return if no instrument loaded or engine disabled          // return if engine disabled
345          if (EngineDisabled.Pop()) {          if (EngineDisabled.Pop()) {
346              dmsg(5,("gig::Engine: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));              dmsg(5,("gig::Engine: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));
347              return 0;              return 0;
348          }          }
         if (!pInstrument) {  
             dmsg(5,("gig::Engine: no instrument loaded\n"));  
             return 0;  
         }  
349    
350            // update time of start and end of this audio fragment (as events' time stamps relate to this)
351            pEventGenerator->UpdateFragmentTime(Samples);
352    
353          // empty the event lists for the new fragment          // We only allow a maximum of CONFIG_MAX_VOICES voices to be spawned
354          pEvents->clear();          // in each audio fragment. All subsequent request for spawning new
355          pCCEvents->clear();          // voices in the same audio fragment will be ignored.
356          for (uint i = 0; i < Event::destination_count; i++) {          VoiceSpawnsLeft = CONFIG_MAX_VOICES;
357              pSynthesisEvents[i]->clear();  
358            // get all events from the engine's global input event queue which belong to the current fragment
359            // (these are usually just SysEx messages)
360            ImportEvents(Samples);
361    
362            // process engine global events (these are currently only MIDI System Exclusive messages)
363            {
364                RTList<Event>::Iterator itEvent = pGlobalEvents->first();
365                RTList<Event>::Iterator end     = pGlobalEvents->end();
366                for (; itEvent != end; ++itEvent) {
367                    switch (itEvent->Type) {
368                        case Event::type_sysex:
369                            dmsg(5,("Engine: Sysex received\n"));
370                            ProcessSysex(itEvent);
371                            break;
372                    }
373                }
374          }          }
375    
376          // read and copy events from input queue          // reset internal voice counter (just for statistic of active voices)
377          Event event = pEventGenerator->CreateEvent();          ActiveVoiceCountTemp = 0;
         while (true) {  
             if (!pEventQueue->pop(&event)) break;  
             pEvents->alloc_assign(event);  
         }  
378    
379            // handle events on all engine channels
380            for (int i = 0; i < engineChannels.size(); i++) {
381                if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
382                ProcessEvents(engineChannels[i], Samples);
383            }
384    
385          // update time of start and end of this audio fragment (as events' time stamps relate to this)          // render all 'normal', active voices on all engine channels
386          pEventGenerator->UpdateFragmentTime(Samples);          for (int i = 0; i < engineChannels.size(); i++) {
387                if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
388                RenderActiveVoices(engineChannels[i], Samples);
389            }
390    
391            // now that all ordinary voices on ALL engine channels are rendered, render new stolen voices
392            RenderStolenVoices(Samples);
393    
394          // process events          // handle cleanup on all engine channels for the next audio fragment
395          Event* pNextEvent = pEvents->first();          for (int i = 0; i < engineChannels.size(); i++) {
396          while (pNextEvent) {              if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
397              Event* pEvent = pNextEvent;              PostProcess(engineChannels[i]);
             pEvents->set_current(pEvent);  
             pNextEvent = pEvents->next();  
             switch (pEvent->Type) {  
                 case Event::type_note_on:  
                     dmsg(5,("Audio Thread: Note on received\n"));  
                     ProcessNoteOn(pEvent);  
                     break;  
                 case Event::type_note_off:  
                     dmsg(5,("Audio Thread: Note off received\n"));  
                     ProcessNoteOff(pEvent);  
                     break;  
                 case Event::type_control_change:  
                     dmsg(5,("Audio Thread: MIDI CC received\n"));  
                     ProcessControlChange(pEvent);  
                     break;  
                 case Event::type_pitchbend:  
                     dmsg(5,("Audio Thread: Pitchbend received\n"));  
                     ProcessPitchbend(pEvent);  
                     break;  
             }  
398          }          }
399    
400    
401          // render audio from all active voices          // empty the engine's event list for the next audio fragment
402          int active_voices = 0;          ClearEventLists();
         uint* piKey = pActiveKeys->first();  
         while (piKey) { // iterate through all active keys  
             midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];  
             pActiveKeys->set_current(piKey);  
             piKey = pActiveKeys->next();  
   
             Voice* pVoiceNext = pKey->pActiveVoices->first();  
             while (pVoiceNext) { // iterate through all voices on this key  
                 // already get next voice on key  
                 Voice* pVoice = pVoiceNext;  
                 pKey->pActiveVoices->set_current(pVoice);  
                 pVoiceNext = pKey->pActiveVoices->next();  
   
                 // now render current voice  
                 pVoice->Render(Samples);  
                 if (pVoice->IsActive()) active_voices++; // still active  
                 else { // voice reached end, is now inactive  
                     KillVoice(pVoice); // remove voice from the list of active voices  
                 }  
             }  
             pKey->pEvents->clear(); // free all events on the key  
         }  
403    
404            // reset voice stealing for the next audio fragment
405            pVoiceStealingQueue->clear();
406    
407          // write that to the disk thread class so that it can print it          // just some statistics about this engine instance
408          // on the console for debugging purposes          ActiveVoiceCount = ActiveVoiceCountTemp;
         ActiveVoiceCount = active_voices;  
409          if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;          if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;
410    
411            FrameTime += Samples;
412    
413          return 0;          return 0;
414      }      }
415    
416      /**      /**
417       *  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
418       *  voice for the given key.       * engine channel.
419       *       *
420       *  @param Key      - MIDI key number of the triggered key       * @param pEngineChannel - engine channel on which events should be
421       *  @param Velocity - MIDI velocity value of the triggered key       *                         processed
422         * @param Samples        - amount of sample points to be processed in
423         *                         this audio fragment cycle
424       */       */
425      void Engine::SendNoteOn(uint8_t Key, uint8_t Velocity) {      void Engine::ProcessEvents(EngineChannel* pEngineChannel, uint Samples) {
426          Event event    = pEventGenerator->CreateEvent();          // get all events from the engine channels's input event queue which belong to the current fragment
427          event.Type     = Event::type_note_on;          // (these are the common events like NoteOn, NoteOff, ControlChange, etc.)
428          event.Key      = Key;          pEngineChannel->ImportEvents(Samples);
429          event.Velocity = Velocity;  
430          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          // process events
431          else dmsg(1,("Engine: Input event queue full!"));          {
432                RTList<Event>::Iterator itEvent = pEngineChannel->pEvents->first();
433                RTList<Event>::Iterator end     = pEngineChannel->pEvents->end();
434                for (; itEvent != end; ++itEvent) {
435                    switch (itEvent->Type) {
436                        case Event::type_note_on:
437                            dmsg(5,("Engine: Note on received\n"));
438                            ProcessNoteOn((EngineChannel*)itEvent->pEngineChannel, itEvent);
439                            break;
440                        case Event::type_note_off:
441                            dmsg(5,("Engine: Note off received\n"));
442                            ProcessNoteOff((EngineChannel*)itEvent->pEngineChannel, itEvent);
443                            break;
444                        case Event::type_control_change:
445                            dmsg(5,("Engine: MIDI CC received\n"));
446                            ProcessControlChange((EngineChannel*)itEvent->pEngineChannel, itEvent);
447                            break;
448                        case Event::type_pitchbend:
449                            dmsg(5,("Engine: Pitchbend received\n"));
450                            ProcessPitchbend((EngineChannel*)itEvent->pEngineChannel, itEvent);
451                            break;
452                    }
453                }
454            }
455    
456            // reset voice stealing for the next engine channel (or next audio fragment)
457            itLastStolenVoice         = RTList<Voice>::Iterator();
458            itLastStolenVoiceGlobally = RTList<Voice>::Iterator();
459            iuiLastStolenKey          = RTList<uint>::Iterator();
460            iuiLastStolenKeyGlobally  = RTList<uint>::Iterator();
461            pLastStolenChannel        = NULL;
462      }      }
463    
464      /**      /**
465       *  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
466       *  voice(s) on the given key.       * this fragment) on the given engine channel.
467       *       *
468       *  @param Key      - MIDI key number of the released key       * @param pEngineChannel - engine channel on which audio should be
469       *  @param Velocity - MIDI release velocity value of the released key       *                         rendered
470         * @param Samples        - amount of sample points to be rendered in
471         *                         this audio fragment cycle
472       */       */
473      void Engine::SendNoteOff(uint8_t Key, uint8_t Velocity) {      void Engine::RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {
474          Event event    = pEventGenerator->CreateEvent();          #if !CONFIG_PROCESS_MUTED_CHANNELS
475          event.Type     = Event::type_note_off;          if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
476          event.Key      = Key;          #endif
477          event.Velocity = Velocity;  
478          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
479          else dmsg(1,("Engine: Input event queue full!"));          RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
480            while (iuiKey != end) { // iterate through all active keys
481                midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
482                ++iuiKey;
483    
484                RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
485                RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
486                for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
487                    // now render current voice
488                    itVoice->Render(Samples);
489                    if (itVoice->IsActive()) ActiveVoiceCountTemp++; // still active
490                    else { // voice reached end, is now inactive
491                        FreeVoice(pEngineChannel, itVoice); // remove voice from the list of active voices
492                    }
493                }
494            }
495      }      }
496    
497      /**      /**
498       *  Will be called by the MIDIIn Thread to signal the audio thread to change       * Render all stolen voices (only voices which were stolen in this
499       *  the pitch value for all voices.       * fragment) on the given engine channel. Stolen voices are rendered
500         * after all normal voices have been rendered; this is needed to render
501         * audio of those voices which were selected for voice stealing until
502         * the point were the stealing (that is the take over of the voice)
503         * actually happened.
504       *       *
505       *  @param Pitch - MIDI pitch value (-8192 ... +8191)       * @param pEngineChannel - engine channel on which audio should be
506         *                         rendered
507         * @param Samples        - amount of sample points to be rendered in
508         *                         this audio fragment cycle
509       */       */
510      void Engine::SendPitchbend(int Pitch) {      void Engine::RenderStolenVoices(uint Samples) {
511          Event event = pEventGenerator->CreateEvent();          RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();
512          event.Type  = Event::type_pitchbend;          RTList<Event>::Iterator end               = pVoiceStealingQueue->end();
513          event.Pitch = Pitch;          for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
514          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);              EngineChannel* pEngineChannel = (EngineChannel*) itVoiceStealEvent->pEngineChannel;
515          else dmsg(1,("Engine: Input event queue full!"));              Pool<Voice>::Iterator itNewVoice =
516                    LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false, false);
517                if (itNewVoice) {
518                    itNewVoice->Render(Samples);
519                    if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active
520                    else { // voice reached end, is now inactive
521                        FreeVoice(pEngineChannel, itNewVoice); // remove voice from the list of active voices
522                    }
523                }
524                else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));
525    
526                // we need to clear the key's event list explicitly here in case key was never active
527                midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itVoiceStealEvent->Param.Note.Key];
528                pKey->VoiceTheftsQueued--;
529                if (!pKey->Active && !pKey->VoiceTheftsQueued) pKey->pEvents->clear();
530            }
531      }      }
532    
533      /**      /**
534       *  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
535       *  continuous controller value has changed.       * the list of active keys and clear all event lists on that engine
536         * channel.
537       *       *
538       *  @param Controller - MIDI controller number of the occured control change       * @param pEngineChannel - engine channel to cleanup
      *  @param Value      - value of the control change  
539       */       */
540      void Engine::SendControlChange(uint8_t Controller, uint8_t Value) {      void Engine::PostProcess(EngineChannel* pEngineChannel) {
541          Event event      = pEventGenerator->CreateEvent();          // free all keys which have no active voices left
542          event.Type       = Event::type_control_change;          {
543          event.Controller = Controller;              RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
544          event.Value      = Value;              RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
545          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);              while (iuiKey != end) { // iterate through all active keys
546                    midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
547                    ++iuiKey;
548                    if (pKey->pActiveVoices->isEmpty()) FreeKey(pEngineChannel, pKey);
549                    #if CONFIG_DEVMODE
550                    else { // just a sanity check for debugging
551                        RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
552                        RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
553                        for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
554                            if (itVoice->itKillEvent) {
555                                dmsg(1,("gig::Engine: ERROR, killed voice survived !!!\n"));
556                            }
557                        }
558                    }
559                    #endif // CONFIG_DEVMODE
560                }
561            }
562    
563            // empty the engine channel's own event lists
564            pEngineChannel->ClearEventLists();
565        }
566    
567        /**
568         *  Will be called by the MIDI input device whenever a MIDI system
569         *  exclusive message has arrived.
570         *
571         *  @param pData - pointer to sysex data
572         *  @param Size  - lenght of sysex data (in bytes)
573         */
574        void Engine::SendSysex(void* pData, uint Size) {
575            Event event             = pEventGenerator->CreateEvent();
576            event.Type              = Event::type_sysex;
577            event.Param.Sysex.Size  = Size;
578            event.pEngineChannel    = NULL; // as Engine global event
579            if (pEventQueue->write_space() > 0) {
580                if (pSysexBuffer->write_space() >= Size) {
581                    // copy sysex data to input buffer
582                    uint toWrite = Size;
583                    uint8_t* pPos = (uint8_t*) pData;
584                    while (toWrite) {
585                        const uint writeNow = RTMath::Min(toWrite, pSysexBuffer->write_space_to_end());
586                        pSysexBuffer->write(pPos, writeNow);
587                        toWrite -= writeNow;
588                        pPos    += writeNow;
589    
590                    }
591                    // finally place sysex event into input event queue
592                    pEventQueue->push(&event);
593                }
594                else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,CONFIG_SYSEX_BUFFER_SIZE));
595            }
596          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
597      }      }
598    
599      /**      /**
600       *  Assigns and triggers a new voice for the respective MIDI key.       *  Assigns and triggers a new voice for the respective MIDI key.
601       *       *
602       *  @param pNoteOnEvent - key, velocity and time stamp of the event       *  @param pEngineChannel - engine channel on which this event occured on
603         *  @param itNoteOnEvent - key, velocity and time stamp of the event
604       */       */
605      void Engine::ProcessNoteOn(Event* pNoteOnEvent) {      void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
606          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Key];          #if !CONFIG_PROCESS_MUTED_CHANNELS
607            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
608            #endif
609    
610            const int key = itNoteOnEvent->Param.Note.Key;
611            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];
612    
613            // move note on event to the key's own event list
614            RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
615    
616            // if Solo Mode then kill all already active voices
617            if (pEngineChannel->SoloMode) {
618                Pool<uint>::Iterator itYoungestKey = pEngineChannel->pActiveKeys->last();
619                if (itYoungestKey) {
620                    const int iYoungestKey = *itYoungestKey;
621                    const midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[iYoungestKey];
622                    if (pOtherKey->Active) {
623                        // get final portamento position of currently active voice
624                        if (pEngineChannel->PortamentoMode) {
625                            RTList<Voice>::Iterator itVoice = pOtherKey->pActiveVoices->last();
626                            if (itVoice) itVoice->UpdatePortamentoPos(itNoteOnEventOnKeyList);
627                        }
628                        // kill all voices on the (other) key
629                        RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
630                        RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
631                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
632                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger)
633                                itVoiceToBeKilled->Kill(itNoteOnEventOnKeyList);
634                        }
635                    }
636                }
637                // set this key as 'currently active solo key'
638                pEngineChannel->SoloKey = key;
639            }
640    
641            // Change key dimension value if key is in keyswitching area
642            {
643                const ::gig::Instrument* pInstrument = pEngineChannel->pInstrument;
644                if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high)
645                    pEngineChannel->CurrentKeyDimension = float(key - pInstrument->DimensionKeyRange.low) /
646                        (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);
647            }
648    
649          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
650            pKey->Velocity   = itNoteOnEventOnKeyList->Param.Note.Velocity;
651            pKey->NoteOnTime = FrameTime + itNoteOnEventOnKeyList->FragmentPos(); // will be used to calculate note length
652    
653          // cancel release process of voices on this key if needed          // cancel release process of voices on this key if needed
654          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !pEngineChannel->SustainPedal) {
655              pNoteOnEvent->Type = Event::type_cancel_release; // transform event type              RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
656              pEvents->move(pNoteOnEvent, pKey->pEvents); // move event to the key's own event list              if (itCancelReleaseEvent) {
657                    *itCancelReleaseEvent = *itNoteOnEventOnKeyList;         // copy event
658                    itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type
659                }
660                else dmsg(1,("Event pool emtpy!\n"));
661          }          }
662    
663          // allocate a new voice for the key          // allocate and trigger new voice(s) for the key
664          Voice* pNewVoice = pKey->pActiveVoices->alloc();          {
665          if (pNewVoice) {              // first, get total amount of required voices (dependant on amount of layers)
666              // launch the new voice              ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOnEventOnKeyList->Param.Note.Key);
667              if (pNewVoice->Trigger(pNoteOnEvent, this->Pitch, this->pInstrument) < 0) {              if (pRegion) {
668                  dmsg(1,("Triggering new voice failed!\n"));                  int voicesRequired = pRegion->Layers;
669                  pKey->pActiveVoices->free(pNewVoice);                  // now launch the required amount of voices
670              }                  for (int i = 0; i < voicesRequired; i++)
671              else if (!pKey->Active) { // mark as active key                      LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true, true);
                 pKey->Active = true;  
                 pKey->pSelf  = pActiveKeys->alloc();  
                 *pKey->pSelf = pNoteOnEvent->Key;  
672              }              }
673          }          }
674          else std::cerr << "No free voice!" << std::endl << std::flush;  
675            // if neither a voice was spawned or postponed then remove note on event from key again
676            if (!pKey->Active && !pKey->VoiceTheftsQueued)
677                pKey->pEvents->free(itNoteOnEventOnKeyList);
678    
679            if (!pEngineChannel->SoloMode || pEngineChannel->PortamentoPos < 0.0f) pEngineChannel->PortamentoPos = (float) key;
680            pKey->RoundRobinIndex++;
681      }      }
682    
683      /**      /**
# Line 515  namespace LinuxSampler { namespace gig { Line 686  namespace LinuxSampler { namespace gig {
686       *  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.
687       *  due to completion of sample playback).       *  due to completion of sample playback).
688       *       *
689       *  @param pNoteOffEvent - key, velocity and time stamp of the event       *  @param pEngineChannel - engine channel on which this event occured on
690         *  @param itNoteOffEvent - key, velocity and time stamp of the event
691       */       */
692      void Engine::ProcessNoteOff(Event* pNoteOffEvent) {      void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {
693          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOffEvent->Key];          #if !CONFIG_PROCESS_MUTED_CHANNELS
694            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
695            #endif
696    
697            const int iKey = itNoteOffEvent->Param.Note.Key;
698            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[iKey];
699          pKey->KeyPressed = false; // the MIDI key was now released          pKey->KeyPressed = false; // the MIDI key was now released
700    
701          // release voices on this key if needed          // move event to the key's own event list
702          if (pKey->Active && !SustainPedal) {          RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
703              pNoteOffEvent->Type = Event::type_release; // transform event type  
704              pEvents->move(pNoteOffEvent, pKey->pEvents); // move event to the key's own event list          bool bShouldRelease = pKey->Active && ShouldReleaseVoice(pEngineChannel, itNoteOffEventOnKeyList->Param.Note.Key);
705    
706            // in case Solo Mode is enabled, kill all voices on this key and respawn a voice on the highest pressed key (if any)
707            if (pEngineChannel->SoloMode) { //TODO: this feels like too much code just for handling solo mode :P
708                bool bOtherKeysPressed = false;
709                if (iKey == pEngineChannel->SoloKey) {
710                    pEngineChannel->SoloKey = -1;
711                    // if there's still a key pressed down, respawn a voice (group) on the highest key
712                    for (int i = 127; i > 0; i--) {
713                        midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[i];
714                        if (pOtherKey->KeyPressed) {
715                            bOtherKeysPressed = true;
716                            // make the other key the new 'currently active solo key'
717                            pEngineChannel->SoloKey = i;
718                            // get final portamento position of currently active voice
719                            if (pEngineChannel->PortamentoMode) {
720                                RTList<Voice>::Iterator itVoice = pKey->pActiveVoices->first();
721                                if (itVoice) itVoice->UpdatePortamentoPos(itNoteOffEventOnKeyList);
722                            }
723                            // create a pseudo note on event
724                            RTList<Event>::Iterator itPseudoNoteOnEvent = pOtherKey->pEvents->allocAppend();
725                            if (itPseudoNoteOnEvent) {
726                                // copy event
727                                *itPseudoNoteOnEvent = *itNoteOffEventOnKeyList;
728                                // transform event to a note on event
729                                itPseudoNoteOnEvent->Type                = Event::type_note_on;
730                                itPseudoNoteOnEvent->Param.Note.Key      = i;
731                                itPseudoNoteOnEvent->Param.Note.Velocity = pOtherKey->Velocity;
732                                // allocate and trigger new voice(s) for the other key
733                                {
734                                    // first, get total amount of required voices (dependant on amount of layers)
735                                    ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(i);
736                                    if (pRegion) {
737                                        int voicesRequired = pRegion->Layers;
738                                        // now launch the required amount of voices
739                                        for (int iLayer = 0; iLayer < voicesRequired; iLayer++)
740                                            LaunchVoice(pEngineChannel, itPseudoNoteOnEvent, iLayer, false, true, false);
741                                    }
742                                }
743                                // if neither a voice was spawned or postponed then remove note on event from key again
744                                if (!pOtherKey->Active && !pOtherKey->VoiceTheftsQueued)
745                                    pOtherKey->pEvents->free(itPseudoNoteOnEvent);
746    
747                            } else dmsg(1,("Could not respawn voice, no free event left\n"));
748                            break; // done
749                        }
750                    }
751                }
752                if (bOtherKeysPressed) {
753                    if (pKey->Active) { // kill all voices on this key
754                        bShouldRelease = false; // no need to release, as we kill it here
755                        RTList<Voice>::Iterator itVoiceToBeKilled = pKey->pActiveVoices->first();
756                        RTList<Voice>::Iterator end               = pKey->pActiveVoices->end();
757                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
758                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger)
759                                itVoiceToBeKilled->Kill(itNoteOffEventOnKeyList);
760                        }
761                    }
762                } else pEngineChannel->PortamentoPos = -1.0f;
763            }
764    
765            // if no solo mode (the usual case) or if solo mode and no other key pressed, then release voices on this key if needed
766            if (bShouldRelease) {
767                itNoteOffEventOnKeyList->Type = Event::type_release; // transform event type
768    
769                // spawn release triggered voice(s) if needed
770                if (pKey->ReleaseTrigger) {
771                    // first, get total amount of required voices (dependant on amount of layers)
772                    ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOffEventOnKeyList->Param.Note.Key);
773                    if (pRegion) {
774                        int voicesRequired = pRegion->Layers;
775    
776                        // MIDI note-on velocity is used instead of note-off velocity
777                        itNoteOffEventOnKeyList->Param.Note.Velocity = pKey->Velocity;
778    
779                        // now launch the required amount of voices
780                        for (int i = 0; i < voicesRequired; i++)
781                            LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, i, true, false, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
782                    }
783                    pKey->ReleaseTrigger = false;
784                }
785          }          }
786    
787            // if neither a voice was spawned or postponed on this key then remove note off event from key again
788            if (!pKey->Active && !pKey->VoiceTheftsQueued)
789                pKey->pEvents->free(itNoteOffEventOnKeyList);
790      }      }
791    
792      /**      /**
793       *  Moves pitchbend event from the general (input) event list to the pitch       *  Moves pitchbend event from the general (input) event list to the engine
794       *  event list.       *  channel's event list. It will actually processed later by the
795         *  respective voice.
796       *       *
797       *  @param pPitchbendEvent - absolute pitch value and time stamp of the event       *  @param pEngineChannel - engine channel on which this event occured on
798         *  @param itPitchbendEvent - absolute pitch value and time stamp of the event
799       */       */
800      void Engine::ProcessPitchbend(Event* pPitchbendEvent) {      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {
801          this->Pitch = pPitchbendEvent->Pitch; // store current pitch value          pEngineChannel->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value
         pEvents->move(pPitchbendEvent, pSynthesisEvents[Event::destination_vco]);  
802      }      }
803    
804      /**      /**
805       *  Immediately kills the voice given with pVoice (no matter if sustain is       *  Allocates and triggers a new voice. This method will usually be
806       *  pressed or not) and removes it from the MIDI key's list of active voice.       *  called by the ProcessNoteOn() method and by the voices itself
807       *  This method will e.g. be called if a voice went inactive by itself.       *  (e.g. to spawn further voices on the same key for layered sounds).
808       *       *
809       *  @param pVoice - points to the voice to be killed       *  @param pEngineChannel      - engine channel on which this event occured on
810         *  @param itNoteOnEvent       - key, velocity and time stamp of the event
811         *  @param iLayer              - layer index for the new voice (optional - only
812         *                               in case of layered sounds of course)
813         *  @param ReleaseTriggerVoice - if new voice is a release triggered voice
814         *                               (optional, default = false)
815         *  @param VoiceStealing       - if voice stealing should be performed
816         *                               when there is no free voice
817         *                               (optional, default = true)
818         *  @param HandleKeyGroupConflicts - if voices should be killed due to a
819         *                                   key group conflict
820         *  @returns pointer to new voice or NULL if there was no free voice or
821         *           if the voice wasn't triggered (for example when no region is
822         *           defined for the given key).
823       */       */
824      void Engine::KillVoice(Voice* pVoice) {      Pool<Voice>::Iterator Engine::LaunchVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing, bool HandleKeyGroupConflicts) {
825          if (pVoice) {          int MIDIKey            = itNoteOnEvent->Param.Note.Key;
826              if (pVoice->IsActive()) pVoice->Kill();          midi_key_info_t* pKey  = &pEngineChannel->pMIDIKeyInfo[MIDIKey];
827            ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(MIDIKey);
828    
829            // if nothing defined for this key
830            if (!pRegion) return Pool<Voice>::Iterator(); // nothing to do
831    
832            // only mark the first voice of a layered voice (group) to be in a
833            // key group, so the layered voices won't kill each other
834            int iKeyGroup = (iLayer == 0 && !ReleaseTriggerVoice) ? pRegion->KeyGroup : 0;
835    
836            // handle key group (a.k.a. exclusive group) conflicts
837            if (HandleKeyGroupConflicts) {
838                if (iKeyGroup) { // if this voice / key belongs to a key group
839                    uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[iKeyGroup];
840                    if (*ppKeyGroup) { // if there's already an active key in that key group
841                        midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[**ppKeyGroup];
842                        // kill all voices on the (other) key
843                        RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
844                        RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
845                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
846                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger) {
847                                itVoiceToBeKilled->Kill(itNoteOnEvent);
848                                --VoiceSpawnsLeft; //FIXME: just a hack, we should better check in StealVoice() if the voice was killed due to key conflict
849                            }
850                        }
851                    }
852                }
853            }
854    
855              midi_key_info_t* pKey = &pMIDIKeyInfo[pVoice->MIDIKey];          Voice::type_t VoiceType = Voice::type_normal;
856    
857            // get current dimension values to select the right dimension region
858            //TODO: for stolen voices this dimension region selection block is processed twice, this should be changed
859            //FIXME: controller values for selecting the dimension region here are currently not sample accurate
860            uint DimValues[8] = { 0 };
861            for (int i = pRegion->Dimensions - 1; i >= 0; i--) {
862                switch (pRegion->pDimensionDefinitions[i].dimension) {
863                    case ::gig::dimension_samplechannel:
864                        DimValues[i] = 0; //TODO: we currently ignore this dimension
865                        break;
866                    case ::gig::dimension_layer:
867                        DimValues[i] = iLayer;
868                        break;
869                    case ::gig::dimension_velocity:
870                        DimValues[i] = itNoteOnEvent->Param.Note.Velocity;
871                        break;
872                    case ::gig::dimension_channelaftertouch:
873                        DimValues[i] = 0; //TODO: we currently ignore this dimension
874                        break;
875                    case ::gig::dimension_releasetrigger:
876                        VoiceType = (ReleaseTriggerVoice) ? Voice::type_release_trigger : (!iLayer) ? Voice::type_release_trigger_required : Voice::type_normal;
877                        DimValues[i] = (uint) ReleaseTriggerVoice;
878                        break;
879                    case ::gig::dimension_keyboard:
880                        DimValues[i] = (uint) (pEngineChannel->CurrentKeyDimension * pRegion->pDimensionDefinitions[i].zones);
881                        break;
882                    case ::gig::dimension_roundrobin:
883                        DimValues[i] = (uint) pEngineChannel->pMIDIKeyInfo[MIDIKey].RoundRobinIndex; // incremented for each note on
884                        break;
885                    case ::gig::dimension_random:
886                        RandomSeed   = RandomSeed * 1103515245 + 12345; // classic pseudo random number generator
887                        DimValues[i] = (uint) RandomSeed >> (32 - pRegion->pDimensionDefinitions[i].bits); // highest bits are most random
888                        break;
889                    case ::gig::dimension_modwheel:
890                        DimValues[i] = pEngineChannel->ControllerTable[1];
891                        break;
892                    case ::gig::dimension_breath:
893                        DimValues[i] = pEngineChannel->ControllerTable[2];
894                        break;
895                    case ::gig::dimension_foot:
896                        DimValues[i] = pEngineChannel->ControllerTable[4];
897                        break;
898                    case ::gig::dimension_portamentotime:
899                        DimValues[i] = pEngineChannel->ControllerTable[5];
900                        break;
901                    case ::gig::dimension_effect1:
902                        DimValues[i] = pEngineChannel->ControllerTable[12];
903                        break;
904                    case ::gig::dimension_effect2:
905                        DimValues[i] = pEngineChannel->ControllerTable[13];
906                        break;
907                    case ::gig::dimension_genpurpose1:
908                        DimValues[i] = pEngineChannel->ControllerTable[16];
909                        break;
910                    case ::gig::dimension_genpurpose2:
911                        DimValues[i] = pEngineChannel->ControllerTable[17];
912                        break;
913                    case ::gig::dimension_genpurpose3:
914                        DimValues[i] = pEngineChannel->ControllerTable[18];
915                        break;
916                    case ::gig::dimension_genpurpose4:
917                        DimValues[i] = pEngineChannel->ControllerTable[19];
918                        break;
919                    case ::gig::dimension_sustainpedal:
920                        DimValues[i] = pEngineChannel->ControllerTable[64];
921                        break;
922                    case ::gig::dimension_portamento:
923                        DimValues[i] = pEngineChannel->ControllerTable[65];
924                        break;
925                    case ::gig::dimension_sostenutopedal:
926                        DimValues[i] = pEngineChannel->ControllerTable[66];
927                        break;
928                    case ::gig::dimension_softpedal:
929                        DimValues[i] = pEngineChannel->ControllerTable[67];
930                        break;
931                    case ::gig::dimension_genpurpose5:
932                        DimValues[i] = pEngineChannel->ControllerTable[80];
933                        break;
934                    case ::gig::dimension_genpurpose6:
935                        DimValues[i] = pEngineChannel->ControllerTable[81];
936                        break;
937                    case ::gig::dimension_genpurpose7:
938                        DimValues[i] = pEngineChannel->ControllerTable[82];
939                        break;
940                    case ::gig::dimension_genpurpose8:
941                        DimValues[i] = pEngineChannel->ControllerTable[83];
942                        break;
943                    case ::gig::dimension_effect1depth:
944                        DimValues[i] = pEngineChannel->ControllerTable[91];
945                        break;
946                    case ::gig::dimension_effect2depth:
947                        DimValues[i] = pEngineChannel->ControllerTable[92];
948                        break;
949                    case ::gig::dimension_effect3depth:
950                        DimValues[i] = pEngineChannel->ControllerTable[93];
951                        break;
952                    case ::gig::dimension_effect4depth:
953                        DimValues[i] = pEngineChannel->ControllerTable[94];
954                        break;
955                    case ::gig::dimension_effect5depth:
956                        DimValues[i] = pEngineChannel->ControllerTable[95];
957                        break;
958                    case ::gig::dimension_none:
959                        std::cerr << "gig::Engine::LaunchVoice() Error: dimension=none\n" << std::flush;
960                        break;
961                    default:
962                        std::cerr << "gig::Engine::LaunchVoice() Error: Unknown dimension\n" << std::flush;
963                }
964            }
965            ::gig::DimensionRegion* pDimRgn = pRegion->GetDimensionRegionByValue(DimValues);
966    
967            // no need to continue if sample is silent
968            if (!pDimRgn->pSample || !pDimRgn->pSample->SamplesTotal) return Pool<Voice>::Iterator();
969    
970            // allocate a new voice for the key
971            Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
972            if (itNewVoice) {
973                // launch the new voice
974                if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pDimRgn, VoiceType, iKeyGroup) < 0) {
975                    dmsg(4,("Voice not triggered\n"));
976                    pKey->pActiveVoices->free(itNewVoice);
977                }
978                else { // on success
979                    --VoiceSpawnsLeft;
980                    if (!pKey->Active) { // mark as active key
981                        pKey->Active = true;
982                        pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();
983                        *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
984                    }
985                    if (itNewVoice->KeyGroup) {
986                        uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup];
987                        *ppKeyGroup = &*pKey->itSelf; // put key as the (new) active key to its key group
988                    }
989                    if (itNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)
990                    return itNewVoice; // success
991                }
992            }
993            else if (VoiceStealing) {
994                // try to steal one voice
995                int result = StealVoice(pEngineChannel, itNoteOnEvent);
996                if (!result) { // voice stolen successfully
997                    // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died
998                    RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();
999                    if (itStealEvent) {
1000                        *itStealEvent = *itNoteOnEvent; // copy event
1001                        itStealEvent->Param.Note.Layer = iLayer;
1002                        itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;
1003                        pKey->VoiceTheftsQueued++;
1004                    }
1005                    else dmsg(1,("Voice stealing queue full!\n"));
1006                }
1007            }
1008    
1009            return Pool<Voice>::Iterator(); // no free voice or error
1010        }
1011    
1012        /**
1013         *  Will be called by LaunchVoice() method in case there are no free
1014         *  voices left. This method will select and kill one old voice for
1015         *  voice stealing and postpone the note-on event until the selected
1016         *  voice actually died.
1017         *
1018         *  @param pEngineChannel - engine channel on which this event occured on
1019         *  @param itNoteOnEvent - key, velocity and time stamp of the event
1020         *  @returns 0 on success, a value < 0 if no active voice could be picked for voice stealing
1021         */
1022        int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
1023            if (VoiceSpawnsLeft <= 0) {
1024                dmsg(1,("Max. voice thefts per audio fragment reached (you may raise CONFIG_MAX_VOICES).\n"));
1025                return -1;
1026            }
1027            if (!pEventPool->poolIsEmpty()) {
1028    
1029                RTList<Voice>::Iterator itSelectedVoice;
1030    
1031                // Select one voice for voice stealing
1032                switch (CONFIG_VOICE_STEAL_ALGO) {
1033    
1034                    // try to pick the oldest voice on the key where the new
1035                    // voice should be spawned, if there is no voice on that
1036                    // key, or no voice left to kill, then procceed with
1037                    // 'oldestkey' algorithm
1038                    case voice_steal_algo_oldestvoiceonkey: {
1039                        midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
1040                        itSelectedVoice = pSelectedKey->pActiveVoices->first();
1041                        // proceed iterating if voice was created in this fragment cycle
1042                        while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1043                        // if we haven't found a voice then proceed with algorithm 'oldestkey'
1044                        if (itSelectedVoice && itSelectedVoice->IsStealable()) break;
1045                    } // no break - intentional !
1046    
1047                    // try to pick the oldest voice on the oldest active key
1048                    // from the same engine channel
1049                    // (caution: must stay after 'oldestvoiceonkey' algorithm !)
1050                    case voice_steal_algo_oldestkey: {
1051                        // if we already stole in this fragment, try to proceed on same key
1052                        if (this->itLastStolenVoice) {
1053                            itSelectedVoice = this->itLastStolenVoice;
1054                            do {
1055                                ++itSelectedVoice;
1056                            } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1057                            // found a "stealable" voice ?
1058                            if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1059                                // remember which voice we stole, so we can simply proceed on next voice stealing
1060                                this->itLastStolenVoice = itSelectedVoice;
1061                                break; // selection succeeded
1062                            }
1063                        }
1064                        // get (next) oldest key
1065                        RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKey) ? ++this->iuiLastStolenKey : pEngineChannel->pActiveKeys->first();
1066                        while (iuiSelectedKey) {
1067                            midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];
1068                            itSelectedVoice = pSelectedKey->pActiveVoices->first();
1069                            // proceed iterating if voice was created in this fragment cycle
1070                            while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1071                            // found a "stealable" voice ?
1072                            if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1073                                // remember which voice on which key we stole, so we can simply proceed on next voice stealing
1074                                this->iuiLastStolenKey  = iuiSelectedKey;
1075                                this->itLastStolenVoice = itSelectedVoice;
1076                                break; // selection succeeded
1077                            }
1078                            ++iuiSelectedKey; // get next oldest key
1079                        }
1080                        break;
1081                    }
1082    
1083                    // don't steal anything
1084                    case voice_steal_algo_none:
1085                    default: {
1086                        dmsg(1,("No free voice (voice stealing disabled)!\n"));
1087                        return -1;
1088                    }
1089                }
1090    
1091                // if we couldn't steal a voice from the same engine channel then
1092                // steal oldest voice on the oldest key from any other engine channel
1093                // (the smaller engine channel number, the higher priority)
1094                if (!itSelectedVoice || !itSelectedVoice->IsStealable()) {
1095                    EngineChannel* pSelectedChannel;
1096                    int            iChannelIndex;
1097                    // select engine channel
1098                    if (pLastStolenChannel) {
1099                        pSelectedChannel = pLastStolenChannel;
1100                        iChannelIndex    = pSelectedChannel->iEngineIndexSelf;
1101                    } else { // pick the engine channel followed by this engine channel
1102                        iChannelIndex    = (pEngineChannel->iEngineIndexSelf + 1) % engineChannels.size();
1103                        pSelectedChannel = engineChannels[iChannelIndex];
1104                    }
1105    
1106                    // if we already stole in this fragment, try to proceed on same key
1107                    if (this->itLastStolenVoiceGlobally) {
1108                        itSelectedVoice = this->itLastStolenVoiceGlobally;
1109                        do {
1110                            ++itSelectedVoice;
1111                        } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1112                    }
1113    
1114                    #if CONFIG_DEVMODE
1115                    EngineChannel* pBegin = pSelectedChannel; // to detect endless loop
1116                    #endif // CONFIG_DEVMODE
1117    
1118                    // did we find a 'stealable' voice?
1119                    if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1120                        // remember which voice we stole, so we can simply proceed on next voice stealing
1121                        this->itLastStolenVoiceGlobally = itSelectedVoice;
1122                    } else while (true) { // iterate through engine channels
1123                        // get (next) oldest key
1124                        RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKeyGlobally) ? ++this->iuiLastStolenKeyGlobally : pSelectedChannel->pActiveKeys->first();
1125                        this->iuiLastStolenKeyGlobally = RTList<uint>::Iterator(); // to prevent endless loop (see line above)
1126                        while (iuiSelectedKey) {
1127                            midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];
1128                            itSelectedVoice = pSelectedKey->pActiveVoices->first();
1129                            // proceed iterating if voice was created in this fragment cycle
1130                            while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1131                            // found a "stealable" voice ?
1132                            if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1133                                // remember which voice on which key on which engine channel we stole, so we can simply proceed on next voice stealing
1134                                this->iuiLastStolenKeyGlobally  = iuiSelectedKey;
1135                                this->itLastStolenVoiceGlobally = itSelectedVoice;
1136                                this->pLastStolenChannel        = pSelectedChannel;
1137                                goto stealable_voice_found; // selection succeeded
1138                            }
1139                            ++iuiSelectedKey; // get next key on current engine channel
1140                        }
1141                        // get next engine channel
1142                        iChannelIndex    = (iChannelIndex + 1) % engineChannels.size();
1143                        pSelectedChannel = engineChannels[iChannelIndex];
1144    
1145                        #if CONFIG_DEVMODE
1146                        if (pSelectedChannel == pBegin) {
1147                            dmsg(1,("FATAL ERROR: voice stealing endless loop!\n"));
1148                            dmsg(1,("VoiceSpawnsLeft=%d.\n", VoiceSpawnsLeft));
1149                            dmsg(1,("Exiting.\n"));
1150                            exit(-1);
1151                        }
1152                        #endif // CONFIG_DEVMODE
1153                    }
1154                }
1155    
1156                // jump point if a 'stealable' voice was found
1157                stealable_voice_found:
1158    
1159                #if CONFIG_DEVMODE
1160                if (!itSelectedVoice->IsActive()) {
1161                    dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
1162                    return -1;
1163                }
1164                #endif // CONFIG_DEVMODE
1165    
1166                // now kill the selected voice
1167                itSelectedVoice->Kill(itNoteOnEvent);
1168    
1169                --VoiceSpawnsLeft;
1170    
1171                return 0; // success
1172            }
1173            else {
1174                dmsg(1,("Event pool emtpy!\n"));
1175                return -1;
1176            }
1177        }
1178    
1179        /**
1180         *  Removes the given voice from the MIDI key's list of active voices.
1181         *  This method will be called when a voice went inactive, e.g. because
1182         *  it finished to playback its sample, finished its release stage or
1183         *  just was killed.
1184         *
1185         *  @param pEngineChannel - engine channel on which this event occured on
1186         *  @param itVoice - points to the voice to be freed
1187         */
1188        void Engine::FreeVoice(EngineChannel* pEngineChannel, Pool<Voice>::Iterator& itVoice) {
1189            if (itVoice) {
1190                midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itVoice->MIDIKey];
1191    
1192                uint keygroup = itVoice->KeyGroup;
1193    
1194              // free the voice object              // free the voice object
1195              pVoicePool->free(pVoice);              pVoicePool->free(itVoice);
1196    
1197              // 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
1198              if (pKey->pActiveVoices->is_empty()) {              if (pKey->pActiveVoices->isEmpty() && keygroup) {
1199                  pKey->Active = false;                  uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[keygroup];
1200                  pActiveKeys->free(pKey->pSelf); // remove key from list of active keys                  if (*ppKeyGroup == &*pKey->itSelf) *ppKeyGroup = NULL; // remove key from key group
                 pKey->pSelf = NULL;  
                 dmsg(3,("Key has no more voices now\n"));  
1201              }              }
1202          }          }
1203          else std::cerr << "Couldn't release voice! (pVoice == NULL)\n" << std::flush;          else std::cerr << "Couldn't release voice! (!itVoice)\n" << std::flush;
1204        }
1205    
1206        /**
1207         *  Called when there's no more voice left on a key, this call will
1208         *  update the key info respectively.
1209         *
1210         *  @param pEngineChannel - engine channel on which this event occured on
1211         *  @param pKey - key which is now inactive
1212         */
1213        void Engine::FreeKey(EngineChannel* pEngineChannel, midi_key_info_t* pKey) {
1214            if (pKey->pActiveVoices->isEmpty()) {
1215                pKey->Active = false;
1216                pEngineChannel->pActiveKeys->free(pKey->itSelf); // remove key from list of active keys
1217                pKey->itSelf = RTList<uint>::Iterator();
1218                pKey->ReleaseTrigger = false;
1219                pKey->pEvents->clear();
1220                dmsg(3,("Key has no more voices now\n"));
1221            }
1222            else dmsg(1,("gig::Engine: Oops, tried to free a key which contains voices.\n"));
1223      }      }
1224    
1225      /**      /**
1226       *  Reacts on supported control change commands (e.g. pitch bend wheel,       *  Reacts on supported control change commands (e.g. pitch bend wheel,
1227       *  modulation wheel, aftertouch).       *  modulation wheel, aftertouch).
1228       *       *
1229       *  @param pControlChangeEvent - controller, value and time stamp of the event       *  @param pEngineChannel - engine channel on which this event occured on
1230         *  @param itControlChangeEvent - controller, value and time stamp of the event
1231       */       */
1232      void Engine::ProcessControlChange(Event* pControlChangeEvent) {      void Engine::ProcessControlChange(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itControlChangeEvent) {
1233          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", pControlChangeEvent->Controller, pControlChangeEvent->Value));          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", itControlChangeEvent->Param.CC.Controller, itControlChangeEvent->Param.CC.Value));
1234    
1235          switch (pControlChangeEvent->Controller) {          // update controller value in the engine channel's controller table
1236              case 64: {          pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
1237                  if (pControlChangeEvent->Value >= 64 && !SustainPedal) {  
1238                      dmsg(4,("PEDAL DOWN\n"));          switch (itControlChangeEvent->Param.CC.Controller) {
1239                      SustainPedal = true;              case 5: { // portamento time
1240                    pEngineChannel->PortamentoTime = (float) itControlChangeEvent->Param.CC.Value / 127.0f * (float) CONFIG_PORTAMENTO_TIME_MAX + (float) CONFIG_PORTAMENTO_TIME_MIN;
1241                    break;
1242                }
1243                case 7: { // volume
1244                    //TODO: not sample accurate yet
1245                    pEngineChannel->GlobalVolume = VolumeCurve[itControlChangeEvent->Param.CC.Value] *  CONFIG_GLOBAL_ATTENUATION;
1246                    pEngineChannel->bStatusChanged = true; // engine channel status has changed, so set notify flag
1247                    break;
1248                }
1249                case 10: { // panpot
1250                    //TODO: not sample accurate yet
1251                    pEngineChannel->GlobalPanLeft  = PanCurve[128 - itControlChangeEvent->Param.CC.Value];
1252                    pEngineChannel->GlobalPanRight = PanCurve[itControlChangeEvent->Param.CC.Value];
1253                    break;
1254                }
1255                case 64: { // sustain
1256                    if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {
1257                        dmsg(4,("DAMPER (RIGHT) PEDAL DOWN\n"));
1258                        pEngineChannel->SustainPedal = true;
1259    
1260                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1261                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1262                        #endif
1263    
1264                      // cancel release process of voices if necessary                      // cancel release process of voices if necessary
1265                      uint* piKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1266                      if (piKey) {                      for (; iuiKey; ++iuiKey) {
1267                          pControlChangeEvent->Type = Event::type_cancel_release; // transform event type                          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1268                          while (piKey) {                          if (!pKey->KeyPressed) {
1269                              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1270                              pActiveKeys->set_current(piKey);                              if (itNewEvent) {
1271                              piKey = pActiveKeys->next();                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1272                              if (!pKey->KeyPressed) {                                  itNewEvent->Type = Event::type_cancel_release; // transform event type
                                 Event* pNewEvent = pKey->pEvents->alloc();  
                                 if (pNewEvent) *pNewEvent = *pControlChangeEvent; // copy event to the key's own event list  
                                 else dmsg(1,("Event pool emtpy!\n"));  
1273                              }                              }
1274                                else dmsg(1,("Event pool emtpy!\n"));
1275                          }                          }
1276                      }                      }
1277                  }                  }
1278                  if (pControlChangeEvent->Value < 64 && SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {
1279                      dmsg(4,("PEDAL UP\n"));                      dmsg(4,("DAMPER (RIGHT) PEDAL UP\n"));
1280                      SustainPedal = false;                      pEngineChannel->SustainPedal = false;
1281    
1282                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1283                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1284                        #endif
1285    
1286                      // release voices if their respective key is not pressed                      // release voices if their respective key is not pressed
1287                      uint* piKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1288                      if (piKey) {                      for (; iuiKey; ++iuiKey) {
1289                          pControlChangeEvent->Type = Event::type_release; // transform event type                          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1290                          while (piKey) {                          if (!pKey->KeyPressed && ShouldReleaseVoice(pEngineChannel, *iuiKey)) {
1291                              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1292                              pActiveKeys->set_current(piKey);                              if (itNewEvent) {
1293                              piKey = pActiveKeys->next();                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1294                              if (!pKey->KeyPressed) {                                  itNewEvent->Type = Event::type_release; // transform event type
                                 Event* pNewEvent = pKey->pEvents->alloc();  
                                 if (pNewEvent) *pNewEvent = *pControlChangeEvent; // copy event to the key's own event list  
                                 else dmsg(1,("Event pool emtpy!\n"));  
1295                              }                              }
1296                                else dmsg(1,("Event pool emtpy!\n"));
1297                            }
1298                        }
1299                    }
1300                    break;
1301                }
1302                case 65: { // portamento on / off
1303                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1304                    pEngineChannel->PortamentoMode = itControlChangeEvent->Param.CC.Value >= 64;
1305                    break;
1306                }
1307                case 66: { // sostenuto
1308                    if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SostenutoPedal) {
1309                        dmsg(4,("SOSTENUTO (CENTER) PEDAL DOWN\n"));
1310                        pEngineChannel->SostenutoPedal = true;
1311    
1312                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1313                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1314                        #endif
1315    
1316                        SostenutoKeyCount = 0;
1317                        // Remeber the pressed keys
1318                        RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1319                        for (; iuiKey; ++iuiKey) {
1320                            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1321                            if (pKey->KeyPressed && SostenutoKeyCount < 128) SostenutoKeys[SostenutoKeyCount++] = *iuiKey;
1322                        }
1323                    }
1324                    if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SostenutoPedal) {
1325                        dmsg(4,("SOSTENUTO (CENTER) PEDAL UP\n"));
1326                        pEngineChannel->SostenutoPedal = false;
1327    
1328                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1329                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1330                        #endif
1331    
1332                        // release voices if the damper pedal is up and their respective key is not pressed
1333                        for (int i = 0; i < SostenutoKeyCount; i++) {
1334                            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[SostenutoKeys[i]];
1335                            if (!pKey->KeyPressed && !pEngineChannel->SustainPedal) {
1336                                RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1337                                if (itNewEvent) {
1338                                    *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1339                                    itNewEvent->Type = Event::type_release; // transform event type
1340                                }
1341                                else dmsg(1,("Event pool emtpy!\n"));
1342                            }
1343                        }
1344                    }
1345                    break;
1346                }
1347    
1348    
1349                // Channel Mode Messages
1350    
1351                case 120: { // all sound off
1352                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1353                    break;
1354                }
1355                case 121: { // reset all controllers
1356                    pEngineChannel->ResetControllers();
1357                    break;
1358                }
1359                case 123: { // all notes off
1360                    #if CONFIG_PROCESS_ALL_NOTES_OFF
1361                    ReleaseAllVoices(pEngineChannel, itControlChangeEvent);
1362                    #endif // CONFIG_PROCESS_ALL_NOTES_OFF
1363                    break;
1364                }
1365                case 126: { // mono mode on
1366                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1367                    pEngineChannel->SoloMode = true;
1368                    break;
1369                }
1370                case 127: { // poly mode on
1371                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1372                    pEngineChannel->SoloMode = false;
1373                    break;
1374                }
1375            }
1376        }
1377    
1378        /**
1379         *  Reacts on MIDI system exclusive messages.
1380         *
1381         *  @param itSysexEvent - sysex data size and time stamp of the sysex event
1382         */
1383        void Engine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) {
1384            RingBuffer<uint8_t>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();
1385    
1386            uint8_t exclusive_status, id;
1387            if (!reader.pop(&exclusive_status)) goto free_sysex_data;
1388            if (!reader.pop(&id))               goto free_sysex_data;
1389            if (exclusive_status != 0xF0)       goto free_sysex_data;
1390    
1391            switch (id) {
1392                case 0x41: { // Roland
1393                    dmsg(3,("Roland Sysex\n"));
1394                    uint8_t device_id, model_id, cmd_id;
1395                    if (!reader.pop(&device_id)) goto free_sysex_data;
1396                    if (!reader.pop(&model_id))  goto free_sysex_data;
1397                    if (!reader.pop(&cmd_id))    goto free_sysex_data;
1398                    if (model_id != 0x42 /*GS*/) goto free_sysex_data;
1399                    if (cmd_id != 0x12 /*DT1*/)  goto free_sysex_data;
1400    
1401                    // command address
1402                    uint8_t addr[3]; // 2 byte addr MSB, followed by 1 byte addr LSB)
1403                    const RingBuffer<uint8_t>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later
1404                    if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;
1405                    if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters
1406                        dmsg(3,("\tSystem Parameter\n"));
1407                    }
1408                    else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters
1409                        dmsg(3,("\tCommon Parameter\n"));
1410                    }
1411                    else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)
1412                        dmsg(3,("\tPart Parameter\n"));
1413                        switch (addr[2]) {
1414                            case 0x40: { // scale tuning
1415                                dmsg(3,("\t\tScale Tuning\n"));
1416                                uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave
1417                                if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;
1418                                uint8_t checksum;
1419                                if (!reader.pop(&checksum)) goto free_sysex_data;
1420                                #if CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1421                                if (GSCheckSum(checksum_reader, 12)) goto free_sysex_data;
1422                                #endif // CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1423                                for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;
1424                                AdjustScale((int8_t*) scale_tunes);
1425                                dmsg(3,("\t\t\tNew scale applied.\n"));
1426                                break;
1427                          }                          }
1428                      }                      }
1429                  }                  }
1430                    else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x20) { // Part Parameters (2)
1431                    }
1432                    else if (addr[0] == 0x41) { // Drum Setup Parameters
1433                    }
1434                  break;                  break;
1435              }              }
1436          }          }
1437    
1438          // update controller value in the engine's controller table          free_sysex_data: // finally free sysex data
1439          ControllerTable[pControlChangeEvent->Controller] = pControlChangeEvent->Value;          pSysexBuffer->increment_read_ptr(itSysexEvent->Param.Sysex.Size);
1440        }
1441    
1442          // move event from the unsorted event list to the control change event list      /**
1443          pEvents->move(pControlChangeEvent, pCCEvents);       * Calculates the Roland GS sysex check sum.
1444         *
1445         * @param AddrReader - reader which currently points to the first GS
1446         *                     command address byte of the GS sysex message in
1447         *                     question
1448         * @param DataSize   - size of the GS message data (in bytes)
1449         */
1450        uint8_t Engine::GSCheckSum(const RingBuffer<uint8_t>::NonVolatileReader AddrReader, uint DataSize) {
1451            RingBuffer<uint8_t>::NonVolatileReader reader = AddrReader;
1452            uint bytes = 3 /*addr*/ + DataSize;
1453            uint8_t addr_and_data[bytes];
1454            reader.read(&addr_and_data[0], bytes);
1455            uint8_t sum = 0;
1456            for (uint i = 0; i < bytes; i++) sum += addr_and_data[i];
1457            return 128 - sum % 128;
1458      }      }
1459    
1460      /**      /**
1461       * Initialize the parameter sequence for the modulation destination given by       * Allows to tune each of the twelve semitones of an octave.
1462       * by 'dst' with the constant value given by val.       *
1463         * @param ScaleTunes - detuning of all twelve semitones (in cents)
1464       */       */
1465      void Engine::ResetSynthesisParameters(Event::destination_t dst, float val) {      void Engine::AdjustScale(int8_t ScaleTunes[12]) {
1466          int maxsamples = pAudioOutputDevice->MaxSamplesPerCycle();          memcpy(&this->ScaleTuning[0], &ScaleTunes[0], 12); //TODO: currently not sample accurate
         for (int i = 0; i < maxsamples; i++) pSynthesisParameters[dst][i] = val;  
1467      }      }
1468    
1469      float Engine::Volume() {      /**
1470          return GlobalVolume;       * Releases all voices on an engine channel. All voices will go into
1471         * the release stage and thus it might take some time (e.g. dependant to
1472         * their envelope release time) until they actually die.
1473         *
1474         * @param pEngineChannel - engine channel on which all voices should be released
1475         * @param itReleaseEvent - event which caused this releasing of all voices
1476         */
1477        void Engine::ReleaseAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itReleaseEvent) {
1478            RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1479            while (iuiKey) {
1480                midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1481                ++iuiKey;
1482                // append a 'release' event to the key's own event list
1483                RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1484                if (itNewEvent) {
1485                    *itNewEvent = *itReleaseEvent; // copy original event (to the key's event list)
1486                    itNewEvent->Type = Event::type_release; // transform event type
1487                }
1488                else dmsg(1,("Event pool emtpy!\n"));
1489            }
1490        }
1491    
1492        /**
1493         * Kills all voices on an engine channel as soon as possible. Voices
1494         * won't get into release state, their volume level will be ramped down
1495         * as fast as possible.
1496         *
1497         * @param pEngineChannel - engine channel on which all voices should be killed
1498         * @param itKillEvent    - event which caused this killing of all voices
1499         */
1500        void Engine::KillAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itKillEvent) {
1501            RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1502            RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
1503            while (iuiKey != end) { // iterate through all active keys
1504                midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1505                ++iuiKey;
1506                RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
1507                RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
1508                for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
1509                    itVoice->Kill(itKillEvent);
1510                    --VoiceSpawnsLeft; //FIXME: just a temporary workaround, we should check the cause in StealVoice() instead
1511                }
1512            }
1513      }      }
1514    
1515      void Engine::Volume(float f) {      /**
1516          GlobalVolume = f;       * Determines whether the specified voice should be released.
1517         *
1518         * @param pEngineChannel - The engine channel on which the voice should be checked
1519         * @param Key - The key number
1520         * @returns true if the specified should be released, false otherwise.
1521         */
1522        bool Engine::ShouldReleaseVoice(EngineChannel* pEngineChannel, int Key) {
1523            if (pEngineChannel->SustainPedal) return false;
1524    
1525            if (pEngineChannel->SostenutoPedal) {
1526                for (int i = 0; i < SostenutoKeyCount; i++)
1527                    if (Key == SostenutoKeys[i]) return false;
1528            }
1529    
1530            return true;
1531      }      }
1532    
1533      uint Engine::VoiceCount() {      uint Engine::VoiceCount() {
# Line 674  namespace LinuxSampler { namespace gig { Line 1558  namespace LinuxSampler { namespace gig {
1558          return pDiskThread->GetBufferFillPercentage();          return pDiskThread->GetBufferFillPercentage();
1559      }      }
1560    
1561        String Engine::EngineName() {
1562            return LS_GIG_ENGINE_NAME;
1563        }
1564    
1565      String Engine::Description() {      String Engine::Description() {
1566          return "Gigasampler Engine";          return "Gigasampler Engine";
1567      }      }
1568    
1569      String Engine::Version() {      String Engine::Version() {
1570          return "0.0.1-0cvs20040423";          String s = "$Revision: 1.63 $";
1571            return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword
1572        }
1573    
1574        // static constant initializers
1575        const float* Engine::VolumeCurve(InitVolumeCurve());
1576        const float* Engine::PanCurve(InitPanCurve());
1577        const float* Engine::CrossfadeCurve(InitCrossfadeCurve());
1578    
1579        float* Engine::InitVolumeCurve() {
1580            // line-segment approximation
1581            const float segments[] = {
1582                0, 0, 2, 0.0046, 16, 0.016, 31, 0.051, 45, 0.115, 54.5, 0.2,
1583                64.5, 0.39, 74, 0.74, 92, 1.03, 114, 1.94, 119.2, 2.2, 127, 2.2
1584            };
1585            return InitCurve(segments);
1586        }
1587    
1588        float* Engine::InitPanCurve() {
1589            // line-segment approximation
1590            const float segments[] = {
1591                0, 0, 1, 0,
1592                2, 0.05, 31.5, 0.7, 51, 0.851, 74.5, 1.12,
1593                127, 1.41, 128, 1.41
1594            };
1595            return InitCurve(segments, 129);
1596        }
1597    
1598        float* Engine::InitCrossfadeCurve() {
1599            // line-segment approximation
1600            const float segments[] = {
1601                0, 0, 1, 0.03, 10, 0.1, 51, 0.58, 127, 1
1602            };
1603            return InitCurve(segments);
1604        }
1605    
1606        float* Engine::InitCurve(const float* segments, int size) {
1607            float* y = new float[size];
1608            for (int x = 0 ; x < size ; x++) {
1609                if (x > segments[2]) segments += 2;
1610                y[x] = segments[1] + (x - segments[0]) *
1611                    (segments[3] - segments[1]) / (segments[2] - segments[0]);
1612            }
1613            return y;
1614      }      }
1615    
1616  }} // namespace LinuxSampler::gig  }} // namespace LinuxSampler::gig

Legend:
Removed from v.53  
changed lines
  Added in v.880

  ViewVC Help
Powered by ViewVC