/[svn]/linuxsampler/trunk/src/engines/gig/Engine.cpp
ViewVC logotype

Diff of /linuxsampler/trunk/src/engines/gig/Engine.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 271 by schoenebeck, Fri Oct 8 20:51:39 2004 UTC revision 466 by schoenebeck, Tue Mar 15 19:27:01 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      Engine::Engine() {      Engine::Engine() {
         pRIFF              = NULL;  
         pGig               = NULL;  
         pInstrument        = NULL;  
100          pAudioOutputDevice = NULL;          pAudioOutputDevice = NULL;
101          pDiskThread        = NULL;          pDiskThread        = NULL;
102          pEventGenerator    = NULL;          pEventGenerator    = NULL;
# Line 41  namespace LinuxSampler { namespace gig { Line 104  namespace LinuxSampler { namespace gig {
104          pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT, 0);          pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT, 0);
105          pEventPool         = new Pool<Event>(MAX_EVENTS_PER_FRAGMENT);          pEventPool         = new Pool<Event>(MAX_EVENTS_PER_FRAGMENT);
106          pVoicePool         = new Pool<Voice>(MAX_AUDIO_VOICES);          pVoicePool         = new Pool<Voice>(MAX_AUDIO_VOICES);
         pActiveKeys        = new Pool<uint>(128);  
107          pVoiceStealingQueue = new RTList<Event>(pEventPool);          pVoiceStealingQueue = new RTList<Event>(pEventPool);
108          pEvents            = new RTList<Event>(pEventPool);          pGlobalEvents      = new RTList<Event>(pEventPool);
         pCCEvents          = new RTList<Event>(pEventPool);  
         for (uint i = 0; i < Event::destination_count; i++) {  
             pSynthesisEvents[i] = new RTList<Event>(pEventPool);  
         }  
         for (uint i = 0; i < 128; i++) {  
             pMIDIKeyInfo[i].pActiveVoices  = new RTList<Voice>(pVoicePool);  
             pMIDIKeyInfo[i].KeyPressed     = false;  
             pMIDIKeyInfo[i].Active         = false;  
             pMIDIKeyInfo[i].ReleaseTrigger = false;  
             pMIDIKeyInfo[i].pEvents        = new RTList<Event>(pEventPool);  
         }  
109          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
110              iterVoice->SetEngine(this);              iterVoice->SetEngine(this);
111          }          }
# Line 64  namespace LinuxSampler { namespace gig { Line 115  namespace LinuxSampler { namespace gig {
115          pBasicFilterParameters  = NULL;          pBasicFilterParameters  = NULL;
116          pMainFilterParameters   = NULL;          pMainFilterParameters   = NULL;
117    
         InstrumentIdx = -1;  
         InstrumentStat = -1;  
   
         AudioDeviceChannelLeft  = -1;  
         AudioDeviceChannelRight = -1;  
   
118          ResetInternal();          ResetInternal();
119      }      }
120    
121      Engine::~Engine() {      Engine::~Engine() {
122          if (pDiskThread) {          if (pDiskThread) {
123                dmsg(1,("Stopping disk thread..."));
124              pDiskThread->StopThread();              pDiskThread->StopThread();
125              delete pDiskThread;              delete pDiskThread;
126                dmsg(1,("OK\n"));
127          }          }
         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;  
128          if (pEventQueue) delete pEventQueue;          if (pEventQueue) delete pEventQueue;
129          if (pEventPool)  delete pEventPool;          if (pEventPool)  delete pEventPool;
130          if (pVoicePool)  delete pVoicePool;          if (pVoicePool) {
131          if (pActiveKeys) delete pActiveKeys;              pVoicePool->clear();
132          if (pSysexBuffer) delete pSysexBuffer;              delete pVoicePool;
133            }
134          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
135          if (pMainFilterParameters) delete[] pMainFilterParameters;          if (pMainFilterParameters) delete[] pMainFilterParameters;
136          if (pBasicFilterParameters) delete[] pBasicFilterParameters;          if (pBasicFilterParameters) delete[] pBasicFilterParameters;
137          if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];          if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
138          if (pVoiceStealingQueue) delete pVoiceStealingQueue;          if (pVoiceStealingQueue) delete pVoiceStealingQueue;
139            if (pSysexBuffer) delete pSysexBuffer;
140            EngineFactory::Destroy(this);
141      }      }
142    
143      void Engine::Enable() {      void Engine::Enable() {
# Line 126  namespace LinuxSampler { namespace gig { Line 164  namespace LinuxSampler { namespace gig {
164       */       */
165      void Engine::Reset() {      void Engine::Reset() {
166          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();  
   
167          ResetInternal();          ResetInternal();
   
         // signal audio thread to continue with rendering  
         //SuspensionRequested = false;  
168          Enable();          Enable();
169      }      }
170    
# Line 152  namespace LinuxSampler { namespace gig { Line 173  namespace LinuxSampler { namespace gig {
173       *  control and status variables. This method is not thread safe!       *  control and status variables. This method is not thread safe!
174       */       */
175      void Engine::ResetInternal() {      void Engine::ResetInternal() {
         Pitch               = 0;  
         SustainPedal        = false;  
176          ActiveVoiceCount    = 0;          ActiveVoiceCount    = 0;
177          ActiveVoiceCountMax = 0;          ActiveVoiceCountMax = 0;
         GlobalVolume        = 1.0;  
178    
179          // reset voice stealing parameters          // reset voice stealing parameters
         itLastStolenVoice = RTList<Voice>::Iterator();  
         iuiLastStolenKey  = RTList<uint>::Iterator();  
180          pVoiceStealingQueue->clear();          pVoiceStealingQueue->clear();
181            itLastStolenVoice  = RTList<Voice>::Iterator();
182            iuiLastStolenKey   = RTList<uint>::Iterator();
183            pLastStolenChannel = NULL;
184    
185          // reset to normal chromatic scale (means equal temper)          // reset to normal chromatic scale (means equal temper)
186          memset(&ScaleTuning[0], 0x00, 12);          memset(&ScaleTuning[0], 0x00, 12);
187    
         // set all MIDI controller values to zero  
         memset(ControllerTable, 0x00, 128);  
   
         // reset key info  
         for (uint i = 0; i < 128; i++) {  
             pMIDIKeyInfo[i].pActiveVoices->clear();  
             pMIDIKeyInfo[i].pEvents->clear();  
             pMIDIKeyInfo[i].KeyPressed     = false;  
             pMIDIKeyInfo[i].Active         = false;  
             pMIDIKeyInfo[i].ReleaseTrigger = false;  
             pMIDIKeyInfo[i].itSelf         = Pool<uint>::Iterator();  
         }  
   
         // reset all key groups  
         map<uint,uint*>::iterator iter = ActiveKeyGroups.begin();  
         for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;  
   
188          // reset all voices          // reset all voices
189          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
190              iterVoice->Reset();              iterVoice->Reset();
191          }          }
192          pVoicePool->clear();          pVoicePool->clear();
193    
         // free all active keys  
         pActiveKeys->clear();  
   
194          // reset disk thread          // reset disk thread
195          if (pDiskThread) pDiskThread->Reset();          if (pDiskThread) pDiskThread->Reset();
196    
# Line 199  namespace LinuxSampler { namespace gig { Line 198  namespace LinuxSampler { namespace gig {
198          pEventQueue->init();          pEventQueue->init();
199      }      }
200    
     /**  
      *  Load an instrument from a .gig file.  
      *  
      *  @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);  
         }  
   
         InstrumentFile = FileName;  
         InstrumentIdx = Instrument;  
         InstrumentStat = 0;  
   
         // delete all key groups  
         ActiveKeyGroups.clear();  
   
         // request gig instrument from instrument manager  
         try {  
             instrument_id_t instrid;  
             instrid.FileName    = FileName;  
             instrid.iInstrument = Instrument;  
             pInstrument = Instruments.Borrow(instrid, this);  
             if (!pInstrument) {  
                 InstrumentStat = -1;  
                 dmsg(1,("no instrument loaded!!!\n"));  
                 exit(EXIT_FAILURE);  
             }  
         }  
         catch (RIFF::Exception e) {  
             InstrumentStat = -2;  
             String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;  
             throw LinuxSamplerException(msg);  
         }  
         catch (InstrumentResourceManagerException e) {  
             InstrumentStat = -3;  
             String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();  
             throw LinuxSamplerException(msg);  
         }  
         catch (...) {  
             InstrumentStat = -4;  
             throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");  
         }  
   
         // rebuild ActiveKeyGroups map with key groups of current instrument  
         for (::gig::Region* pRegion = pInstrument->GetFirstRegion(); pRegion; pRegion = pInstrument->GetNextRegion())  
             if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL;  
   
         InstrumentStat = 100;  
   
         // inform audio driver for the need of two channels  
         try {  
             if (pAudioOutputDevice) pAudioOutputDevice->AcquireChannels(2); // gig Engine only stereo  
         }  
         catch (AudioOutputException e) {  
             String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();  
             throw LinuxSamplerException(msg);  
         }  
   
         Enable();  
     }  
   
     /**  
      * Will be called by the InstrumentResourceManager when the instrument  
      * we are currently using in this engine is going to be updated, so we  
      * can stop playback before that happens.  
      */  
     void Engine::ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {  
         dmsg(3,("gig::Engine: Received instrument update message.\n"));  
         DisableAndLock();  
         ResetInternal();  
         this->pInstrument = NULL;  
     }  
   
     /**  
      * Will be called by the InstrumentResourceManager when the instrument  
      * update process was completed, so we can continue with playback.  
      */  
     void Engine::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {  
         this->pInstrument = pNewResource; //TODO: there are couple of engine parameters we should update here as well if the instrument was updated (see LoadInstrument())  
         Enable();  
     }  
   
