/[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 424 by schoenebeck, Fri Mar 4 22:54:11 2005 UTC revision 831 by persson, Sat Jan 28 16:55:30 2006 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                              *   *   Copyright (C) 2005, 2006 Christian Schoenebeck                        *
7   *                                                                         *   *                                                                         *
8   *   This program is free software; you can redistribute it and/or modify  *   *   This program is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 29  Line 29 
29    
30  #include "Engine.h"  #include "Engine.h"
31    
 #if defined(__APPLE__)  
 # include <stdlib.h>  
 #else  
 # include <malloc.h>  
 #endif  
   
32  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
33    
34      InstrumentResourceManager Engine::instruments;      InstrumentResourceManager Engine::instruments;
# Line 56  namespace LinuxSampler { namespace gig { Line 50  namespace LinuxSampler { namespace gig {
50          // check if there's already an engine for the given audio output device          // check if there's already an engine for the given audio output device
51          if (engines.count(pDevice)) {          if (engines.count(pDevice)) {
52              dmsg(4,("Using existing gig::Engine.\n"));              dmsg(4,("Using existing gig::Engine.\n"));
53              pEngine = engines[pDevice];                          pEngine = engines[pDevice];
54          } else { // create a new engine (and disk thread) instance for the given audio output device          } else { // create a new engine (and disk thread) instance for the given audio output device
55              dmsg(4,("Creating new gig::Engine.\n"));              dmsg(4,("Creating new gig::Engine.\n"));
56              pEngine = (Engine*) EngineFactory::Create("gig");              pEngine = (Engine*) EngineFactory::Create("gig");
57              pEngine->Connect(pDevice);              pEngine->Connect(pDevice);
58              engines[pDevice] = pEngine;                          engines[pDevice] = pEngine;
59          }          }
60          // register engine channel to the engine instance          // register engine channel to the engine instance
61          pEngine->engineChannels.push_back(pChannel);          pEngine->engineChannels.add(pChannel);
62            // remember index in the ArrayList
63            pChannel->iEngineIndexSelf = pEngine->engineChannels.size() - 1;
64          dmsg(4,("This gig::Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));          dmsg(4,("This gig::Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));
65          return pEngine;          return pEngine;
66      }      }
# Line 94  namespace LinuxSampler { namespace gig { Line 90  namespace LinuxSampler { namespace gig {
90          else dmsg(4,("This gig::Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));          else dmsg(4,("This gig::Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));
91      }      }
92    
93        /**
94         * Constructor
95         */
96      Engine::Engine() {      Engine::Engine() {
97          pAudioOutputDevice = NULL;          pAudioOutputDevice = NULL;
98          pDiskThread        = NULL;          pDiskThread        = NULL;
99          pEventGenerator    = NULL;          pEventGenerator    = NULL;
100          pSysexBuffer       = new RingBuffer<uint8_t>(SYSEX_BUFFER_SIZE, 0);          pSysexBuffer       = new RingBuffer<uint8_t>(CONFIG_SYSEX_BUFFER_SIZE, 0);
101          pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT, 0);          pEventQueue        = new RingBuffer<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);
102          pEventPool         = new Pool<Event>(MAX_EVENTS_PER_FRAGMENT);          pEventPool         = new Pool<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT);
103          pVoicePool         = new Pool<Voice>(MAX_AUDIO_VOICES);                  pVoicePool         = new Pool<Voice>(CONFIG_MAX_VOICES);
104          pVoiceStealingQueue = new RTList<Event>(pEventPool);          pVoiceStealingQueue = new RTList<Event>(pEventPool);
105          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);  
         }  
106          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()) {
107              iterVoice->SetEngine(this);              iterVoice->SetEngine(this);
108          }          }
109          pVoicePool->clear();          pVoicePool->clear();
110    
         pSynthesisParameters[0] = NULL; // we allocate when an audio device is connected  
         pBasicFilterParameters  = NULL;  
         pMainFilterParameters   = NULL;  
   
