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

Legend:
Removed from v.80  
changed lines
  Added in v.690

  ViewVC Help
Powered by ViewVC