201      void Engine::Connect(AudioOutputDevice* pAudioOut) {      void Engine::Connect(AudioOutputDevice* pAudioOut) {
202          pAudioOutputDevice = pAudioOut;          pAudioOutputDevice = pAudioOut;
203    
# Line 306  namespace LinuxSampler { namespace gig { Line 212  namespace LinuxSampler { namespace gig {
212              throw LinuxSamplerException(msg);              throw LinuxSamplerException(msg);
213          }          }
214    
215          this->AudioDeviceChannelLeft  = 0;          this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle();
216          this->AudioDeviceChannelRight = 1;          this->SampleRate         = pAudioOutputDevice->SampleRate();
217          this->pOutputLeft             = pAudioOutputDevice->Channel(0)->Buffer();  
218          this->pOutputRight            = pAudioOutputDevice->Channel(1)->Buffer();          // FIXME: audio drivers with varying fragment sizes might be a problem here
219          this->MaxSamplesPerCycle      = pAudioOutputDevice->MaxSamplesPerCycle();          MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * EG_MIN_RELEASE_TIME) - 1;
220          this->SampleRate              = pAudioOutputDevice->SampleRate();          if (MaxFadeOutPos < 0)
221                throw LinuxSamplerException("EG_MIN_RELEASE_TIME in EGADSR.h too big for current audio fragment size / sampling rate!");
222    
223          // (re)create disk thread          // (re)create disk thread
224          if (this->pDiskThread) {          if (this->pDiskThread) {
225                dmsg(1,("Stopping disk thread..."));
226              this->pDiskThread->StopThread();              this->pDiskThread->StopThread();
227              delete this->pDiskThread;              delete this->pDiskThread;
228                dmsg(1,("OK\n"));
229          }          }
230          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo
231          if (!pDiskThread) {          if (!pDiskThread) {
# Line 335  namespace LinuxSampler { namespace gig { Line 244  namespace LinuxSampler { namespace gig {
244          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
245    
246          // (re)allocate synthesis parameter matrix          // (re)allocate synthesis parameter matrix
247          if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];          if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
248          pSynthesisParameters[0] = new float[Event::destination_count * pAudioOut->MaxSamplesPerCycle()];  
249            #if defined(__APPLE__)
250            pSynthesisParameters[0] = (float *) malloc(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle());
251            #else
252            pSynthesisParameters[0] = (float *) memalign(16,(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle()));
253            #endif
254          for (int dst = 1; dst < Event::destination_count; dst++)          for (int dst = 1; dst < Event::destination_count; dst++)
255              pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();              pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();
256    
# Line 358  namespace LinuxSampler { namespace gig { Line 272  namespace LinuxSampler { namespace gig {
272          }          }
273      }      }
274    
275      void Engine::DisconnectAudioOutputDevice() {      void Engine::ClearEventLists() {
276          if (pAudioOutputDevice) { // if clause to prevent disconnect loops          pGlobalEvents->clear();
277              AudioOutputDevice* olddevice = pAudioOutputDevice;      }
278              pAudioOutputDevice = NULL;  
279              olddevice->Disconnect(this);      /**
280              AudioDeviceChannelLeft  = -1;       * Copy all events from the engine's global input queue buffer to the
281              AudioDeviceChannelRight = -1;       * engine's internal event list. This will be done at the beginning of
282         * each audio cycle (that is each RenderAudio() call) to distinguish
283         * all global events which have to be processed in the current audio
284         * cycle. These events are usually just SysEx messages. Every
285         * EngineChannel has it's own input event queue buffer and event list
286         * to handle common events like NoteOn, NoteOff and ControlChange
287         * events.
288         *
289         * @param Samples - number of sample points to be processed in the
290         *                  current audio cycle
291         */
292        void Engine::ImportEvents(uint Samples) {
293            RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
294            Event* pEvent;
295            while (true) {
296                // get next event from input event queue
297                if (!(pEvent = eventQueueReader.pop())) break;
298                // if younger event reached, ignore that and all subsequent ones for now
299                if (pEvent->FragmentPos() >= Samples) {
300                    eventQueueReader--;
301                    dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
302                    pEvent->ResetFragmentPos();
303                    break;
304                }
305                // copy event to internal event list
306                if (pGlobalEvents->poolIsEmpty()) {
307                    dmsg(1,("Event pool emtpy!\n"));
308                    break;
309                }
310                *pGlobalEvents->allocAppend() = *pEvent;
311          }          }
312            eventQueueReader.free(); // free all copied events from input queue
313      }      }
314    
315      /**      /**
# Line 381  namespace LinuxSampler { namespace gig { Line 325  namespace LinuxSampler { namespace gig {
325      int Engine::RenderAudio(uint Samples) {      int Engine::RenderAudio(uint Samples) {
326          dmsg(5,("RenderAudio(Samples=%d)\n", Samples));          dmsg(5,("RenderAudio(Samples=%d)\n", Samples));
327    
328          // return if no instrument loaded or engine disabled          // return if engine disabled
329          if (EngineDisabled.Pop()) {          if (EngineDisabled.Pop()) {
330              dmsg(5,("gig::Engine: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));              dmsg(5,("gig::Engine: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));
331              return 0;              return 0;
332          }          }
         if (!pInstrument) {  
             dmsg(5,("gig::Engine: no instrument loaded\n"));  
             return 0;  
         }  
333    
334            // update time of start and end of this audio fragment (as events' time stamps relate to this)
335            pEventGenerator->UpdateFragmentTime(Samples);
336    
337          // empty the event lists for the new fragment          // get all events from the engine's global input event queue which belong to the current fragment
338          pEvents->clear();          // (these are usually just SysEx messages)
339          pCCEvents->clear();          ImportEvents(Samples);
340          for (uint i = 0; i < Event::destination_count; i++) {  
341              pSynthesisEvents[i]->clear();          // process engine global events (these are currently only MIDI System Exclusive messages)
         }  
342          {          {
343              RTList<uint>::Iterator iuiKey = pActiveKeys->first();              RTList<Event>::Iterator itEvent = pGlobalEvents->first();
344              RTList<uint>::Iterator end    = pActiveKeys->end();              RTList<Event>::Iterator end     = pGlobalEvents->end();
345              for(; iuiKey != end; ++iuiKey) {              for (; itEvent != end; ++itEvent) {
346                  pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key                  switch (itEvent->Type) {
347                        case Event::type_sysex:
348                            dmsg(5,("Engine: Sysex received\n"));
349                            ProcessSysex(itEvent);
350                            break;
351                    }
352              }              }
353          }          }
354    
355          // read and copy events from input queue          // We only allow a maximum of MAX_AUDIO_VOICES voices to be stolen
356          Event event = pEventGenerator->CreateEvent();          // in each audio fragment. All subsequent request for spawning new
357          while (true) {          // voices in the same audio fragment will be ignored.
358              if (!pEventQueue->pop(&event) || pEvents->poolIsEmpty()) break;          VoiceTheftsLeft = MAX_AUDIO_VOICES;
359              *pEvents->allocAppend() = event;  
360            // reset internal voice counter (just for statistic of active voices)
361            ActiveVoiceCountTemp = 0;
362    
363    
364            // handle events on all engine channels
365            for (int i = 0; i < engineChannels.size(); i++) {
366                if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
367                ProcessEvents(engineChannels[i], Samples);
368          }          }
369    
370            // render all 'normal', active voices on all engine channels
371            for (int i = 0; i < engineChannels.size(); i++) {
372                if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
373                RenderActiveVoices(engineChannels[i], Samples);
374            }
375    
376          // update time of start and end of this audio fragment (as events' time stamps relate to this)          // now that all ordinary voices on ALL engine channels are rendered, render new stolen voices
377          pEventGenerator->UpdateFragmentTime(Samples);          RenderStolenVoices(Samples);
378    
379            // handle cleanup on all engine channels for the next audio fragment
380            for (int i = 0; i < engineChannels.size(); i++) {
381                if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
382                PostProcess(engineChannels[i]);
383            }
384    
385    
386            // empty the engine's event list for the next audio fragment
387            ClearEventLists();
388    
389            // reset voice stealing for the next audio fragment
390            pVoiceStealingQueue->clear();
391            itLastStolenVoice  = RTList<Voice>::Iterator();
392            iuiLastStolenKey   = RTList<uint>::Iterator();
393            pLastStolenChannel = NULL;
394    
395            // just some statistics about this engine instance
396            ActiveVoiceCount = ActiveVoiceCountTemp;
397            if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;
398    
399            return 0;
400        }
401    
402        void Engine::ProcessEvents(EngineChannel* pEngineChannel, uint Samples) {
403            // get all events from the engine channels's input event queue which belong to the current fragment
404            // (these are the common events like NoteOn, NoteOff, ControlChange, etc.)
405            pEngineChannel->ImportEvents(Samples);
406    
407          // process events          // process events
408          {          {
409              RTList<Event>::Iterator itEvent = pEvents->first();              RTList<Event>::Iterator itEvent = pEngineChannel->pEvents->first();
410              RTList<Event>::Iterator end     = pEvents->end();              RTList<Event>::Iterator end     = pEngineChannel->pEvents->end();
411              for (; itEvent != end; ++itEvent) {              for (; itEvent != end; ++itEvent) {
412                  switch (itEvent->Type) {                  switch (itEvent->Type) {
413                      case Event::type_note_on:                      case Event::type_note_on:
414                          dmsg(5,("Engine: Note on received\n"));                          dmsg(5,("Engine: Note on received\n"));
415                          ProcessNoteOn(itEvent);                          ProcessNoteOn((EngineChannel*)itEvent->pEngineChannel, itEvent);
416                          break;                          break;
417                      case Event::type_note_off:                      case Event::type_note_off:
418                          dmsg(5,("Engine: Note off received\n"));                          dmsg(5,("Engine: Note off received\n"));
419                          ProcessNoteOff(itEvent);                          ProcessNoteOff((EngineChannel*)itEvent->pEngineChannel, itEvent);
420                          break;                          break;
421                      case Event::type_control_change:                      case Event::type_control_change:
422                          dmsg(5,("Engine: MIDI CC received\n"));                          dmsg(5,("Engine: MIDI CC received\n"));
423                          ProcessControlChange(itEvent);                          ProcessControlChange((EngineChannel*)itEvent->pEngineChannel, itEvent);
424                          break;                          break;
425                      case Event::type_pitchbend:                      case Event::type_pitchbend:
426                          dmsg(5,("Engine: Pitchbend received\n"));                          dmsg(5,("Engine: Pitchbend received\n"));
427                          ProcessPitchbend(itEvent);                          ProcessPitchbend((EngineChannel*)itEvent->pEngineChannel, itEvent);
                         break;  
                     case Event::type_sysex:  
                         dmsg(5,("Engine: Sysex received\n"));  
                         ProcessSysex(itEvent);  
428                          break;                          break;
429                  }                  }
430              }              }
431          }          }
432        }
433    
434        void Engine::RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {
435          int active_voices = 0;          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
436            RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
437          // render audio from all active voices          while (iuiKey != end) { // iterate through all active keys
438          {              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
439              RTList<uint>::Iterator iuiKey = pActiveKeys->first();              ++iuiKey;
440              RTList<uint>::Iterator end    = pActiveKeys->end();  
441              while (iuiKey != end) { // iterate through all active keys              RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
442                  midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];              RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
443                  ++iuiKey;              for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
444                    // now render current voice
445                  RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();                  itVoice->Render(Samples);
446                  RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();                  if (itVoice->IsActive()) ActiveVoiceCountTemp++; // still active
447                  for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key                  else { // voice reached end, is now inactive
448                      // now render current voice                      FreeVoice(pEngineChannel, itVoice); // remove voice from the list of active voices
                     itVoice->Render(Samples);  
                     if (itVoice->IsActive()) active_voices++; // still active  
                     else { // voice reached end, is now inactive  
                         KillVoiceImmediately(itVoice); // remove voice from the list of active voices  
                     }  
449                  }                  }
450              }              }
451          }          }
452        }
453    
454        void Engine::RenderStolenVoices(uint Samples) {
455            RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();
456            RTList<Event>::Iterator end               = pVoiceStealingQueue->end();
457            for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
458                EngineChannel* pEngineChannel = (EngineChannel*) itVoiceStealEvent->pEngineChannel;
459                Pool<Voice>::Iterator itNewVoice =
460                    LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false);
461                if (itNewVoice) {
462                    itNewVoice->Render(Samples);
463                    if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active
464                    else { // voice reached end, is now inactive
465                        FreeVoice(pEngineChannel, itNewVoice); // remove voice from the list of active voices
466                    }
467                }
468                else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));
469            }
470        }
471    
472          // now render all postponed voices from voice stealing      void Engine::PostProcess(EngineChannel* pEngineChannel) {
473            // free all keys which have no active voices left
474          {          {
475              RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();              RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
476              RTList<Event>::Iterator end               = pVoiceStealingQueue->end();              RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
477              for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {              while (iuiKey != end) { // iterate through all active keys
478                  Pool<Voice>::Iterator itNewVoice = LaunchVoice(itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false);                  midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
479                  if (itNewVoice) {                  ++iuiKey;
480                      itNewVoice->Render(Samples);                  if (pKey->pActiveVoices->isEmpty()) FreeKey(pEngineChannel, pKey);
481                      if (itNewVoice->IsActive()) active_voices++; // still active                  #if DEVMODE
482                      else { // voice reached end, is now inactive                  else { // FIXME: should be removed before the final release (purpose: just a sanity check for debugging)
483                          KillVoiceImmediately(itNewVoice); // remove voice from the list of active voices                      RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
484                        RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
485                        for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
486                            if (itVoice->itKillEvent) {
487                                dmsg(1,("gig::Engine: ERROR, killed voice survived !!!\n"));
488                            }
489                      }                      }
490                  }                  }
491                  else dmsg(1,("Ouch, voice stealing didn't work out!\n"));                  #endif // DEVMODE
492              }              }
493          }          }
         // reset voice stealing for the new fragment  
         pVoiceStealingQueue->clear();  
         itLastStolenVoice = RTList<Voice>::Iterator();  
         iuiLastStolenKey  = RTList<uint>::Iterator();  
   
   
         // write that to the disk thread class so that it can print it  
         // on the console for debugging purposes  
         ActiveVoiceCount = active_voices;  
         if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;  
494    
495            // empty the engine channel's own event lists
496          return 0;          pEngineChannel->ClearEventLists();
     }  
   
     /**  
      *  Will be called by the MIDIIn Thread to let the audio thread trigger a new  
      *  voice for the given key.  
      *  
      *  @param Key      - MIDI key number of the triggered key  
      *  @param Velocity - MIDI velocity value of the triggered key  
      */  
     void Engine::SendNoteOn(uint8_t Key, uint8_t Velocity) {  
         Event event               = pEventGenerator->CreateEvent();  
         event.Type                = Event::type_note_on;  
         event.Param.Note.Key      = Key;  
         event.Param.Note.Velocity = Velocity;  
         if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);  
         else dmsg(1,("Engine: Input event queue full!"));  
     }  
   
     /**  
      *  Will be called by the MIDIIn Thread to signal the audio thread to release  
      *  voice(s) on the given key.  
      *  
      *  @param Key      - MIDI key number of the released key  
      *  @param Velocity - MIDI release velocity value of the released key  
      */  
     void Engine::SendNoteOff(uint8_t Key, uint8_t Velocity) {  
         Event event               = pEventGenerator->CreateEvent();  
         event.Type                = Event::type_note_off;  
         event.Param.Note.Key      = Key;  
         event.Param.Note.Velocity = Velocity;  
         if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);  
         else dmsg(1,("Engine: Input event queue full!"));  
     }  
   
     /**  
      *  Will be called by the MIDIIn Thread to signal the audio thread to change  
      *  the pitch value for all voices.  
      *  
      *  @param Pitch - MIDI pitch value (-8192 ... +8191)  
      */  
     void Engine::SendPitchbend(int Pitch) {  
         Event event             = pEventGenerator->CreateEvent();  
         event.Type              = Event::type_pitchbend;  
         event.Param.Pitch.Pitch = Pitch;  
         if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);  
         else dmsg(1,("Engine: Input event queue full!"));  
     }  
   
     /**  
      *  Will be called by the MIDIIn Thread to signal the audio thread that a  
      *  continuous controller value has changed.  
      *  
      *  @param Controller - MIDI controller number of the occured control change  
      *  @param Value      - value of the control change  
      */  
     void Engine::SendControlChange(uint8_t Controller, uint8_t Value) {  
         Event event               = pEventGenerator->CreateEvent();  
         event.Type                = Event::type_control_change;  
         event.Param.CC.Controller = Controller;  
         event.Param.CC.Value      = Value;  
         if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);  
         else dmsg(1,("Engine: Input event queue full!"));  