111          ResetInternal();          ResetInternal();
112            ResetScaleTuning();
113      }      }
114    
115        /**
116         * Destructor
117         */
118      Engine::~Engine() {      Engine::~Engine() {
119          if (pDiskThread) {          if (pDiskThread) {
120              dmsg(1,("Stopping disk thread..."));              dmsg(1,("Stopping disk thread..."));
# Line 128  namespace LinuxSampler { namespace gig { Line 122  namespace LinuxSampler { namespace gig {
122              delete pDiskThread;              delete pDiskThread;
123              dmsg(1,("OK\n"));              dmsg(1,("OK\n"));
124          }          }
         for (uint i = 0; i < Event::destination_count; i++) {  
             if (pSynthesisEvents[i]) delete pSynthesisEvents[i];  
         }  
         if (pEvents)     delete pEvents;  
         if (pCCEvents)   delete pCCEvents;  
125          if (pEventQueue) delete pEventQueue;          if (pEventQueue) delete pEventQueue;
126          if (pEventPool)  delete pEventPool;          if (pEventPool)  delete pEventPool;
127          if (pVoicePool) {          if (pVoicePool) {
# Line 140  namespace LinuxSampler { namespace gig { Line 129  namespace LinuxSampler { namespace gig {
129              delete pVoicePool;              delete pVoicePool;
130          }          }
131          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
         if (pMainFilterParameters) delete[] pMainFilterParameters;  
         if (pBasicFilterParameters) delete[] pBasicFilterParameters;  
         if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);  
132          if (pVoiceStealingQueue) delete pVoiceStealingQueue;          if (pVoiceStealingQueue) delete pVoiceStealingQueue;
133          if (pSysexBuffer) delete pSysexBuffer;          if (pSysexBuffer) delete pSysexBuffer;
134          EngineFactory::Destroy(this);          EngineFactory::Destroy(this);
# Line 173  namespace LinuxSampler { namespace gig { Line 159  namespace LinuxSampler { namespace gig {
159      void Engine::Reset() {      void Engine::Reset() {
160          DisableAndLock();          DisableAndLock();
161          ResetInternal();          ResetInternal();
162            ResetScaleTuning();
163          Enable();          Enable();
164      }      }
165    
# Line 186  namespace LinuxSampler { namespace gig { Line 173  namespace LinuxSampler { namespace gig {
173    
174          // reset voice stealing parameters          // reset voice stealing parameters
175          pVoiceStealingQueue->clear();          pVoiceStealingQueue->clear();
176            itLastStolenVoice          = RTList<Voice>::Iterator();
177          // reset to normal chromatic scale (means equal temper)          itLastStolenVoiceGlobally  = RTList<Voice>::Iterator();
178          memset(&ScaleTuning[0], 0x00, 12);          iuiLastStolenKey           = RTList<uint>::Iterator();
179            iuiLastStolenKeyGlobally   = RTList<uint>::Iterator();
180            pLastStolenChannel         = NULL;
181    
182          // reset all voices          // reset all voices
183          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
# Line 201  namespace LinuxSampler { namespace gig { Line 190  namespace LinuxSampler { namespace gig {
190    
191          // delete all input events          // delete all input events
192          pEventQueue->init();          pEventQueue->init();
193      }              pSysexBuffer->init();
194        }
195    
196        /**
197         * Reset to normal, chromatic scale (means equal tempered).
198         */
199        void Engine::ResetScaleTuning() {
200            memset(&ScaleTuning[0], 0x00, 12);
201        }
202    
203        /**
204         * Connect this engine instance with the given audio output device.
205         * This method will be called when an Engine instance is created.
206         * All of the engine's data structures which are dependant to the used
207         * audio output device / driver will be (re)allocated and / or
208         * adjusted appropriately.
209         *
210         * @param pAudioOut - audio output device to connect to
211         */
212      void Engine::Connect(AudioOutputDevice* pAudioOut) {      void Engine::Connect(AudioOutputDevice* pAudioOut) {
213          pAudioOutputDevice = pAudioOut;          pAudioOutputDevice = pAudioOut;
214    
# Line 216  namespace LinuxSampler { namespace gig { Line 222  namespace LinuxSampler { namespace gig {
222              String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();              String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();
223              throw LinuxSamplerException(msg);              throw LinuxSamplerException(msg);
224          }          }
225            
226          this->MaxSamplesPerCycle      = pAudioOutputDevice->MaxSamplesPerCycle();          this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle();
227          this->SampleRate              = pAudioOutputDevice->SampleRate();          this->SampleRate         = pAudioOutputDevice->SampleRate();
228    
229          // FIXME: audio drivers with varying fragment sizes might be a problem here          // FIXME: audio drivers with varying fragment sizes might be a problem here
230          MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * EG_MIN_RELEASE_TIME) - 1;          MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * CONFIG_EG_MIN_RELEASE_TIME) - 1;
231          if (MaxFadeOutPos < 0)          if (MaxFadeOutPos < 0) {
232              throw LinuxSamplerException("EG_MIN_RELEASE_TIME in EGADSR.h too big for current audio fragment size / sampling rate!");              std::cerr << "gig::Engine: WARNING, CONFIG_EG_MIN_RELEASE_TIME "
233                          << "too big for current audio fragment size & sampling rate! "
234                          << "May lead to click sounds if voice stealing chimes in!\n" << std::flush;
235                // force volume ramp downs at the beginning of each fragment
236                MaxFadeOutPos = 0;
237                // lower minimum release time
238                const float minReleaseTime = (float) MaxSamplesPerCycle / (float) SampleRate;
239                for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
240                    iterVoice->EG1.CalculateFadeOutCoeff(minReleaseTime, SampleRate);
241                }
242                pVoicePool->clear();
243            }
244    
245          // (re)create disk thread          // (re)create disk thread
246          if (this->pDiskThread) {          if (this->pDiskThread) {
# Line 232  namespace LinuxSampler { namespace gig { Line 249  namespace LinuxSampler { namespace gig {
249              delete this->pDiskThread;              delete this->pDiskThread;
250              dmsg(1,("OK\n"));              dmsg(1,("OK\n"));
251          }          }
252          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
253          if (!pDiskThread) {          if (!pDiskThread) {
254              dmsg(0,("gig::Engine  new diskthread = NULL\n"));              dmsg(0,("gig::Engine  new diskthread = NULL\n"));
255              exit(EXIT_FAILURE);              exit(EXIT_FAILURE);
# Line 248  namespace LinuxSampler { namespace gig { Line 265  namespace LinuxSampler { namespace gig {
265          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
266          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
267    
         // (re)allocate synthesis parameter matrix  
         if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);  
   
         #if defined(__APPLE__)  
         pSynthesisParameters[0] = (float *) malloc(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle());  
         #else  
         pSynthesisParameters[0] = (float *) memalign(16,(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle()));  
         #endif  
         for (int dst = 1; dst < Event::destination_count; dst++)  
             pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();  
   
         // (re)allocate biquad filter parameter sequence  
         if (pBasicFilterParameters) delete[] pBasicFilterParameters;  
         if (pMainFilterParameters)  delete[] pMainFilterParameters;  
         pBasicFilterParameters = new biquad_param_t[pAudioOut->MaxSamplesPerCycle()];  
         pMainFilterParameters  = new biquad_param_t[pAudioOut->MaxSamplesPerCycle()];  
   
268          dmsg(1,("Starting disk thread..."));          dmsg(1,("Starting disk thread..."));
269          pDiskThread->StartThread();          pDiskThread->StartThread();
270          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
# Line 277  namespace LinuxSampler { namespace gig { Line 277  namespace LinuxSampler { namespace gig {
277          }          }
278      }      }
279    
280        /**
281         * Clear all engine global event lists.
282         */
283      void Engine::ClearEventLists() {      void Engine::ClearEventLists() {
284          pEvents->clear();          pGlobalEvents->clear();
         pCCEvents->clear();  
         for (uint i = 0; i < Event::destination_count; i++) {  
             pSynthesisEvents[i]->clear();  
         }  
285      }      }
286    
287      /**      /**
288       * Copy all events from the given input queue buffer to the engine's       * Copy all events from the engine's global input queue buffer to the
289       * internal event list. This will be done at the beginning of each audio       * engine's internal event list. This will be done at the beginning of
290       * cycle (that is each RenderAudio() call) to get all events which have       * each audio cycle (that is each RenderAudio() call) to distinguish
291       * to be processed in the current audio cycle. Each EngineChannel has       * all global events which have to be processed in the current audio
292       * it's own input event queue for the common channel specific events       * cycle. These events are usually just SysEx messages. Every
293       * (like NoteOn, NoteOff and ControlChange events). Beside that, the       * EngineChannel has it's own input event queue buffer and event list
294       * engine also has a input event queue for global events (usually SysEx       * to handle common events like NoteOn, NoteOff and ControlChange
295       * message).       * events.
296       *       *
297       * @param pEventQueue - input event buffer to read from       * @param Samples - number of sample points to be processed in the
298       * @param Samples     - number of sample points to be processed in the       *                  current audio cycle
      *                      current audio cycle  
299       */       */
300      void Engine::ImportEvents(RingBuffer<Event>* pEventQueue, uint Samples) {      void Engine::ImportEvents(uint Samples) {
301          RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();          RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
302          Event* pEvent;          Event* pEvent;
303          while (true) {          while (true) {
# Line 313  namespace LinuxSampler { namespace gig { Line 311  namespace LinuxSampler { namespace gig {
311                  break;                  break;
312              }              }
313              // copy event to internal event list              // copy event to internal event list
314              if (pEvents->poolIsEmpty()) {              if (pGlobalEvents->poolIsEmpty()) {
315                  dmsg(1,("Event pool emtpy!\n"));                  dmsg(1,("Event pool emtpy!\n"));
316                  break;                  break;
317              }              }
318              *pEvents->allocAppend() = *pEvent;              *pGlobalEvents->allocAppend() = *pEvent;
319          }          }
320          eventQueueReader.free(); // free all copied events from input queue          eventQueueReader.free(); // free all copied events from input queue
321      }          }
322    
323      /**      /**
324       *  Let this engine proceed to render the given amount of sample points. The       *  Let this engine proceed to render the given amount of sample points. The
# Line 344  namespace LinuxSampler { namespace gig { Line 342  namespace LinuxSampler { namespace gig {
342          // update time of start and end of this audio fragment (as events' time stamps relate to this)          // update time of start and end of this audio fragment (as events' time stamps relate to this)
343          pEventGenerator->UpdateFragmentTime(Samples);          pEventGenerator->UpdateFragmentTime(Samples);
344    
345          // empty the engine's event lists for the new fragment          // We only allow a maximum of CONFIG_MAX_VOICES voices to be spawned
346          ClearEventLists();          // in each audio fragment. All subsequent request for spawning new
347            // voices in the same audio fragment will be ignored.
348            VoiceSpawnsLeft = CONFIG_MAX_VOICES;
349    
350          // get all events from the engine's global input event queue which belong to the current fragment          // get all events from the engine's global input event queue which belong to the current fragment
351          // (these are usually just SysEx messages)          // (these are usually just SysEx messages)
352          ImportEvents(this->pEventQueue, Samples);          ImportEvents(Samples);
353    
354          // process engine global events (these are currently only MIDI System Exclusive messages)          // process engine global events (these are currently only MIDI System Exclusive messages)
355          {          {
356              RTList<Event>::Iterator itEvent = pEvents->first();              RTList<Event>::Iterator itEvent = pGlobalEvents->first();
357              RTList<Event>::Iterator end     = pEvents->end();              RTList<Event>::Iterator end     = pGlobalEvents->end();
358              for (; itEvent != end; ++itEvent) {              for (; itEvent != end; ++itEvent) {
359                  switch (itEvent->Type) {                  switch (itEvent->Type) {
360                      case Event::type_sysex:                      case Event::type_sysex:
# Line 368  namespace LinuxSampler { namespace gig { Line 368  namespace LinuxSampler { namespace gig {
368          // reset internal voice counter (just for statistic of active voices)          // reset internal voice counter (just for statistic of active voices)
369          ActiveVoiceCountTemp = 0;          ActiveVoiceCountTemp = 0;
370    
371          // render audio for all engine channels          // handle events on all engine channels
372          // TODO: should we make voice stealing engine globally? unfortunately this would mean other disadvantages so I left voice stealing in the engine channel space for now          for (int i = 0; i < engineChannels.size(); i++) {
373          {              if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
374              std::list<EngineChannel*>::iterator itChannel = engineChannels.begin();              ProcessEvents(engineChannels[i], Samples);
375              std::list<EngineChannel*>::iterator end       = engineChannels.end();          }
376              for (; itChannel != end; itChannel++) {  
377                  if (!(*itChannel)->pInstrument) continue; // ignore if no instrument loaded          // render all 'normal', active voices on all engine channels
378                  RenderAudio(*itChannel, Samples);          for (int i = 0; i < engineChannels.size(); i++) {
379              }              if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
380                RenderActiveVoices(engineChannels[i], Samples);
381            }
382    
383            // now that all ordinary voices on ALL engine channels are rendered, render new stolen voices
384            RenderStolenVoices(Samples);
385    
386            // handle cleanup on all engine channels for the next audio fragment
387            for (int i = 0; i < engineChannels.size(); i++) {
388                if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
389                PostProcess(engineChannels[i]);
390          }          }
391    
392    
393            // empty the engine's event list for the next audio fragment
394            ClearEventLists();
395    
396            // reset voice stealing for the next audio fragment
397            pVoiceStealingQueue->clear();
398    
399          // just some statistics about this engine instance          // just some statistics about this engine instance
400          ActiveVoiceCount = ActiveVoiceCountTemp;          ActiveVoiceCount = ActiveVoiceCountTemp;
401          if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;          if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;
402    
403            FrameTime += Samples;
404    
405          return 0;          return 0;
406      }      }
407    
408      void Engine::RenderAudio(EngineChannel* pEngineChannel, uint Samples) {      /**
409          // empty the engine's event lists for the new fragment       * Dispatch and handle all events in this audio fragment for the given
410          ClearEventLists();       * engine channel.
411          // empty the engine channel's, MIDI key specific event lists       *
412          {       * @param pEngineChannel - engine channel on which events should be
413              RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();       *                         processed
414              RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();       * @param Samples        - amount of sample points to be processed in
415              for(; iuiKey != end; ++iuiKey) {       *                         this audio fragment cycle
416                  pEngineChannel->pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key       */
417              }      void Engine::ProcessEvents(EngineChannel* pEngineChannel, uint Samples) {
         }  
   
   
