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

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

  ViewVC Help
Powered by ViewVC