497      }      }
498    
499      /**      /**
# Line 577  namespace LinuxSampler { namespace gig { Line 507  namespace LinuxSampler { namespace gig {
507          Event event             = pEventGenerator->CreateEvent();          Event event             = pEventGenerator->CreateEvent();
508          event.Type              = Event::type_sysex;          event.Type              = Event::type_sysex;
509          event.Param.Sysex.Size  = Size;          event.Param.Sysex.Size  = Size;
510            event.pEngineChannel    = NULL; // as Engine global event
511          if (pEventQueue->write_space() > 0) {          if (pEventQueue->write_space() > 0) {
512              if (pSysexBuffer->write_space() >= Size) {              if (pSysexBuffer->write_space() >= Size) {
513                  // copy sysex data to input buffer                  // copy sysex data to input buffer
# Line 600  namespace LinuxSampler { namespace gig { Line 531  namespace LinuxSampler { namespace gig {
531      /**      /**
532       *  Assigns and triggers a new voice for the respective MIDI key.       *  Assigns and triggers a new voice for the respective MIDI key.
533       *       *
534         *  @param pEngineChannel - engine channel on which this event occured on
535       *  @param itNoteOnEvent - key, velocity and time stamp of the event       *  @param itNoteOnEvent - key, velocity and time stamp of the event
536       */       */
537      void Engine::ProcessNoteOn(Pool<Event>::Iterator& itNoteOnEvent) {      void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
538          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];  
539            const int key = itNoteOnEvent->Param.Note.Key;
540    
541            // Change key dimension value if key is in keyswitching area
542            {
543                const ::gig::Instrument* pInstrument = pEngineChannel->pInstrument;
544                if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high)
545                    pEngineChannel->CurrentKeyDimension = ((key - pInstrument->DimensionKeyRange.low) * 128) /
546                        (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);
547            }
548    
549            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];
550    
551          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
552    
553          // cancel release process of voices on this key if needed          // cancel release process of voices on this key if needed
554          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !pEngineChannel->SustainPedal) {
555              RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();              RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
556              if (itCancelReleaseEvent) {              if (itCancelReleaseEvent) {
557                  *itCancelReleaseEvent = *itNoteOnEvent;                  // copy event                  *itCancelReleaseEvent = *itNoteOnEvent;                  // copy event
# Line 620  namespace LinuxSampler { namespace gig { Line 563  namespace LinuxSampler { namespace gig {
563          // move note on event to the key's own event list          // move note on event to the key's own event list
564          RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);          RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
565    
566          // allocate and trigger a new voice for the key          // allocate and trigger new voice(s) for the key
567          LaunchVoice(itNoteOnEventOnKeyList);          {
568                // first, get total amount of required voices (dependant on amount of layers)
569                ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOnEventOnKeyList->Param.Note.Key);
570                if (pRegion) {
571                    int voicesRequired = pRegion->Layers;
572                    // now launch the required amount of voices
573                    for (int i = 0; i < voicesRequired; i++)
574                        LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true);
575                }
576            }
577    
578            pKey->RoundRobinIndex++;
579      }      }
580    
581      /**      /**
# Line 630  namespace LinuxSampler { namespace gig { Line 584  namespace LinuxSampler { namespace gig {
584       *  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.
585       *  due to completion of sample playback).       *  due to completion of sample playback).
586       *       *
587         *  @param pEngineChannel - engine channel on which this event occured on
588       *  @param itNoteOffEvent - key, velocity and time stamp of the event       *  @param itNoteOffEvent - key, velocity and time stamp of the event
589       */       */
590      void Engine::ProcessNoteOff(Pool<Event>::Iterator& itNoteOffEvent) {      void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {
591          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];
592    
593          pKey->KeyPressed = false; // the MIDI key was now released          pKey->KeyPressed = false; // the MIDI key was now released
594    
595          // release voices on this key if needed          // release voices on this key if needed
596          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !pEngineChannel->SustainPedal) {
597              itNoteOffEvent->Type = Event::type_release; // transform event type              itNoteOffEvent->Type = Event::type_release; // transform event type
598          }          }
599    
# Line 647  namespace LinuxSampler { namespace gig { Line 602  namespace LinuxSampler { namespace gig {
602    
603          // spawn release triggered voice(s) if needed          // spawn release triggered voice(s) if needed
604          if (pKey->ReleaseTrigger) {          if (pKey->ReleaseTrigger) {
605              LaunchVoice(itNoteOffEventOnKeyList, 0, true);              // first, get total amount of required voices (dependant on amount of layers)
606                ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOffEventOnKeyList->Param.Note.Key);
607                if (pRegion) {
608                    int voicesRequired = pRegion->Layers;
609                    // now launch the required amount of voices
610                    for (int i = 0; i < voicesRequired; i++)
611                        LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, i, true, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
612                }
613              pKey->ReleaseTrigger = false;              pKey->ReleaseTrigger = false;
614          }          }
615      }      }
# Line 656  namespace LinuxSampler { namespace gig { Line 618  namespace LinuxSampler { namespace gig {
618       *  Moves pitchbend event from the general (input) event list to the pitch       *  Moves pitchbend event from the general (input) event list to the pitch
619       *  event list.       *  event list.
620       *       *
621         *  @param pEngineChannel - engine channel on which this event occured on
622       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event
623       */       */
624      void Engine::ProcessPitchbend(Pool<Event>::Iterator& itPitchbendEvent) {      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {
625          this->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value          pEngineChannel->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value
626          itPitchbendEvent.moveToEndOf(pSynthesisEvents[Event::destination_vco]);          itPitchbendEvent.moveToEndOf(pEngineChannel->pSynthesisEvents[Event::destination_vco]);
627      }      }
628    
629      /**      /**
# Line 668  namespace LinuxSampler { namespace gig { Line 631  namespace LinuxSampler { namespace gig {
631       *  called by the ProcessNoteOn() method and by the voices itself       *  called by the ProcessNoteOn() method and by the voices itself
632       *  (e.g. to spawn further voices on the same key for layered sounds).       *  (e.g. to spawn further voices on the same key for layered sounds).
633       *       *
634         *  @param pEngineChannel      - engine channel on which this event occured on
635       *  @param itNoteOnEvent       - key, velocity and time stamp of the event       *  @param itNoteOnEvent       - key, velocity and time stamp of the event
636       *  @param iLayer              - layer index for the new voice (optional - only       *  @param iLayer              - layer index for the new voice (optional - only
637       *                               in case of layered sounds of course)       *                               in case of layered sounds of course)
# Line 677  namespace LinuxSampler { namespace gig { Line 641  namespace LinuxSampler { namespace gig {
641       *                               when there is no free voice       *                               when there is no free voice
642       *                               (optional, default = true)       *                               (optional, default = true)
643       *  @returns pointer to new voice or NULL if there was no free voice or       *  @returns pointer to new voice or NULL if there was no free voice or
644       *           if an error occured while trying to trigger the new voice       *           if the voice wasn't triggered (for example when no region is
645         *           defined for the given key).
646       */       */
647      Pool<Voice>::Iterator Engine::LaunchVoice(Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing) {      Pool<Voice>::Iterator Engine::LaunchVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing) {
648          midi_key_info_t* pKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
649    
650          // allocate a new voice for the key          // allocate a new voice for the key
651          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
652          if (itNewVoice) {          if (itNewVoice) {
653              // launch the new voice              // launch the new voice
654              if (itNewVoice->Trigger(itNoteOnEvent, this->Pitch, this->pInstrument, iLayer, ReleaseTriggerVoice) < 0) {              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pEngineChannel->pInstrument, iLayer, ReleaseTriggerVoice, VoiceStealing) < 0) {
655                  dmsg(1,("Triggering new voice failed!\n"));                  dmsg(4,("Voice not triggered\n"));
656                  pKey->pActiveVoices->free(itNewVoice);                  pKey->pActiveVoices->free(itNewVoice);
657              }              }
658              else { // on success              else { // on success
659                  uint** ppKeyGroup = NULL;                  uint** ppKeyGroup = NULL;
660                  if (itNewVoice->KeyGroup) { // if this voice / key belongs to a key group                  if (itNewVoice->KeyGroup) { // if this voice / key belongs to a key group
661                      ppKeyGroup = &ActiveKeyGroups[itNewVoice->KeyGroup];                      ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup];
662                      if (*ppKeyGroup) { // if there's already an active key in that key group                      if (*ppKeyGroup) { // if there's already an active key in that key group
663                          midi_key_info_t* pOtherKey = &pMIDIKeyInfo[**ppKeyGroup];                          midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[**ppKeyGroup];
664                          // kill all voices on the (other) key                          // kill all voices on the (other) key
665                          RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();                          RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
666                          RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();                          RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
# Line 706  namespace LinuxSampler { namespace gig { Line 671  namespace LinuxSampler { namespace gig {
671                  }                  }
672                  if (!pKey->Active) { // mark as active key                  if (!pKey->Active) { // mark as active key
673                      pKey->Active = true;                      pKey->Active = true;
674                      pKey->itSelf = pActiveKeys->allocAppend();                      pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();
675                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
676                  }                  }
677                  if (itNewVoice->KeyGroup) {                  if (itNewVoice->KeyGroup) {
# Line 716  namespace LinuxSampler { namespace gig { Line 681  namespace LinuxSampler { namespace gig {
681                  return itNewVoice; // success                  return itNewVoice; // success
682              }              }
683          }          }
684          else if (VoiceStealing) StealVoice(itNoteOnEvent, iLayer, ReleaseTriggerVoice); // no free voice left, so steal one          else if (VoiceStealing) {
685    
686                // try to steal one voice
687                StealVoice(pEngineChannel, itNoteOnEvent);
688    
689                // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died
690                RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();
691                if (itStealEvent) {
692                    *itStealEvent = *itNoteOnEvent; // copy event
693                    itStealEvent->Param.Note.Layer = iLayer;
694                    itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;
695                }
696                else dmsg(1,("Voice stealing queue full!\n"));
697            }
698    
699          return Pool<Voice>::Iterator(); // no free voice or error          return Pool<Voice>::Iterator(); // no free voice or error
700      }      }
# Line 727  namespace LinuxSampler { namespace gig { Line 705  namespace LinuxSampler { namespace gig {
705       *  voice stealing and postpone the note-on event until the selected       *  voice stealing and postpone the note-on event until the selected
706       *  voice actually died.       *  voice actually died.
707       *       *
708       *  @param itNoteOnEvent       - key, velocity and time stamp of the event       *  @param pEngineChannel - engine channel on which this event occured on
709       *  @param iLayer              - layer index for the new voice       *  @param itNoteOnEvent - key, velocity and time stamp of the event
      *  @param ReleaseTriggerVoice - if new voice is a release triggered voice  