418          // get all events from the engine channels's input event queue which belong to the current fragment          // get all events from the engine channels's input event queue which belong to the current fragment
419          // (these are the common events like NoteOn, NoteOff, ControlChange, etc.)          // (these are the common events like NoteOn, NoteOff, ControlChange, etc.)
420          ImportEvents(pEngineChannel->pEventQueue, Samples);                pEngineChannel->ImportEvents(Samples);
   
421    
422          // process events          // process events
423          {          {
424              RTList<Event>::Iterator itEvent = pEvents->first();              RTList<Event>::Iterator itEvent = pEngineChannel->pEvents->first();
425              RTList<Event>::Iterator end     = pEvents->end();              RTList<Event>::Iterator end     = pEngineChannel->pEvents->end();
426              for (; itEvent != end; ++itEvent) {              for (; itEvent != end; ++itEvent) {
427                  switch (itEvent->Type) {                  switch (itEvent->Type) {
428                      case Event::type_note_on:                      case Event::type_note_on:
# Line 430  namespace LinuxSampler { namespace gig { Line 445  namespace LinuxSampler { namespace gig {
445              }              }
446          }          }
447    
448            // reset voice stealing for the next engine channel (or next audio fragment)
449            itLastStolenVoice         = RTList<Voice>::Iterator();
450            itLastStolenVoiceGlobally = RTList<Voice>::Iterator();
451            iuiLastStolenKey          = RTList<uint>::Iterator();
452            iuiLastStolenKeyGlobally  = RTList<uint>::Iterator();
453            pLastStolenChannel        = NULL;
454        }
455    
456          // render audio from all active voices      /**
457          {       * Render all 'normal' voices (that is voices which were not stolen in
458              RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();       * this fragment) on the given engine channel.
459              RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();       *
460              while (iuiKey != end) { // iterate through all active keys       * @param pEngineChannel - engine channel on which audio should be
461                  midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];       *                         rendered
462                  ++iuiKey;       * @param Samples        - amount of sample points to be rendered in
463         *                         this audio fragment cycle
464         */
465        void Engine::RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {
466            #if !CONFIG_PROCESS_MUTED_CHANNELS
467            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
468            #endif
469    
470                  RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
471                  RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();          RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
472                  for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key          while (iuiKey != end) { // iterate through all active keys
473                      // now render current voice              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
474                      itVoice->Render(Samples);              ++iuiKey;
475                      if (itVoice->IsActive()) ActiveVoiceCountTemp++; // still active  
476                      else { // voice reached end, is now inactive              RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
477                          FreeVoice(pEngineChannel, itVoice); // remove voice from the list of active voices              RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
478                      }              for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
479                    // now render current voice
480                    itVoice->Render(Samples);
481                    if (itVoice->IsActive()) ActiveVoiceCountTemp++; // still active
482                    else { // voice reached end, is now inactive
483                        FreeVoice(pEngineChannel, itVoice); // remove voice from the list of active voices
484                  }                  }
485              }              }
486          }          }
487        }
488    
489                /**
490          // now render all postponed voices from voice stealing       * Render all stolen voices (only voices which were stolen in this
491          {       * fragment) on the given engine channel. Stolen voices are rendered
492              RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();       * after all normal voices have been rendered; this is needed to render
493              RTList<Event>::Iterator end               = pVoiceStealingQueue->end();       * audio of those voices which were selected for voice stealing until
494              for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {       * the point were the stealing (that is the take over of the voice)
495                  Pool<Voice>::Iterator itNewVoice =       * actually happened.
496                      LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false);       *
497                  if (itNewVoice) {       * @param pEngineChannel - engine channel on which audio should be
498                      for (; itNewVoice; itNewVoice = itNewVoice->itChildVoice) {       *                         rendered
499                          itNewVoice->Render(Samples);       * @param Samples        - amount of sample points to be rendered in
500                          if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active       *                         this audio fragment cycle
501                          else { // voice reached end, is now inactive       */
502                              FreeVoice(pEngineChannel, itNewVoice); // remove voice from the list of active voices      void Engine::RenderStolenVoices(uint Samples) {
503                          }          RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();
504                      }          RTList<Event>::Iterator end               = pVoiceStealingQueue->end();
505            for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
506                EngineChannel* pEngineChannel = (EngineChannel*) itVoiceStealEvent->pEngineChannel;
507                Pool<Voice>::Iterator itNewVoice =
508                    LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false, false);
509                if (itNewVoice) {
510                    itNewVoice->Render(Samples);
511                    if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active
512                    else { // voice reached end, is now inactive
513                        FreeVoice(pEngineChannel, itNewVoice); // remove voice from the list of active voices
514                  }                  }
                 else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));  
515              }              }
516                else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));
517    
518                // we need to clear the key's event list explicitly here in case key was never active
519                midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itVoiceStealEvent->Param.Note.Key];
520                pKey->VoiceTheftsQueued--;
521                if (!pKey->Active && !pKey->VoiceTheftsQueued) pKey->pEvents->clear();
522          }          }
523          // reset voice stealing for the new fragment      }
         pVoiceStealingQueue->clear();  
         pEngineChannel->itLastStolenVoice = RTList<Voice>::Iterator();  
         pEngineChannel->iuiLastStolenKey  = RTList<uint>::Iterator();  
           
524    
525        /**
526         * Free all keys which have turned inactive in this audio fragment, from
527         * the list of active keys and clear all event lists on that engine
528         * channel.
529         *
530         * @param pEngineChannel - engine channel to cleanup
531         */
532        void Engine::PostProcess(EngineChannel* pEngineChannel) {
533          // free all keys which have no active voices left          // free all keys which have no active voices left
534          {          {
535              RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();              RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
# Line 486  namespace LinuxSampler { namespace gig { Line 538  namespace LinuxSampler { namespace gig {
538                  midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];                  midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
539                  ++iuiKey;                  ++iuiKey;
540                  if (pKey->pActiveVoices->isEmpty()) FreeKey(pEngineChannel, pKey);                  if (pKey->pActiveVoices->isEmpty()) FreeKey(pEngineChannel, pKey);
541                  #if DEVMODE                  #if CONFIG_DEVMODE
542                  else { // FIXME: should be removed before the final release (purpose: just a sanity check for debugging)                  else { // just a sanity check for debugging
543                      RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();                      RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
544                      RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();                      RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
545                      for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key                      for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
# Line 496  namespace LinuxSampler { namespace gig { Line 548  namespace LinuxSampler { namespace gig {
548                          }                          }
549                      }                      }
550                  }                  }
551                  #endif // DEVMODE                  #endif // CONFIG_DEVMODE
552              }              }
553          }          }
554    
555            // empty the engine channel's own event lists
556            pEngineChannel->ClearEventLists();
557      }      }
558    
559      /**      /**
# Line 528  namespace LinuxSampler { namespace gig { Line 583  namespace LinuxSampler { namespace gig {
583                  // finally place sysex event into input event queue                  // finally place sysex event into input event queue
584                  pEventQueue->push(&event);                  pEventQueue->push(&event);
585              }              }
586              else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,SYSEX_BUFFER_SIZE));              else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,CONFIG_SYSEX_BUFFER_SIZE));
587          }          }
588          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
589      }      }
# Line 540  namespace LinuxSampler { namespace gig { Line 595  namespace LinuxSampler { namespace gig {
595       *  @param itNoteOnEvent - key, velocity and time stamp of the event       *  @param itNoteOnEvent - key, velocity and time stamp of the event
596       */       */
597      void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {      void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
598                    #if !CONFIG_PROCESS_MUTED_CHANNELS
599            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
600            #endif
601    
602          const int key = itNoteOnEvent->Param.Note.Key;          const int key = itNoteOnEvent->Param.Note.Key;
603            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];
604    
605            // move note on event to the key's own event list
606            RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
607    
608            // if Solo Mode then kill all already active voices
609            if (pEngineChannel->SoloMode) {
610                Pool<uint>::Iterator itYoungestKey = pEngineChannel->pActiveKeys->last();
611                if (itYoungestKey) {
612                    const int iYoungestKey = *itYoungestKey;
613                    const midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[iYoungestKey];
614                    if (pOtherKey->Active) {
615                        // get final portamento position of currently active voice
616                        if (pEngineChannel->PortamentoMode) {
617                            RTList<Voice>::Iterator itVoice = pOtherKey->pActiveVoices->last();
618                            if (itVoice) itVoice->UpdatePortamentoPos(itNoteOnEventOnKeyList);
619                        }
620                        // kill all voices on the (other) key
621                        RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
622                        RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
623                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
624                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger)
625                                itVoiceToBeKilled->Kill(itNoteOnEventOnKeyList);
626                        }
627                    }
628                }
629                // set this key as 'currently active solo key'
630                pEngineChannel->SoloKey = key;
631            }
632    
633          // Change key dimension value if key is in keyswitching area          // Change key dimension value if key is in keyswitching area
634          {          {
# Line 551  namespace LinuxSampler { namespace gig { Line 638  namespace LinuxSampler { namespace gig {
638                      (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);                      (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);
639          }          }
640    
         midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];  
   
641          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
642            pKey->Velocity   = itNoteOnEventOnKeyList->Param.Note.Velocity;
643            pKey->NoteOnTime = FrameTime + itNoteOnEventOnKeyList->FragmentPos(); // will be used to calculate note length
644    
645          // cancel release process of voices on this key if needed          // cancel release process of voices on this key if needed
646          if (pKey->Active && !pEngineChannel->SustainPedal) {          if (pKey->Active && !pEngineChannel->SustainPedal) {
647              RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();              RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
648              if (itCancelReleaseEvent) {              if (itCancelReleaseEvent) {
649                  *itCancelReleaseEvent = *itNoteOnEvent;                  // copy event                  *itCancelReleaseEvent = *itNoteOnEventOnKeyList;         // copy event
650                  itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type                  itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type
651              }              }
652              else dmsg(1,("Event pool emtpy!\n"));              else dmsg(1,("Event pool emtpy!\n"));
653          }          }
654    
655          // move note on event to the key's own event list          // allocate and trigger new voice(s) for the key
656          RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);          {
657                // first, get total amount of required voices (dependant on amount of layers)
658                ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOnEventOnKeyList->Param.Note.Key);
659                if (pRegion) {
660                    int voicesRequired = pRegion->Layers;
661                    // now launch the required amount of voices
662                    for (int i = 0; i < voicesRequired; i++)
663                        LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true, true);
664                }
665            }
666    
667          // allocate and trigger a new voice for the key          // if neither a voice was spawned or postponed then remove note on event from key again
668          LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, 0, false, true);          if (!pKey->Active && !pKey->VoiceTheftsQueued)
669                pKey->pEvents->free(itNoteOnEventOnKeyList);
670    
671            if (!pEngineChannel->SoloMode || pEngineChannel->PortamentoPos < 0.0f) pEngineChannel->PortamentoPos = (float) key;
672            pKey->RoundRobinIndex++;
673      }      }
674    
675      /**      /**
# Line 582  namespace LinuxSampler { namespace gig { Line 682  namespace LinuxSampler { namespace gig {
682       *  @param itNoteOffEvent - key, velocity and time stamp of the event       *  @param itNoteOffEvent - key, velocity and time stamp of the event
683       */       */
684      void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {      void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {
685          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];          #if !CONFIG_PROCESS_MUTED_CHANNELS
686            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
687            #endif
688    
689            const int iKey = itNoteOffEvent->Param.Note.Key;
690            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[iKey];
691          pKey->KeyPressed = false; // the MIDI key was now released          pKey->KeyPressed = false; // the MIDI key was now released
692    
         // release voices on this key if needed  
         if (pKey->Active && !pEngineChannel->SustainPedal) {  
             itNoteOffEvent->Type = Event::type_release; // transform event type  
         }  
   
693          // move event to the key's own event list          // move event to the key's own event list
694          RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);          RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
695    
696          // spawn release triggered voice(s) if needed          bool bShouldRelease = pKey->Active && ShouldReleaseVoice(pEngineChannel, itNoteOffEventOnKeyList->Param.Note.Key);
697          if (pKey->ReleaseTrigger) {  
698              LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, 0, true, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples          // in case Solo Mode is enabled, kill all voices on this key and respawn a voice on the highest pressed key (if any)
699              pKey->ReleaseTrigger = false;          if (pEngineChannel->SoloMode) { //TODO: this feels like too much code just for handling solo mode :P
700                bool bOtherKeysPressed = false;
701                if (iKey == pEngineChannel->SoloKey) {
702                    pEngineChannel->SoloKey = -1;
703                    // if there's still a key pressed down, respawn a voice (group) on the highest key
704                    for (int i = 127; i > 0; i--) {
705                        midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[i];
706                        if (pOtherKey->KeyPressed) {
707                            bOtherKeysPressed = true;
708                            // make the other key the new 'currently active solo key'
709                            pEngineChannel->SoloKey = i;
710                            // get final portamento position of currently active voice
711                            if (pEngineChannel->PortamentoMode) {
712                                RTList<Voice>::Iterator itVoice = pKey->pActiveVoices->first();
713                                if (itVoice) itVoice->UpdatePortamentoPos(itNoteOffEventOnKeyList);
714                            }
715                            // create a pseudo note on event
716                            RTList<Event>::Iterator itPseudoNoteOnEvent = pOtherKey->pEvents->allocAppend();
717                            if (itPseudoNoteOnEvent) {
718                                // copy event
719                                *itPseudoNoteOnEvent = *itNoteOffEventOnKeyList;
720                                // transform event to a note on event
721                                itPseudoNoteOnEvent->Type                = Event::type_note_on;
722                                itPseudoNoteOnEvent->Param.Note.Key      = i;
723                                itPseudoNoteOnEvent->Param.Note.Velocity = pOtherKey->Velocity;
724                                // allocate and trigger new voice(s) for the other key
725                                {
726                                    // first, get total amount of required voices (dependant on amount of layers)
727                                    ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(i);
728                                    if (pRegion) {
729                                        int voicesRequired = pRegion->Layers;
730                                        // now launch the required amount of voices
731                                        for (int iLayer = 0; iLayer < voicesRequired; iLayer++)
732                                            LaunchVoice(pEngineChannel, itPseudoNoteOnEvent, iLayer, false, true, false);
733                                    }
734                                }
735                                // if neither a voice was spawned or postponed then remove note on event from key again
736                                if (!pOtherKey->Active && !pOtherKey->VoiceTheftsQueued)
737                                    pOtherKey->pEvents->free(itPseudoNoteOnEvent);
738    
739                            } else dmsg(1,("Could not respawn voice, no free event left\n"));
740                            break; // done
741                        }
742                    }
743                }
744                if (bOtherKeysPressed) {
745                    if (pKey->Active) { // kill all voices on this key
746                        bShouldRelease = false; // no need to release, as we kill it here
747                        RTList<Voice>::Iterator itVoiceToBeKilled = pKey->pActiveVoices->first();
748                        RTList<Voice>::Iterator end               = pKey->pActiveVoices->end();
749                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
750                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger)
751                                itVoiceToBeKilled->Kill(itNoteOffEventOnKeyList);
752                        }
753                    }
754                } else pEngineChannel->PortamentoPos = -1.0f;
755          }          }
756    
757            // if no solo mode (the usual case) or if solo mode and no other key pressed, then release voices on this key if needed
758            if (bShouldRelease) {
759                itNoteOffEventOnKeyList->Type = Event::type_release; // transform event type
760    
761                // spawn release triggered voice(s) if needed
762                if (pKey->ReleaseTrigger) {
763                    // first, get total amount of required voices (dependant on amount of layers)
764                    ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOffEventOnKeyList->Param.Note.Key);
765                    if (pRegion) {
766                        int voicesRequired = pRegion->Layers;
767    
768                        // MIDI note-on velocity is used instead of note-off velocity
769                        itNoteOffEventOnKeyList->Param.Note.Velocity = pKey->Velocity;
770    
771                        // now launch the required amount of voices
772                        for (int i = 0; i < voicesRequired; i++)
773                            LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, i, true, false, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
774                    }
775                    pKey->ReleaseTrigger = false;
776                }
777            }
778    
779            // if neither a voice was spawned or postponed on this key then remove note off event from key again
780            if (!pKey->Active && !pKey->VoiceTheftsQueued)
781                pKey->pEvents->free(itNoteOffEventOnKeyList);
782      }      }
783    
784      /**      /**
785       *  Moves pitchbend event from the general (input) event list to the pitch       *  Moves pitchbend event from the general (input) event list to the engine
786       *  event list.       *  channel's event list. It will actually processed later by the
787         *  respective voice.
788       *       *
789       *  @param pEngineChannel - engine channel on which this event occured on       *  @param pEngineChannel - engine channel on which this event occured on
790       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event
791       */       */
792      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {
793          pEngineChannel->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value          pEngineChannel->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value
         itPitchbendEvent.moveToEndOf(pSynthesisEvents[Event::destination_vco]);  
794      }      }
795    
796      /**      /**
# Line 627  namespace LinuxSampler { namespace gig { Line 807  namespace LinuxSampler { namespace gig {
807       *  @param VoiceStealing       - if voice stealing should be performed       *  @param VoiceStealing       - if voice stealing should be performed
808       *                               when there is no free voice       *                               when there is no free voice
809       *                               (optional, default = true)       *                               (optional, default = true)
810         *  @param HandleKeyGroupConflicts - if voices should be killed due to a
811         *                                   key group conflict
812       *  @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
813       *           if the voice wasn't triggered (for example when no region is       *           if the voice wasn't triggered (for example when no region is
814       *           defined for the given key).       *           defined for the given key).
815       */       */
816      Pool<Voice>::Iterator Engine::LaunchVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing) {      Pool<Voice>::Iterator Engine::LaunchVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing, bool HandleKeyGroupConflicts) {
817          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];          int MIDIKey            = itNoteOnEvent->Param.Note.Key;
818            midi_key_info_t* pKey  = &pEngineChannel->pMIDIKeyInfo[MIDIKey];
819            ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(MIDIKey);
820    
821            // if nothing defined for this key
822            if (!pRegion) return Pool<Voice>::Iterator(); // nothing to do
823    
824            // only mark the first voice of a layered voice (group) to be in a
825            // key group, so the layered voices won't kill each other
826            int iKeyGroup = (iLayer == 0 && !ReleaseTriggerVoice) ? pRegion->KeyGroup : 0;
827    
828            // handle key group (a.k.a. exclusive group) conflicts
829            if (HandleKeyGroupConflicts) {
830                if (iKeyGroup) { // if this voice / key belongs to a key group
831                    uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[iKeyGroup];
832                    if (*ppKeyGroup) { // if there's already an active key in that key group
833                        midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[**ppKeyGroup];
834                        // kill all voices on the (other) key
835                        RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
836                        RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
837                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
838                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger) {
839                                itVoiceToBeKilled->Kill(itNoteOnEvent);
840                                --VoiceSpawnsLeft; //FIXME: just a hack, we should better check in StealVoice() if the voice was killed due to key conflict
841                            }
842                        }
843                    }
844                }
845            }
846    
847            Voice::type_t VoiceType = Voice::type_normal;
848    
849            // get current dimension values to select the right dimension region
850            //TODO: for stolen voices this dimension region selection block is processed twice, this should be changed
851            //FIXME: controller values for selecting the dimension region here are currently not sample accurate
852            uint DimValues[8] = { 0 };
853            for (int i = pRegion->Dimensions - 1; i >= 0; i--) {
854                switch (pRegion->pDimensionDefinitions[i].dimension) {
855                    case ::gig::dimension_samplechannel:
856                        DimValues[i] = 0; //TODO: we currently ignore this dimension
857                        break;
858                    case ::gig::dimension_layer:
859                        DimValues[i] = iLayer;
860                        break;
861                    case ::gig::dimension_velocity:
862                        DimValues[i] = itNoteOnEvent->Param.Note.Velocity;
863                        break;
864                    case ::gig::dimension_channelaftertouch:
865                        DimValues[i] = 0; //TODO: we currently ignore this dimension
866                        break;
867                    case ::gig::dimension_releasetrigger:
868                        VoiceType = (ReleaseTriggerVoice) ? Voice::type_release_trigger : (!iLayer) ? Voice::type_release_trigger_required : Voice::type_normal;
869                        DimValues[i] = (uint) ReleaseTriggerVoice;
870                        break;
871                    case ::gig::dimension_keyboard:
872                        DimValues[i] = (uint) pEngineChannel->CurrentKeyDimension;
873                        break;
874                    case ::gig::dimension_roundrobin:
875                        DimValues[i] = (uint) pEngineChannel->pMIDIKeyInfo[MIDIKey].RoundRobinIndex; // incremented for each note on
876                        break;
877                    case ::gig::dimension_random:
878                        RandomSeed   = RandomSeed * 1103515245 + 12345; // classic pseudo random number generator
879                        DimValues[i] = (uint) RandomSeed >> (32 - pRegion->pDimensionDefinitions[i].bits); // highest bits are most random
880                        break;
881                    case ::gig::dimension_modwheel:
882                        DimValues[i] = pEngineChannel->ControllerTable[1];
883                        break;
884                    case ::gig::dimension_breath:
885                        DimValues[i] = pEngineChannel->ControllerTable[2];
886                        break;
887                    case ::gig::dimension_foot:
888                        DimValues[i] = pEngineChannel->ControllerTable[4];
889                        break;
890                    case ::gig::dimension_portamentotime:
891                        DimValues[i] = pEngineChannel->ControllerTable[5];
892                        break;
893                    case ::gig::dimension_effect1:
894                        DimValues[i] = pEngineChannel->ControllerTable[12];
895                        break;
896                    case ::gig::dimension_effect2:
897                        DimValues[i] = pEngineChannel->ControllerTable[13];
898                        break;
899                    case ::gig::dimension_genpurpose1:
900                        DimValues[i] = pEngineChannel->ControllerTable[16];
901                        break;
902                    case ::gig::dimension_genpurpose2:
903                        DimValues[i] = pEngineChannel->ControllerTable[17];
904                        break;
905                    case ::gig::dimension_genpurpose3:
906                        DimValues[i] = pEngineChannel->ControllerTable[18];
907                        break;
908                    case ::gig::dimension_genpurpose4:
909                        DimValues[i] = pEngineChannel->ControllerTable[19];
910                        break;
911                    case ::gig::dimension_sustainpedal:
912                        DimValues[i] = pEngineChannel->ControllerTable[64];
913                        break;
914                    case ::gig::dimension_portamento:
915                        DimValues[i] = pEngineChannel->ControllerTable[65];
916                        break;
917                    case ::gig::dimension_sostenutopedal:
918                        DimValues[i] = pEngineChannel->ControllerTable[66];
919                        break;
920                    case ::gig::dimension_softpedal:
921                        DimValues[i] = pEngineChannel->ControllerTable[67];
922                        break;
923                    case ::gig::dimension_genpurpose5:
924                        DimValues[i] = pEngineChannel->ControllerTable[80];
925                        break;
926                    case ::gig::dimension_genpurpose6:
927                        DimValues[i] = pEngineChannel->ControllerTable[81];
928                        break;
929                    case ::gig::dimension_genpurpose7:
930                        DimValues[i] = pEngineChannel->ControllerTable[82];
931                        break;
932                    case ::gig::dimension_genpurpose8:
933                        DimValues[i] = pEngineChannel->ControllerTable[83];
934                        break;
935                    case ::gig::dimension_effect1depth:
936                        DimValues[i] = pEngineChannel->ControllerTable[91];
937                        break;
938                    case ::gig::dimension_effect2depth:
939                        DimValues[i] = pEngineChannel->ControllerTable[92];
940                        break;
941                    case ::gig::dimension_effect3depth:
942                        DimValues[i] = pEngineChannel->ControllerTable[93];
943                        break;
944                    case ::gig::dimension_effect4depth:
945                        DimValues[i] = pEngineChannel->ControllerTable[94];
946                        break;
947                    case ::gig::dimension_effect5depth:
948                        DimValues[i] = pEngineChannel->ControllerTable[95];
949                        break;
950                    case ::gig::dimension_none:
951                        std::cerr << "gig::Engine::LaunchVoice() Error: dimension=none\n" << std::flush;
952                        break;
953                    default:
954                        std::cerr << "gig::Engine::LaunchVoice() Error: Unknown dimension\n" << std::flush;
955                }
956            }
957            ::gig::DimensionRegion* pDimRgn = pRegion->GetDimensionRegionByValue(DimValues);
958    
959            // no need to continue if sample is silent
960            if (!pDimRgn->pSample || !pDimRgn->pSample->SamplesTotal) return Pool<Voice>::Iterator();
961    
962          // allocate a new voice for the key          // allocate a new voice for the key
963          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
964          if (itNewVoice) {          if (itNewVoice) {
965              // launch the new voice              // launch the new voice
966              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pEngineChannel->pInstrument, iLayer, ReleaseTriggerVoice, VoiceStealing) < 0) {              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pDimRgn, VoiceType, iKeyGroup) < 0) {
967                  dmsg(4,("Voice not triggered\n"));                  dmsg(4,("Voice not triggered\n"));
968                  pKey->pActiveVoices->free(itNewVoice);                  pKey->pActiveVoices->free(itNewVoice);
969              }              }
970              else { // on success              else { // on success
971                  uint** ppKeyGroup = NULL;                  --VoiceSpawnsLeft;
                 if (itNewVoice->KeyGroup) { // if this voice / key belongs to a key group  
                     ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup];  
                     if (*ppKeyGroup) { // if there's already an active key in that key group  
                         midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[**ppKeyGroup];  
                         // kill all voices on the (other) key  
                         RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();  
                         RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();  
                         for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {  
                             if (itVoiceToBeKilled->Type != Voice::type_release_trigger) itVoiceToBeKilled->Kill(itNoteOnEvent);  
                         }  
                     }  
                 }  