710       */       */
711      void Engine::StealVoice(Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice) {      void Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
712            if (!VoiceTheftsLeft) {
713                dmsg(1,("Max. voice thefts per audio fragment reached (you may raise MAX_AUDIO_VOICES).\n"));
714                return;
715            }
716          if (!pEventPool->poolIsEmpty()) {          if (!pEventPool->poolIsEmpty()) {
717    
718              RTList<uint>::Iterator  iuiOldestKey;              RTList<Voice>::Iterator itSelectedVoice;
             RTList<Voice>::Iterator itOldestVoice;  
719    
720              // Select one voice for voice stealing              // Select one voice for voice stealing
721              switch (VOICE_STEAL_ALGORITHM) {              switch (VOICE_STEAL_ALGORITHM) {
# Line 744  namespace LinuxSampler { namespace gig { Line 724  namespace LinuxSampler { namespace gig {
724                  // voice should be spawned, if there is no voice on that                  // voice should be spawned, if there is no voice on that
725                  // key, or no voice left to kill there, then procceed with                  // key, or no voice left to kill there, then procceed with
726                  // 'oldestkey' algorithm                  // 'oldestkey' algorithm
727                  case voice_steal_algo_keymask: {                  case voice_steal_algo_oldestvoiceonkey: {
728                      midi_key_info_t* pOldestKey = &pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];                  #if 0 // FIXME: broken
729                      if (itLastStolenVoice) {                      midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
730                          itOldestVoice = itLastStolenVoice;                      if (this->itLastStolenVoice) {
731                          ++itOldestVoice;                          itSelectedVoice = this->itLastStolenVoice;
732                            ++itSelectedVoice;
733                      }                      }
734                      else { // no voice stolen in this audio fragment cycle yet                      else { // no voice stolen in this audio fragment cycle yet
735                          itOldestVoice = pOldestKey->pActiveVoices->first();                          itSelectedVoice = pSelectedKey->pActiveVoices->first();
736                      }                      }
737                      if (itOldestVoice) {                      if (itSelectedVoice) {
738                          iuiOldestKey = pOldestKey->itSelf;                          iuiSelectedKey = pSelectedKey->itSelf;
739                          break; // selection succeeded                          break; // selection succeeded
740                      }                      }
741                    #endif
742                  } // no break - intentional !                  } // no break - intentional !
743    
744                  // try to pick the oldest voice on the oldest active key                  // try to pick the oldest voice on the oldest active key
745                  // (caution: must stay after 'keymask' algorithm !)                  // (caution: must stay after 'oldestvoiceonkey' algorithm !)
746                  case voice_steal_algo_oldestkey: {                  case voice_steal_algo_oldestkey: {
747                      if (itLastStolenVoice) {                      if (this->itLastStolenVoice) {
748                          midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiLastStolenKey];                          itSelectedVoice = this->itLastStolenVoice;
749                          itOldestVoice = itLastStolenVoice;                          ++itSelectedVoice;
750                          ++itOldestVoice;                          if (itSelectedVoice) break; // selection succeeded
751                          if (!itOldestVoice) {                          RTList<uint>::Iterator iuiSelectedKey = this->iuiLastStolenKey;
752                              iuiOldestKey = iuiLastStolenKey;                          ++iuiSelectedKey;
753                              ++iuiOldestKey;                          if (iuiSelectedKey) {
754                              if (iuiOldestKey) {                              this->iuiLastStolenKey = iuiSelectedKey;
755                                  midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiOldestKey];                              midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];
756                                  itOldestVoice = pOldestKey->pActiveVoices->first();                              itSelectedVoice = pSelectedKey->pActiveVoices->first();
757                              }                              break; // selection succeeded
                             else { // too less voices, even for voice stealing  
                                 dmsg(1,("Voice overflow! - You might recompile with higher MAX_AUDIO_VOICES!\n"));  
                                 return;  
                             }  
758                          }                          }
                         else iuiOldestKey = iuiLastStolenKey;  
                     }  
                     else { // no voice stolen in this audio fragment cycle yet  
                         iuiOldestKey = pActiveKeys->first();  
                         midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*iuiOldestKey];  
                         itOldestVoice = pOldestKey->pActiveVoices->first();  
759                      }                      }
760                      break;                      break;
761                  }                  }
# Line 796  namespace LinuxSampler { namespace gig { Line 768  namespace LinuxSampler { namespace gig {
768                  }                  }
769              }              }
770    
771              // now kill the selected voice              // steal oldest voice on the oldest key from this or any other engine channel
772              itOldestVoice->Kill(itNoteOnEvent);              if (!itSelectedVoice) {
773              // remember which voice on which key we stole, so we can simply proceed for the next voice stealing                  EngineChannel* pSelectedChannel = (pLastStolenChannel) ? pLastStolenChannel : pEngineChannel;
774              this->itLastStolenVoice = itOldestVoice;                  int iChannelIndex = pSelectedChannel->iEngineIndexSelf;
775              this->iuiLastStolenKey = iuiOldestKey;                  while (true) {
776              // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died                      RTList<uint>::Iterator iuiSelectedKey = pSelectedChannel->pActiveKeys->first();
777              RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();                      if (iuiSelectedKey) {
778              if (itStealEvent) {                          midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];
779                  *itStealEvent = *itNoteOnEvent; // copy event                          itSelectedVoice    = pSelectedKey->pActiveVoices->first();
780                  itStealEvent->Param.Note.Layer = iLayer;                          iuiLastStolenKey   = iuiSelectedKey;
781                  itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;                          pLastStolenChannel = pSelectedChannel;
782                            break; // selection succeeded
783                        }
784                        iChannelIndex    = (iChannelIndex + 1) % engineChannels.size();
785                        pSelectedChannel =  engineChannels[iChannelIndex];
786                    }
787              }              }
788              else dmsg(1,("Voice stealing queue full!\n"));  
789                //FIXME: can be removed, just a sanity check for debugging
790                if (!itSelectedVoice->IsActive()) dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
791    
792                // now kill the selected voice
793                itSelectedVoice->Kill(itNoteOnEvent);
794    
795                // remember which voice we stole, so we can simply proceed for the next voice stealing
796                itLastStolenVoice = itSelectedVoice;
797    
798                --VoiceTheftsLeft;
799          }          }
800          else dmsg(1,("Event pool emtpy!\n"));          else dmsg(1,("Event pool emtpy!\n"));
801      }      }
802    
803      /**      /**
804       *  Immediately kills the voice given with pVoice (no matter if sustain is       *  Removes the given voice from the MIDI key's list of active voices.
805       *  pressed or not) and removes it from the MIDI key's list of active voice.       *  This method will be called when a voice went inactive, e.g. because
806       *  This method will e.g. be called if a voice went inactive by itself.       *  it finished to playback its sample, finished its release stage or
807         *  just was killed.
808       *       *
809       *  @param itVoice - points to the voice to be killed       *  @param pEngineChannel - engine channel on which this event occured on
810         *  @param itVoice - points to the voice to be freed
811       */       */
812      void Engine::KillVoiceImmediately(Pool<Voice>::Iterator& itVoice) {      void Engine::FreeVoice(EngineChannel* pEngineChannel, Pool<Voice>::Iterator& itVoice) {
813          if (itVoice) {          if (itVoice) {
814              if (itVoice->IsActive()) itVoice->KillImmediately();              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itVoice->MIDIKey];
   
             midi_key_info_t* pKey = &pMIDIKeyInfo[itVoice->MIDIKey];  
815    
816              uint keygroup = itVoice->KeyGroup;              uint keygroup = itVoice->KeyGroup;
817    
818              // free the voice object              // free the voice object
819              pVoicePool->free(itVoice);              pVoicePool->free(itVoice);
820    
821              // 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
822              if (pKey->pActiveVoices->isEmpty()) {              if (pKey->pActiveVoices->isEmpty() && keygroup) {
823                  if (keygroup) { // if voice / key belongs to a key group                  uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[keygroup];
824                      uint** ppKeyGroup = &ActiveKeyGroups[keygroup];                  if (*ppKeyGroup == &*pKey->itSelf) *ppKeyGroup = NULL; // remove key from key group
                     if (*ppKeyGroup == &*pKey->itSelf) *ppKeyGroup = NULL; // remove key from key group  
                 }  
                 pKey->Active = false;  
                 pActiveKeys->free(pKey->itSelf); // remove key from list of active keys  
                 pKey->itSelf = RTList<uint>::Iterator();  
                 pKey->ReleaseTrigger = false;  
                 pKey->pEvents->clear();  
                 dmsg(3,("Key has no more voices now\n"));  
825              }              }
826          }          }
827          else std::cerr << "Couldn't release voice! (pVoice == NULL)\n" << std::flush;          else std::cerr << "Couldn't release voice! (!itVoice)\n" << std::flush;
828        }
829    
830        /**
831         *  Called when there's no more voice left on a key, this call will
832         *  update the key info respectively.
833         *
834         *  @param pEngineChannel - engine channel on which this event occured on
835         *  @param pKey - key which is now inactive
836         */
837        void Engine::FreeKey(EngineChannel* pEngineChannel, midi_key_info_t* pKey) {
838            if (pKey->pActiveVoices->isEmpty()) {
839                pKey->Active = false;
840                pEngineChannel->pActiveKeys->free(pKey->itSelf); // remove key from list of active keys
841                pKey->itSelf = RTList<uint>::Iterator();
842                pKey->ReleaseTrigger = false;
843                pKey->pEvents->clear();
844                dmsg(3,("Key has no more voices now\n"));
845            }
846            else dmsg(1,("gig::Engine: Oops, tried to free a key which contains voices.\n"));
847      }      }
848    
849      /**      /**
850       *  Reacts on supported control change commands (e.g. pitch bend wheel,       *  Reacts on supported control change commands (e.g. pitch bend wheel,
851       *  modulation wheel, aftertouch).       *  modulation wheel, aftertouch).
852       *       *
853         *  @param pEngineChannel - engine channel on which this event occured on
854       *  @param itControlChangeEvent - controller, value and time stamp of the event       *  @param itControlChangeEvent - controller, value and time stamp of the event
855       */       */
856      void Engine::ProcessControlChange(Pool<Event>::Iterator& itControlChangeEvent) {      void Engine::ProcessControlChange(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itControlChangeEvent) {
857          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", itControlChangeEvent->Param.CC.Controller, itControlChangeEvent->Param.CC.Value));          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", itControlChangeEvent->Param.CC.Controller, itControlChangeEvent->Param.CC.Value));
858    
859          switch (itControlChangeEvent->Param.CC.Controller) {          switch (itControlChangeEvent->Param.CC.Controller) {
860              case 64: {              case 7: { // volume
861                  if (itControlChangeEvent->Param.CC.Value >= 64 && !SustainPedal) {                  //TODO: not sample accurate yet
862                    pEngineChannel->GlobalVolume = (float) itControlChangeEvent->Param.CC.Value / 127.0f;
863                    break;
864                }
865                case 10: { // panpot
866                    //TODO: not sample accurate yet
867                    const int pan = (int) itControlChangeEvent->Param.CC.Value - 64;
868                    pEngineChannel->GlobalPanLeft  = 1.0f - float(RTMath::Max(pan, 0)) /  63.0f;
869                    pEngineChannel->GlobalPanRight = 1.0f - float(RTMath::Min(pan, 0)) / -64.0f;
870                    break;
871                }
872                case 64: { // sustain
873                    if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {
874                      dmsg(4,("PEDAL DOWN\n"));                      dmsg(4,("PEDAL DOWN\n"));
875                      SustainPedal = true;                      pEngineChannel->SustainPedal = true;
876    
877                      // cancel release process of voices if necessary                      // cancel release process of voices if necessary
878                      RTList<uint>::Iterator iuiKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
879                      if (iuiKey) {                      if (iuiKey) {
880                          itControlChangeEvent->Type = Event::type_cancel_release; // transform event type                          itControlChangeEvent->Type = Event::type_cancel_release; // transform event type
881                          while (iuiKey) {                          while (iuiKey) {
882                              midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];                              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
883                              ++iuiKey;                              ++iuiKey;
884                              if (!pKey->KeyPressed) {                              if (!pKey->KeyPressed) {
885                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
# Line 878  namespace LinuxSampler { namespace gig { Line 889  namespace LinuxSampler { namespace gig {
889                          }                          }
890                      }                      }
891                  }                  }
892                  if (itControlChangeEvent->Param.CC.Value < 64 && SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {
893                      dmsg(4,("PEDAL UP\n"));                      dmsg(4,("PEDAL UP\n"));
894                      SustainPedal = false;                      pEngineChannel->SustainPedal = false;
895    
896                      // release voices if their respective key is not pressed                      // release voices if their respective key is not pressed
897                      RTList<uint>::Iterator iuiKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
898                      if (iuiKey) {                      if (iuiKey) {
899                          itControlChangeEvent->Type = Event::type_release; // transform event type                          itControlChangeEvent->Type = Event::type_release; // transform event type
900                          while (iuiKey) {                          while (iuiKey) {
901                              midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];                              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
902                              ++iuiKey;                              ++iuiKey;
903                              if (!pKey->KeyPressed) {                              if (!pKey->KeyPressed) {
904                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
# Line 902  namespace LinuxSampler { namespace gig { Line 913  namespace LinuxSampler { namespace gig {
913          }          }
914    
915          // update controller value in the engine's controller table          // update controller value in the engine's controller table
916          ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;          pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
917    
918          // move event from the unsorted event list to the control change event list          // move event from the unsorted event list to the control change event list
919          itControlChangeEvent.moveToEndOf(pCCEvents);          itControlChangeEvent.moveToEndOf(pEngineChannel->pCCEvents);
920      }      }
921    
922      /**      /**
# Line 1006  namespace LinuxSampler { namespace gig { Line 1017  namespace LinuxSampler { namespace gig {
1017          }          }
1018      }      }
1019    
     float Engine::Volume() {  
         return GlobalVolume;  
     }  
   
     void Engine::Volume(float f) {  
         GlobalVolume = f;  
     }  
   
     uint Engine::Channels() {  
         return 2;  
     }  
   
     void Engine::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) {  
         AudioChannel* pChannel = pAudioOutputDevice->Channel(AudioDeviceChannel);  
         if (!pChannel) throw AudioOutputException("Invalid audio output device channel " + ToString(AudioDeviceChannel));  
         switch (EngineAudioChannel) {  
             case 0: // left output channel  
                 pOutputLeft = pChannel->Buffer();  
                 AudioDeviceChannelLeft = AudioDeviceChannel;  
                 break;  
             case 1: // right output channel  
                 pOutputRight = pChannel->Buffer();  
                 AudioDeviceChannelRight = AudioDeviceChannel;  
                 break;  
             default:  
                 throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));  
         }  
     }  
   
     int Engine::OutputChannel(uint EngineAudioChannel) {  
         switch (EngineAudioChannel) {  
             case 0: // left channel  
                 return AudioDeviceChannelLeft;  
             case 1: // right channel  
                 return AudioDeviceChannelRight;  
             default:  
                 throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));  
         }  
     }  
   
1020      uint Engine::VoiceCount() {      uint Engine::VoiceCount() {
1021          return ActiveVoiceCount;          return ActiveVoiceCount;
1022      }      }
# Line 1078  namespace LinuxSampler { namespace gig { Line 1049  namespace LinuxSampler { namespace gig {
1049          return "GigEngine";          return "GigEngine";
1050      }      }
1051    
     String Engine::InstrumentFileName() {  
         return InstrumentFile;  
     }  
   
     int Engine::InstrumentIndex() {  
         return InstrumentIdx;  
     }  
   
     int Engine::InstrumentStatus() {  
         return InstrumentStat;  
     }  
   
1052      String Engine::Description() {      String Engine::Description() {
1053          return "Gigasampler Engine";          return "Gigasampler Engine";
1054      }      }
1055    
1056      String Engine::Version() {      String Engine::Version() {
1057          String s = "$Revision: 1.15 $";          String s = "$Revision: 1.32 $";
1058          return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword          return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword
1059      }      }
1060    

Legend:
Removed from v.271  
changed lines
  Added in v.466

  ViewVC Help
Powered by ViewVC