972                  if (!pKey->Active) { // mark as active key                  if (!pKey->Active) { // mark as active key
973                      pKey->Active = true;                      pKey->Active = true;
974                      pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();                      pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();
975                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
976                  }                  }
977                  if (itNewVoice->KeyGroup) {                  if (itNewVoice->KeyGroup) {
978                        uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup];
979                      *ppKeyGroup = &*pKey->itSelf; // put key as the (new) active key to its key group                      *ppKeyGroup = &*pKey->itSelf; // put key as the (new) active key to its key group
980                  }                  }
981                  if (itNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)                  if (itNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)
# Line 669  namespace LinuxSampler { namespace gig { Line 983  namespace LinuxSampler { namespace gig {
983              }              }
984          }          }
985          else if (VoiceStealing) {          else if (VoiceStealing) {
986              // first, get total amount of required voices (dependant on amount of layers)              // try to steal one voice
987              ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOnEvent->Param.Note.Key);              int result = StealVoice(pEngineChannel, itNoteOnEvent);
988              if (!pRegion) return Pool<Voice>::Iterator(); // nothing defined for this MIDI key, so no voice needed              if (!result) { // voice stolen successfully
989              int voicesRequired = pRegion->Layers;                  // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died
990                    RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();
991              // now steal the (remaining) amount of voices                  if (itStealEvent) {
992              for (int i = iLayer; i < voicesRequired; i++)                      *itStealEvent = *itNoteOnEvent; // copy event
993                  StealVoice(pEngineChannel, itNoteOnEvent);                      itStealEvent->Param.Note.Layer = iLayer;
994                        itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;
995              // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died                      pKey->VoiceTheftsQueued++;
996              RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();                  }
997              if (itStealEvent) {                  else dmsg(1,("Voice stealing queue full!\n"));
                 *itStealEvent = *itNoteOnEvent; // copy event  
                 itStealEvent->Param.Note.Layer = iLayer;  
                 itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;  
998              }              }
             else dmsg(1,("Voice stealing queue full!\n"));  
999          }          }
1000    
1001          return Pool<Voice>::Iterator(); // no free voice or error          return Pool<Voice>::Iterator(); // no free voice or error
# Line 699  namespace LinuxSampler { namespace gig { Line 1009  namespace LinuxSampler { namespace gig {
1009       *       *
1010       *  @param pEngineChannel - engine channel on which this event occured on       *  @param pEngineChannel - engine channel on which this event occured on
1011       *  @param itNoteOnEvent - key, velocity and time stamp of the event       *  @param itNoteOnEvent - key, velocity and time stamp of the event
1012         *  @returns 0 on success, a value < 0 if no active voice could be picked for voice stealing
1013       */       */
1014      void Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {      int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
1015            if (VoiceSpawnsLeft <= 0) {
1016                dmsg(1,("Max. voice thefts per audio fragment reached (you may raise CONFIG_MAX_VOICES).\n"));
1017                return -1;
1018            }
1019          if (!pEventPool->poolIsEmpty()) {          if (!pEventPool->poolIsEmpty()) {
1020    
1021              RTList<uint>::Iterator  iuiOldestKey;              RTList<Voice>::Iterator itSelectedVoice;
             RTList<Voice>::Iterator itOldestVoice;  
1022    
1023              // Select one voice for voice stealing              // Select one voice for voice stealing
1024              switch (VOICE_STEAL_ALGORITHM) {              switch (CONFIG_VOICE_STEAL_ALGO) {
1025    
1026                  // try to pick the oldest voice on the key where the new                  // try to pick the oldest voice on the key where the new
1027                  // voice should be spawned, if there is no voice on that                  // voice should be spawned, if there is no voice on that
1028                  // key, or no voice left to kill there, then procceed with                  // key, or no voice left to kill, then procceed with
1029                  // 'oldestkey' algorithm                  // 'oldestkey' algorithm
1030                  case voice_steal_algo_keymask: {                  case voice_steal_algo_oldestvoiceonkey: {
1031                      midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];                      midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
1032                      if (pEngineChannel->itLastStolenVoice) {                      itSelectedVoice = pSelectedKey->pActiveVoices->first();
1033                          itOldestVoice = pEngineChannel->itLastStolenVoice;                      // proceed iterating if voice was created in this fragment cycle
1034                          ++itOldestVoice;                      while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1035                      }                      // if we haven't found a voice then proceed with algorithm 'oldestkey'
1036                      else { // no voice stolen in this audio fragment cycle yet                      if (itSelectedVoice && itSelectedVoice->IsStealable()) break;
                         itOldestVoice = pOldestKey->pActiveVoices->first();  
                     }  
                     if (itOldestVoice) {  
                         iuiOldestKey = pOldestKey->itSelf;  
                         break; // selection succeeded  
                     }  
1037                  } // no break - intentional !                  } // no break - intentional !
1038    
1039                  // try to pick the oldest voice on the oldest active key                  // try to pick the oldest voice on the oldest active key
1040                  // (caution: must stay after 'keymask' algorithm !)                  // from the same engine channel
1041                    // (caution: must stay after 'oldestvoiceonkey' algorithm !)
1042                  case voice_steal_algo_oldestkey: {                  case voice_steal_algo_oldestkey: {
1043                      if (pEngineChannel->itLastStolenVoice) {                      // if we already stole in this fragment, try to proceed on same key
1044                          midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[*pEngineChannel->iuiLastStolenKey];                      if (this->itLastStolenVoice) {
1045                          itOldestVoice = pEngineChannel->itLastStolenVoice;                          itSelectedVoice = this->itLastStolenVoice;
1046                          ++itOldestVoice;                          do {
1047                          if (!itOldestVoice) {                              ++itSelectedVoice;
1048                              iuiOldestKey = pEngineChannel->iuiLastStolenKey;                          } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1049                              ++iuiOldestKey;                          // found a "stealable" voice ?
1050                              if (iuiOldestKey) {                          if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1051                                  midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[*iuiOldestKey];                              // remember which voice we stole, so we can simply proceed on next voice stealing
1052                                  itOldestVoice = pOldestKey->pActiveVoices->first();                              this->itLastStolenVoice = itSelectedVoice;
1053                              }                              break; // selection succeeded
                             else {  
                                 dmsg(1,("gig::Engine: Warning, too less voices, even for voice stealing! - Better recompile with higher MAX_AUDIO_VOICES.\n"));  
                                 return;  
                             }  
1054                          }                          }
                         else iuiOldestKey = pEngineChannel->iuiLastStolenKey;  
1055                      }                      }
1056                      else { // no voice stolen in this audio fragment cycle yet                      // get (next) oldest key
1057                          iuiOldestKey = pEngineChannel->pActiveKeys->first();                      RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKey) ? ++this->iuiLastStolenKey : pEngineChannel->pActiveKeys->first();
1058                          midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[*iuiOldestKey];                      while (iuiSelectedKey) {
1059                          itOldestVoice = pOldestKey->pActiveVoices->first();                          midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];
1060                            itSelectedVoice = pSelectedKey->pActiveVoices->first();
1061                            // proceed iterating if voice was created in this fragment cycle
1062                            while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1063                            // found a "stealable" voice ?
1064                            if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1065                                // remember which voice on which key we stole, so we can simply proceed on next voice stealing
1066                                this->iuiLastStolenKey  = iuiSelectedKey;
1067                                this->itLastStolenVoice = itSelectedVoice;
1068                                break; // selection succeeded
1069                            }
1070                            ++iuiSelectedKey; // get next oldest key
1071                      }                      }
1072                      break;                      break;
1073                  }                  }
# Line 761  namespace LinuxSampler { namespace gig { Line 1076  namespace LinuxSampler { namespace gig {
1076                  case voice_steal_algo_none:                  case voice_steal_algo_none:
1077                  default: {                  default: {
1078                      dmsg(1,("No free voice (voice stealing disabled)!\n"));                      dmsg(1,("No free voice (voice stealing disabled)!\n"));
1079                      return;                      return -1;
1080                  }                  }
1081              }              }
1082    
1083              //FIXME: can be removed, just a sanity check for debugging              // if we couldn't steal a voice from the same engine channel then
1084              if (!itOldestVoice->IsActive()) dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));              // steal oldest voice on the oldest key from any other engine channel
1085                // (the smaller engine channel number, the higher priority)
1086                if (!itSelectedVoice || !itSelectedVoice->IsStealable()) {
1087                    EngineChannel* pSelectedChannel;
1088                    int            iChannelIndex;
1089                    // select engine channel
1090                    if (pLastStolenChannel) {
1091                        pSelectedChannel = pLastStolenChannel;
1092                        iChannelIndex    = pSelectedChannel->iEngineIndexSelf;
1093                    } else { // pick the engine channel followed by this engine channel
1094                        iChannelIndex    = (pEngineChannel->iEngineIndexSelf + 1) % engineChannels.size();
1095                        pSelectedChannel = engineChannels[iChannelIndex];
1096                    }
1097    
1098                    // if we already stole in this fragment, try to proceed on same key
1099                    if (this->itLastStolenVoiceGlobally) {
1100                        itSelectedVoice = this->itLastStolenVoiceGlobally;
1101                        do {
1102                            ++itSelectedVoice;
1103                        } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1104                    }
1105    
1106                    #if CONFIG_DEVMODE
1107                    EngineChannel* pBegin = pSelectedChannel; // to detect endless loop
1108                    #endif // CONFIG_DEVMODE
1109    
1110                    // did we find a 'stealable' voice?
1111                    if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1112                        // remember which voice we stole, so we can simply proceed on next voice stealing
1113                        this->itLastStolenVoiceGlobally = itSelectedVoice;
1114                    } else while (true) { // iterate through engine channels
1115                        // get (next) oldest key
1116                        RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKeyGlobally) ? ++this->iuiLastStolenKeyGlobally : pSelectedChannel->pActiveKeys->first();
1117                        this->iuiLastStolenKeyGlobally = RTList<uint>::Iterator(); // to prevent endless loop (see line above)
1118                        while (iuiSelectedKey) {
1119                            midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];
1120                            itSelectedVoice = pSelectedKey->pActiveVoices->first();
1121                            // proceed iterating if voice was created in this fragment cycle
1122                            while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1123                            // found a "stealable" voice ?
1124                            if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1125                                // remember which voice on which key on which engine channel we stole, so we can simply proceed on next voice stealing
1126                                this->iuiLastStolenKeyGlobally  = iuiSelectedKey;
1127                                this->itLastStolenVoiceGlobally = itSelectedVoice;
1128                                this->pLastStolenChannel        = pSelectedChannel;
1129                                goto stealable_voice_found; // selection succeeded
1130                            }
1131                            ++iuiSelectedKey; // get next key on current engine channel
1132                        }
1133                        // get next engine channel
1134                        iChannelIndex    = (iChannelIndex + 1) % engineChannels.size();
1135                        pSelectedChannel = engineChannels[iChannelIndex];
1136    
1137                        #if CONFIG_DEVMODE
1138                        if (pSelectedChannel == pBegin) {
1139                            dmsg(1,("FATAL ERROR: voice stealing endless loop!\n"));
1140                            dmsg(1,("VoiceSpawnsLeft=%d.\n", VoiceSpawnsLeft));
1141                            dmsg(1,("Exiting.\n"));
1142                            exit(-1);
1143                        }
1144                        #endif // CONFIG_DEVMODE
1145                    }
1146                }
1147    
1148                // jump point if a 'stealable' voice was found
1149                stealable_voice_found:
1150    
1151                #if CONFIG_DEVMODE
1152                if (!itSelectedVoice->IsActive()) {
1153                    dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
1154                    return -1;
1155                }
1156                #endif // CONFIG_DEVMODE
1157    
1158              // now kill the selected voice              // now kill the selected voice
1159              itOldestVoice->Kill(itNoteOnEvent);              itSelectedVoice->Kill(itNoteOnEvent);
1160              // remember which voice on which key we stole, so we can simply proceed for the next voice stealing  
1161              pEngineChannel->itLastStolenVoice = itOldestVoice;              --VoiceSpawnsLeft;
1162              pEngineChannel->iuiLastStolenKey = iuiOldestKey;  
1163                return 0; // success
1164            }
1165            else {
1166                dmsg(1,("Event pool emtpy!\n"));
1167                return -1;
1168          }          }
         else dmsg(1,("Event pool emtpy!\n"));  
1169      }      }
1170    
1171      /**      /**
# Line 833  namespace LinuxSampler { namespace gig { Line 1224  namespace LinuxSampler { namespace gig {
1224      void Engine::ProcessControlChange(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itControlChangeEvent) {      void Engine::ProcessControlChange(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itControlChangeEvent) {
1225          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));
1226    
1227            // update controller value in the engine channel's controller table
1228            pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
1229    
1230          switch (itControlChangeEvent->Param.CC.Controller) {          switch (itControlChangeEvent->Param.CC.Controller) {
1231                case 5: { // portamento time
1232                    pEngineChannel->PortamentoTime = (float) itControlChangeEvent->Param.CC.Value / 127.0f * (float) CONFIG_PORTAMENTO_TIME_MAX + (float) CONFIG_PORTAMENTO_TIME_MIN;
1233                    break;
1234                }
1235              case 7: { // volume              case 7: { // volume
1236                  //TODO: not sample accurate yet                  //TODO: not sample accurate yet
1237                  pEngineChannel->GlobalVolume = (float) itControlChangeEvent->Param.CC.Value / 127.0f;                  pEngineChannel->GlobalVolume = VolumeCurve[itControlChangeEvent->Param.CC.Value] *  CONFIG_GLOBAL_ATTENUATION;
1238                    pEngineChannel->bStatusChanged = true; // engine channel status has changed, so set notify flag
1239                  break;                  break;
1240              }              }
1241              case 10: { // panpot              case 10: { // panpot
1242                  //TODO: not sample accurate yet                  //TODO: not sample accurate yet
1243                  const int pan = (int) itControlChangeEvent->Param.CC.Value - 64;                  pEngineChannel->GlobalPanLeft  = PanCurve[128 - itControlChangeEvent->Param.CC.Value];
1244                  pEngineChannel->GlobalPanLeft  = 1.0f - float(RTMath::Max(pan, 0)) /  63.0f;                  pEngineChannel->GlobalPanRight = PanCurve[itControlChangeEvent->Param.CC.Value];
                 pEngineChannel->GlobalPanRight = 1.0f - float(RTMath::Min(pan, 0)) / -64.0f;  
1245                  break;                  break;
1246              }              }
1247              case 64: { // sustain              case 64: { // sustain
1248                  if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {
1249                      dmsg(4,("PEDAL DOWN\n"));                      dmsg(4,("DAMPER (RIGHT) PEDAL DOWN\n"));
1250                      pEngineChannel->SustainPedal = true;                      pEngineChannel->SustainPedal = true;
1251    
1252                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1253                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1254                        #endif
1255    
1256                      // cancel release process of voices if necessary                      // cancel release process of voices if necessary
1257                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1258                      if (iuiKey) {                      for (; iuiKey; ++iuiKey) {
1259                          itControlChangeEvent->Type = Event::type_cancel_release; // transform event type                          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1260                          while (iuiKey) {                          if (!pKey->KeyPressed) {
1261                              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1262                              ++iuiKey;                              if (itNewEvent) {
1263                              if (!pKey->KeyPressed) {                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1264                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();                                  itNewEvent->Type = Event::type_cancel_release; // transform event type
                                 if (itNewEvent) *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list  
                                 else dmsg(1,("Event pool emtpy!\n"));  
1265                              }                              }
1266                                else dmsg(1,("Event pool emtpy!\n"));
1267                          }                          }
1268                      }                      }
1269                  }                  }
1270                  if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {
1271                      dmsg(4,("PEDAL UP\n"));                      dmsg(4,("DAMPER (RIGHT) PEDAL UP\n"));
1272                      pEngineChannel->SustainPedal = false;                      pEngineChannel->SustainPedal = false;
1273    
1274                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1275                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1276                        #endif
1277    
1278                      // release voices if their respective key is not pressed                      // release voices if their respective key is not pressed
1279                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1280                      if (iuiKey) {                      for (; iuiKey; ++iuiKey) {
1281                          itControlChangeEvent->Type = Event::type_release; // transform event type                          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1282                          while (iuiKey) {                          if (!pKey->KeyPressed && ShouldReleaseVoice(pEngineChannel, *iuiKey)) {
1283                              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1284                              ++iuiKey;                              if (itNewEvent) {
1285                              if (!pKey->KeyPressed) {                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1286                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();                                  itNewEvent->Type = Event::type_release; // transform event type
                                 if (itNewEvent) *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list  
                                 else dmsg(1,("Event pool emtpy!\n"));  
1287                              }                              }
1288                                else dmsg(1,("Event pool emtpy!\n"));
1289                            }
1290                        }
1291                    }
1292                    break;
1293                }
1294                case 65: { // portamento on / off
1295                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1296                    pEngineChannel->PortamentoMode = itControlChangeEvent->Param.CC.Value >= 64;
1297                    break;
1298                }
1299                case 66: { // sostenuto
1300                    if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SostenutoPedal) {
1301                        dmsg(4,("SOSTENUTO (CENTER) PEDAL DOWN\n"));
1302                        pEngineChannel->SostenutoPedal = true;
1303    
1304                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1305                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1306                        #endif
1307    
1308                        SostenutoKeyCount = 0;
1309                        // Remeber the pressed keys
1310                        RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1311                        for (; iuiKey; ++iuiKey) {
1312                            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1313                            if (pKey->KeyPressed && SostenutoKeyCount < 128) SostenutoKeys[SostenutoKeyCount++] = *iuiKey;
1314                        }
1315                    }
1316                    if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SostenutoPedal) {
1317                        dmsg(4,("SOSTENUTO (CENTER) PEDAL UP\n"));
1318                        pEngineChannel->SostenutoPedal = false;
1319    
1320                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1321                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1322                        #endif
1323    
1324                        // release voices if the damper pedal is up and their respective key is not pressed
1325                        for (int i = 0; i < SostenutoKeyCount; i++) {
1326                            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[SostenutoKeys[i]];
1327                            if (!pKey->KeyPressed && !pEngineChannel->SustainPedal) {
1328                                RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1329                                if (itNewEvent) {
1330                                    *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1331                                    itNewEvent->Type = Event::type_release; // transform event type
1332                                }
1333                                else dmsg(1,("Event pool emtpy!\n"));
1334                          }                          }
1335                      }                      }
1336                  }                  }
1337                  break;                  break;
1338              }              }
         }  
1339    
         // update controller value in the engine's controller table  
         pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;  
1340    
1341          // move event from the unsorted event list to the control change event list              // Channel Mode Messages
1342          itControlChangeEvent.moveToEndOf(pCCEvents);  
1343                case 120: { // all sound off
1344                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1345                    break;
1346                }
1347                case 121: { // reset all controllers
1348                    pEngineChannel->ResetControllers();
1349                    break;
1350                }
1351                case 123: { // all notes off
1352                    ReleaseAllVoices(pEngineChannel, itControlChangeEvent);
1353                    break;
1354                }
1355                case 126: { // mono mode on
1356                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1357                    pEngineChannel->SoloMode = true;
1358                    break;
1359                }
1360                case 127: { // poly mode on
1361                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1362                    pEngineChannel->SoloMode = false;
1363                    break;
1364                }
1365            }
1366      }      }
1367    
1368      /**      /**
# Line 911  namespace LinuxSampler { namespace gig { Line 1380  namespace LinuxSampler { namespace gig {
1380    
1381          switch (id) {          switch (id) {
1382              case 0x41: { // Roland              case 0x41: { // Roland
1383                    dmsg(3,("Roland Sysex\n"));
1384                  uint8_t device_id, model_id, cmd_id;                  uint8_t device_id, model_id, cmd_id;
1385                  if (!reader.pop(&device_id)) goto free_sysex_data;                  if (!reader.pop(&device_id)) goto free_sysex_data;
1386                  if (!reader.pop(&model_id))  goto free_sysex_data;                  if (!reader.pop(&model_id))  goto free_sysex_data;
# Line 923  namespace LinuxSampler { namespace gig { Line 1393  namespace LinuxSampler { namespace gig {
1393                  const RingBuffer<uint8_t>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later                  const RingBuffer<uint8_t>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later
1394                  if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;                  if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;
1395                  if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters                  if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters
1396                        dmsg(3,("\tSystem Parameter\n"));
1397                  }                  }
1398                  else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters                  else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters
1399                        dmsg(3,("\tCommon Parameter\n"));
1400                  }                  }
1401                  else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)                  else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)
1402                      switch (addr[3]) {                      dmsg(3,("\tPart Parameter\n"));
1403                        switch (addr[2]) {
1404                          case 0x40: { // scale tuning                          case 0x40: { // scale tuning
1405                                dmsg(3,("\t\tScale Tuning\n"));
1406                              uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave                              uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave
1407                              if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;                              if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;
1408                              uint8_t checksum;                              uint8_t checksum;
1409                              if (!reader.pop(&checksum))                      goto free_sysex_data;                              if (!reader.pop(&checksum)) goto free_sysex_data;
1410                              if (GSCheckSum(checksum_reader, 12) != checksum) goto free_sysex_data;                              #if CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1411                                if (GSCheckSum(checksum_reader, 12)) goto free_sysex_data;
1412                                #endif // CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1413                              for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;                              for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;
1414                              AdjustScale((int8_t*) scale_tunes);                              AdjustScale((int8_t*) scale_tunes);
1415                                dmsg(3,("\t\t\tNew scale applied.\n"));
1416                              break;                              break;
1417                          }                          }
1418                      }                      }
# Line 980  namespace LinuxSampler { namespace gig { Line 1457  namespace LinuxSampler { namespace gig {
1457      }      }
1458    
1459      /**      /**
1460       * Initialize the parameter sequence for the modulation destination given by       * Releases all voices on an engine channel. All voices will go into
1461       * by 'dst' with the constant value given by val.       * the release stage and thus it might take some time (e.g. dependant to
1462         * their envelope release time) until they actually die.
1463         *
1464         * @param pEngineChannel - engine channel on which all voices should be released
1465         * @param itReleaseEvent - event which caused this releasing of all voices
1466         */
1467        void Engine::ReleaseAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itReleaseEvent) {
1468            RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1469            while (iuiKey) {
1470                midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1471                ++iuiKey;
1472                // append a 'release' event to the key's own event list
1473                RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1474                if (itNewEvent) {
1475                    *itNewEvent = *itReleaseEvent; // copy original event (to the key's event list)
1476                    itNewEvent->Type = Event::type_release; // transform event type
1477                }
1478                else dmsg(1,("Event pool emtpy!\n"));
1479            }
1480        }
1481    
1482        /**
1483         * Kills all voices on an engine channel as soon as possible. Voices
1484         * won't get into release state, their volume level will be ramped down
1485         * as fast as possible.
1486         *
1487         * @param pEngineChannel - engine channel on which all voices should be killed
1488         * @param itKillEvent    - event which caused this killing of all voices
1489       */       */
1490      void Engine::ResetSynthesisParameters(Event::destination_t dst, float val) {      void Engine::KillAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itKillEvent) {
1491          int maxsamples = pAudioOutputDevice->MaxSamplesPerCycle();          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1492          float* m = &pSynthesisParameters[dst][0];          RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
1493          for (int i = 0; i < maxsamples; i += 4) {          while (iuiKey != end) { // iterate through all active keys
1494             m[i]   = val;              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1495             m[i+1] = val;              ++iuiKey;
1496             m[i+2] = val;              RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
1497             m[i+3] = val;              RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
1498                for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
1499                    itVoice->Kill(itKillEvent);
1500                    --VoiceSpawnsLeft; //FIXME: just a temporary workaround, we should check the cause in StealVoice() instead
1501                }
1502          }          }
1503      }          }
1504    
1505        /**
1506         * Determines whether the specified voice should be released.
1507         *
1508         * @param pEngineChannel - The engine channel on which the voice should be checked
1509         * @param Key - The key number
1510         * @returns true if the specified should be released, false otherwise.
1511         */
1512        bool Engine::ShouldReleaseVoice(EngineChannel* pEngineChannel, int Key) {
1513            if (pEngineChannel->SustainPedal) return false;
1514    
1515            if (pEngineChannel->SostenutoPedal) {
1516                for (int i = 0; i < SostenutoKeyCount; i++)
1517                    if (Key == SostenutoKeys[i]) return false;
1518            }
1519    
1520            return true;
1521        }
1522    
1523      uint Engine::VoiceCount() {      uint Engine::VoiceCount() {
1524          return ActiveVoiceCount;          return ActiveVoiceCount;
# Line 1023  namespace LinuxSampler { namespace gig { Line 1549  namespace LinuxSampler { namespace gig {
1549      }      }
1550    
1551      String Engine::EngineName() {      String Engine::EngineName() {
1552          return "GigEngine";          return LS_GIG_ENGINE_NAME;
1553      }      }
1554    
1555      String Engine::Description() {      String Engine::Description() {
# Line 1031  namespace LinuxSampler { namespace gig { Line 1557  namespace LinuxSampler { namespace gig {
1557      }      }
1558    
1559      String Engine::Version() {      String Engine::Version() {
1560          String s = "$Revision: 1.29 $";          String s = "$Revision: 1.58 $";
1561          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
1562      }      }
1563    
1564        // static constant initializers
1565        const float* Engine::VolumeCurve(InitVolumeCurve());
1566        const float* Engine::PanCurve(InitPanCurve());
1567    
1568        float* Engine::InitVolumeCurve() {
1569            // line-segment approximation
1570            const float segments[] = {
1571                0, 0, 2, 0.0046, 16, 0.016, 31, 0.051, 45, 0.115, 54.5, 0.2,
1572                64.5, 0.39, 74, 0.74, 92, 1.03, 114, 1.94, 119.2, 2.2, 127, 2.2
1573            };
1574            return InitCurve(segments);
1575        }
1576    
1577        float* Engine::InitPanCurve() {
1578            // line-segment approximation
1579            const float segments[] = {
1580                0, 0, 1, 0,
1581                2, 0.05, 31.5, 0.7, 51, 0.851, 74.5, 1.12,
1582                127, 1.41, 128, 1.41
1583            };
1584            return InitCurve(segments, 129);
1585        }
1586    
1587        float* Engine::InitCurve(const float* segments, int size) {
1588            float* y = new float[size];
1589            for (int x = 0 ; x < size ; x++) {
1590                if (x > segments[2]) segments += 2;
1591                y[x] = segments[1] + (x - segments[0]) *
1592                    (segments[3] - segments[1]) / (segments[2] - segments[0]);
1593            }
1594            return y;
1595        }
1596    
1597  }} // namespace LinuxSampler::gig  }} // namespace LinuxSampler::gig

Legend:
Removed from v.424  
changed lines
  Added in v.831

  ViewVC Help
Powered by ViewVC