/[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 438 by persson, Wed Mar 9 22:12:15 2005 UTC revision 776 by iliev, Wed Sep 21 19:05:41 2005 UTC
# 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 64  namespace LinuxSampler { namespace gig { Line 58  namespace LinuxSampler { namespace gig {
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 217  namespace LinuxSampler { namespace gig { Line 223  namespace LinuxSampler { namespace gig {
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      }      }
# 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);
             std::list<EngineChannel*>::iterator end       = engineChannels.end();  
             for (; itChannel != end; itChannel++) {  
                 if (!(*itChannel)->pInstrument) continue; // ignore if no instrument loaded  
                 RenderAudio(*itChannel, Samples);  
             }  
375          }          }
376    
377            // render all 'normal', active voices on all engine channels
378            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"));
         // reset voice stealing for the new fragment  
         pVoiceStealingQueue->clear();  
         pEngineChannel->itLastStolenVoice = RTList<Voice>::Iterator();  
         pEngineChannel->iuiLastStolenKey  = RTList<uint>::Iterator();  
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        }
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    
# Line 554  namespace LinuxSampler { namespace gig { Line 612  namespace LinuxSampler { namespace gig {
612          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];
613    
614          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
615            pKey->Velocity   = itNoteOnEvent->Param.Note.Velocity;
616            pKey->NoteOnTime = FrameTime + itNoteOnEvent->FragmentPos(); // will be used to calculate note length
617    
618          // cancel release process of voices on this key if needed          // cancel release process of voices on this key if needed
619          if (pKey->Active && !pEngineChannel->SustainPedal) {          if (pKey->Active && !pEngineChannel->SustainPedal) {
# Line 568  namespace LinuxSampler { namespace gig { Line 628  namespace LinuxSampler { namespace gig {
628          // move note on event to the key's own event list          // move note on event to the key's own event list
629          RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);          RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
630    
631          // allocate and trigger a new voice for the key          // allocate and trigger new voice(s) for the key
632          LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, 0, false, true);          {
633                // first, get total amount of required voices (dependant on amount of layers)
634                ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOnEventOnKeyList->Param.Note.Key);
635                if (pRegion) {
636                    int voicesRequired = pRegion->Layers;
637                    // now launch the required amount of voices
638                    for (int i = 0; i < voicesRequired; i++)
639                        LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true, true);
640                }
641            }
642    
643            // if neither a voice was spawned or postponed then remove note on event from key again
644            if (!pKey->Active && !pKey->VoiceTheftsQueued)
645                pKey->pEvents->free(itNoteOnEventOnKeyList);
646    
647          pKey->RoundRobinIndex++;          pKey->RoundRobinIndex++;
648      }      }
# Line 584  namespace LinuxSampler { namespace gig { Line 657  namespace LinuxSampler { namespace gig {
657       *  @param itNoteOffEvent - key, velocity and time stamp of the event       *  @param itNoteOffEvent - key, velocity and time stamp of the event
658       */       */
659      void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {      void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {
660          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];          #if !CONFIG_PROCESS_MUTED_CHANNELS
661            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
662            #endif
663    
664            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];
665          pKey->KeyPressed = false; // the MIDI key was now released          pKey->KeyPressed = false; // the MIDI key was now released
666    
667          // release voices on this key if needed          // release voices on this key if needed
668          if (pKey->Active && !pEngineChannel->SustainPedal) {          if (pKey->Active && ShouldReleaseVoice(pEngineChannel, itNoteOffEvent->Param.Note.Key)) {
669              itNoteOffEvent->Type = Event::type_release; // transform event type              itNoteOffEvent->Type = Event::type_release; // transform event type
         }  
670    
671          // move event to the key's own event list              // move event to the key's own event list
672          RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);              RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
673    
674          // spawn release triggered voice(s) if needed              // spawn release triggered voice(s) if needed
675          if (pKey->ReleaseTrigger) {              if (pKey->ReleaseTrigger) {
676              LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, 0, true, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples                  // first, get total amount of required voices (dependant on amount of layers)
677              pKey->ReleaseTrigger = false;                  ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOffEventOnKeyList->Param.Note.Key);
678                    if (pRegion) {
679                        int voicesRequired = pRegion->Layers;
680    
681                        // MIDI note-on velocity is used instead of note-off velocity
682                        itNoteOffEventOnKeyList->Param.Note.Velocity = pKey->Velocity;
683    
684                        // now launch the required amount of voices
685                        for (int i = 0; i < voicesRequired; i++)
686                            LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, i, true, false, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
687                    }
688                    pKey->ReleaseTrigger = false;
689                }
690    
691                // if neither a voice was spawned or postponed then remove note off event from key again
692                if (!pKey->Active && !pKey->VoiceTheftsQueued)
693                    pKey->pEvents->free(itNoteOffEventOnKeyList);
694          }          }
695      }      }
696    
697      /**      /**
698       *  Moves pitchbend event from the general (input) event list to the pitch       *  Moves pitchbend event from the general (input) event list to the engine
699       *  event list.       *  channel's event list. It will actually processed later by the
700         *  respective voice.
701       *       *
702       *  @param pEngineChannel - engine channel on which this event occured on       *  @param pEngineChannel - engine channel on which this event occured on
703       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event       *  @param itPitchbendEvent - absolute pitch value and time stamp of the event
704       */       */
705      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {
706          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]);  
707      }      }
708    
709      /**      /**
# Line 629  namespace LinuxSampler { namespace gig { Line 720  namespace LinuxSampler { namespace gig {
720       *  @param VoiceStealing       - if voice stealing should be performed       *  @param VoiceStealing       - if voice stealing should be performed
721       *                               when there is no free voice       *                               when there is no free voice
722       *                               (optional, default = true)       *                               (optional, default = true)
723         *  @param HandleKeyGroupConflicts - if voices should be killed due to a
724         *                                   key group conflict
725       *  @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
726       *           if the voice wasn't triggered (for example when no region is       *           if the voice wasn't triggered (for example when no region is
727       *           defined for the given key).       *           defined for the given key).
728       */       */
729      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) {
730          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];          int MIDIKey            = itNoteOnEvent->Param.Note.Key;
731            midi_key_info_t* pKey  = &pEngineChannel->pMIDIKeyInfo[MIDIKey];
732            ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(MIDIKey);
733    
734            // if nothing defined for this key
735            if (!pRegion) return Pool<Voice>::Iterator(); // nothing to do
736    
737            // only mark the first voice of a layered voice (group) to be in a
738            // key group, so the layered voices won't kill each other
739            int iKeyGroup = (iLayer == 0 && !ReleaseTriggerVoice) ? pRegion->KeyGroup : 0;
740    
741            // handle key group (a.k.a. exclusive group) conflicts
742            if (HandleKeyGroupConflicts) {
743                if (iKeyGroup) { // if this voice / key belongs to a key group
744                    uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[iKeyGroup];
745                    if (*ppKeyGroup) { // if there's already an active key in that key group
746                        midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[**ppKeyGroup];
747                        // kill all voices on the (other) key
748                        RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
749                        RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
750                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
751                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger) {
752                                itVoiceToBeKilled->Kill(itNoteOnEvent);
753                                --VoiceSpawnsLeft; //FIXME: just a hack, we should better check in StealVoice() if the voice was killed due to key conflict
754                            }
755                        }
756                    }
757                }
758            }
759    
760            Voice::type_t VoiceType = Voice::type_normal;
761    
762            // get current dimension values to select the right dimension region
763            //TODO: for stolen voices this dimension region selection block is processed twice, this should be changed
764            //FIXME: controller values for selecting the dimension region here are currently not sample accurate
765            uint DimValues[8] = { 0 };
766            for (int i = pRegion->Dimensions - 1; i >= 0; i--) {
767                switch (pRegion->pDimensionDefinitions[i].dimension) {
768                    case ::gig::dimension_samplechannel:
769                        DimValues[i] = 0; //TODO: we currently ignore this dimension
770                        break;
771                    case ::gig::dimension_layer:
772                        DimValues[i] = iLayer;
773                        break;
774                    case ::gig::dimension_velocity:
775                        DimValues[i] = itNoteOnEvent->Param.Note.Velocity;
776                        break;
777                    case ::gig::dimension_channelaftertouch:
778                        DimValues[i] = 0; //TODO: we currently ignore this dimension
779                        break;
780                    case ::gig::dimension_releasetrigger:
781                        VoiceType = (ReleaseTriggerVoice) ? Voice::type_release_trigger : (!iLayer) ? Voice::type_release_trigger_required : Voice::type_normal;
782                        DimValues[i] = (uint) ReleaseTriggerVoice;
783                        break;
784                    case ::gig::dimension_keyboard:
785                        DimValues[i] = (uint) pEngineChannel->CurrentKeyDimension;
786                        break;
787                    case ::gig::dimension_roundrobin:
788                        DimValues[i] = (uint) pEngineChannel->pMIDIKeyInfo[MIDIKey].RoundRobinIndex; // incremented for each note on
789                        break;
790                    case ::gig::dimension_random:
791                        RandomSeed   = RandomSeed * 1103515245 + 12345; // classic pseudo random number generator
792                        DimValues[i] = (uint) RandomSeed >> (32 - pRegion->pDimensionDefinitions[i].bits); // highest bits are most random
793                        break;
794                    case ::gig::dimension_modwheel:
795                        DimValues[i] = pEngineChannel->ControllerTable[1];
796                        break;
797                    case ::gig::dimension_breath:
798                        DimValues[i] = pEngineChannel->ControllerTable[2];
799                        break;
800                    case ::gig::dimension_foot:
801                        DimValues[i] = pEngineChannel->ControllerTable[4];
802                        break;
803                    case ::gig::dimension_portamentotime:
804                        DimValues[i] = pEngineChannel->ControllerTable[5];
805                        break;
806                    case ::gig::dimension_effect1:
807                        DimValues[i] = pEngineChannel->ControllerTable[12];
808                        break;
809                    case ::gig::dimension_effect2:
810                        DimValues[i] = pEngineChannel->ControllerTable[13];
811                        break;
812                    case ::gig::dimension_genpurpose1:
813                        DimValues[i] = pEngineChannel->ControllerTable[16];
814                        break;
815                    case ::gig::dimension_genpurpose2:
816                        DimValues[i] = pEngineChannel->ControllerTable[17];
817                        break;
818                    case ::gig::dimension_genpurpose3:
819                        DimValues[i] = pEngineChannel->ControllerTable[18];
820                        break;
821                    case ::gig::dimension_genpurpose4:
822                        DimValues[i] = pEngineChannel->ControllerTable[19];
823                        break;
824                    case ::gig::dimension_sustainpedal:
825                        DimValues[i] = pEngineChannel->ControllerTable[64];
826                        break;
827                    case ::gig::dimension_portamento:
828                        DimValues[i] = pEngineChannel->ControllerTable[65];
829                        break;
830                    case ::gig::dimension_sostenutopedal:
831                        DimValues[i] = pEngineChannel->ControllerTable[66];
832                        break;
833                    case ::gig::dimension_softpedal:
834                        DimValues[i] = pEngineChannel->ControllerTable[67];
835                        break;
836                    case ::gig::dimension_genpurpose5:
837                        DimValues[i] = pEngineChannel->ControllerTable[80];
838                        break;
839                    case ::gig::dimension_genpurpose6:
840                        DimValues[i] = pEngineChannel->ControllerTable[81];
841                        break;
842                    case ::gig::dimension_genpurpose7:
843                        DimValues[i] = pEngineChannel->ControllerTable[82];
844                        break;
845                    case ::gig::dimension_genpurpose8:
846                        DimValues[i] = pEngineChannel->ControllerTable[83];
847                        break;
848                    case ::gig::dimension_effect1depth:
849                        DimValues[i] = pEngineChannel->ControllerTable[91];
850                        break;
851                    case ::gig::dimension_effect2depth:
852                        DimValues[i] = pEngineChannel->ControllerTable[92];
853                        break;
854                    case ::gig::dimension_effect3depth:
855                        DimValues[i] = pEngineChannel->ControllerTable[93];
856                        break;
857                    case ::gig::dimension_effect4depth:
858                        DimValues[i] = pEngineChannel->ControllerTable[94];
859                        break;
860                    case ::gig::dimension_effect5depth:
861                        DimValues[i] = pEngineChannel->ControllerTable[95];
862                        break;
863                    case ::gig::dimension_none:
864                        std::cerr << "gig::Engine::LaunchVoice() Error: dimension=none\n" << std::flush;
865                        break;
866                    default:
867                        std::cerr << "gig::Engine::LaunchVoice() Error: Unknown dimension\n" << std::flush;
868                }
869            }
870            ::gig::DimensionRegion* pDimRgn = pRegion->GetDimensionRegionByValue(DimValues);
871    
872            // no need to continue if sample is silent
873            if (!pDimRgn->pSample || !pDimRgn->pSample->SamplesTotal) return Pool<Voice>::Iterator();
874    
875          // allocate a new voice for the key          // allocate a new voice for the key
876          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
877          if (itNewVoice) {          if (itNewVoice) {
878              // launch the new voice              // launch the new voice
879              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pEngineChannel->pInstrument, iLayer, ReleaseTriggerVoice, VoiceStealing) < 0) {              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pDimRgn, VoiceType, iKeyGroup) < 0) {
880                  dmsg(4,("Voice not triggered\n"));                  dmsg(4,("Voice not triggered\n"));
881                  pKey->pActiveVoices->free(itNewVoice);                  pKey->pActiveVoices->free(itNewVoice);
882              }              }
883              else { // on success              else { // on success
884                  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);  
                         }  
                     }  
                 }  
885                  if (!pKey->Active) { // mark as active key                  if (!pKey->Active) { // mark as active key
886                      pKey->Active = true;                      pKey->Active = true;
887                      pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();                      pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();
888                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
889                  }                  }
890                  if (itNewVoice->KeyGroup) {                  if (itNewVoice->KeyGroup) {
891                        uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup];
892                      *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
893                  }                  }
894                  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 671  namespace LinuxSampler { namespace gig { Line 896  namespace LinuxSampler { namespace gig {
896              }              }
897          }          }
898          else if (VoiceStealing) {          else if (VoiceStealing) {
899              // first, get total amount of required voices (dependant on amount of layers)              // try to steal one voice
900              ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOnEvent->Param.Note.Key);              int result = StealVoice(pEngineChannel, itNoteOnEvent);
901              if (!pRegion) return Pool<Voice>::Iterator(); // nothing defined for this MIDI key, so no voice needed              if (!result) { // voice stolen successfully
902              int voicesRequired = pRegion->Layers;                  // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died
903                    RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();
904              // now steal the (remaining) amount of voices                  if (itStealEvent) {
905              for (int i = iLayer; i < voicesRequired; i++)                      *itStealEvent = *itNoteOnEvent; // copy event
906                  StealVoice(pEngineChannel, itNoteOnEvent);                      itStealEvent->Param.Note.Layer = iLayer;
907                        itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;
908              // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died                      pKey->VoiceTheftsQueued++;
909              RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();                  }
910              if (itStealEvent) {                  else dmsg(1,("Voice stealing queue full!\n"));
                 *itStealEvent = *itNoteOnEvent; // copy event  
                 itStealEvent->Param.Note.Layer = iLayer;  
                 itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;  
911              }              }
             else dmsg(1,("Voice stealing queue full!\n"));  
912          }          }
913    
914          return Pool<Voice>::Iterator(); // no free voice or error          return Pool<Voice>::Iterator(); // no free voice or error
# Line 701  namespace LinuxSampler { namespace gig { Line 922  namespace LinuxSampler { namespace gig {
922       *       *
923       *  @param pEngineChannel - engine channel on which this event occured on       *  @param pEngineChannel - engine channel on which this event occured on
924       *  @param itNoteOnEvent - key, velocity and time stamp of the event       *  @param itNoteOnEvent - key, velocity and time stamp of the event
925         *  @returns 0 on success, a value < 0 if no active voice could be picked for voice stealing
926       */       */
927      void Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {      int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
928            if (VoiceSpawnsLeft <= 0) {
929                dmsg(1,("Max. voice thefts per audio fragment reached (you may raise CONFIG_MAX_VOICES).\n"));
930                return -1;
931            }
932          if (!pEventPool->poolIsEmpty()) {          if (!pEventPool->poolIsEmpty()) {
933    
934              RTList<uint>::Iterator  iuiOldestKey;              RTList<Voice>::Iterator itSelectedVoice;
             RTList<Voice>::Iterator itOldestVoice;  
935    
936              // Select one voice for voice stealing              // Select one voice for voice stealing
937              switch (VOICE_STEAL_ALGORITHM) {              switch (CONFIG_VOICE_STEAL_ALGO) {
938    
939                  // try to pick the oldest voice on the key where the new                  // try to pick the oldest voice on the key where the new
940                  // voice should be spawned, if there is no voice on that                  // voice should be spawned, if there is no voice on that
941                  // key, or no voice left to kill there, then procceed with                  // key, or no voice left to kill, then procceed with
942                  // 'oldestkey' algorithm                  // 'oldestkey' algorithm
943                  case voice_steal_algo_keymask: {                  case voice_steal_algo_oldestvoiceonkey: {
944                      midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];                      midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
945                      if (pEngineChannel->itLastStolenVoice) {                      itSelectedVoice = pSelectedKey->pActiveVoices->first();
946                          itOldestVoice = pEngineChannel->itLastStolenVoice;                      // proceed iterating if voice was created in this fragment cycle
947                          ++itOldestVoice;                      while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
948                      }                      // if we haven't found a voice then proceed with algorithm 'oldestkey'
949                      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  
                     }  
950                  } // no break - intentional !                  } // no break - intentional !
951    
952                  // try to pick the oldest voice on the oldest active key                  // try to pick the oldest voice on the oldest active key
953                  // (caution: must stay after 'keymask' algorithm !)                  // from the same engine channel
954                    // (caution: must stay after 'oldestvoiceonkey' algorithm !)
955                  case voice_steal_algo_oldestkey: {                  case voice_steal_algo_oldestkey: {
956                      if (pEngineChannel->itLastStolenVoice) {                      // if we already stole in this fragment, try to proceed on same key
957                          midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[*pEngineChannel->iuiLastStolenKey];                      if (this->itLastStolenVoice) {
958                          itOldestVoice = pEngineChannel->itLastStolenVoice;                          itSelectedVoice = this->itLastStolenVoice;
959                          ++itOldestVoice;                          do {
960                          if (!itOldestVoice) {                              ++itSelectedVoice;
961                              iuiOldestKey = pEngineChannel->iuiLastStolenKey;                          } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
962                              ++iuiOldestKey;                          // found a "stealable" voice ?
963                              if (iuiOldestKey) {                          if (itSelectedVoice && itSelectedVoice->IsStealable()) {
964                                  midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[*iuiOldestKey];                              // remember which voice we stole, so we can simply proceed on next voice stealing
965                                  itOldestVoice = pOldestKey->pActiveVoices->first();                              this->itLastStolenVoice = itSelectedVoice;
966                              }                              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;  
                             }  
967                          }                          }
                         else iuiOldestKey = pEngineChannel->iuiLastStolenKey;  
968                      }                      }
969                      else { // no voice stolen in this audio fragment cycle yet                      // get (next) oldest key
970                          iuiOldestKey = pEngineChannel->pActiveKeys->first();                      RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKey) ? ++this->iuiLastStolenKey : pEngineChannel->pActiveKeys->first();
971                          midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[*iuiOldestKey];                      while (iuiSelectedKey) {
972                          itOldestVoice = pOldestKey->pActiveVoices->first();                          midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];
973                            itSelectedVoice = pSelectedKey->pActiveVoices->first();
974                            // proceed iterating if voice was created in this fragment cycle
975                            while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
976                            // found a "stealable" voice ?
977                            if (itSelectedVoice && itSelectedVoice->IsStealable()) {
978                                // remember which voice on which key we stole, so we can simply proceed on next voice stealing
979                                this->iuiLastStolenKey  = iuiSelectedKey;
980                                this->itLastStolenVoice = itSelectedVoice;
981                                break; // selection succeeded
982                            }
983                            ++iuiSelectedKey; // get next oldest key
984                      }                      }
985                      break;                      break;
986                  }                  }
# Line 763  namespace LinuxSampler { namespace gig { Line 989  namespace LinuxSampler { namespace gig {
989                  case voice_steal_algo_none:                  case voice_steal_algo_none:
990                  default: {                  default: {
991                      dmsg(1,("No free voice (voice stealing disabled)!\n"));                      dmsg(1,("No free voice (voice stealing disabled)!\n"));
992                      return;                      return -1;
993                    }
994                }
995    
996                // if we couldn't steal a voice from the same engine channel then
997                // steal oldest voice on the oldest key from any other engine channel
998                // (the smaller engine channel number, the higher priority)
999                if (!itSelectedVoice || !itSelectedVoice->IsStealable()) {
1000                    EngineChannel* pSelectedChannel;
1001                    int            iChannelIndex;
1002                    // select engine channel
1003                    if (pLastStolenChannel) {
1004                        pSelectedChannel = pLastStolenChannel;
1005                        iChannelIndex    = pSelectedChannel->iEngineIndexSelf;
1006                    } else { // pick the engine channel followed by this engine channel
1007                        iChannelIndex    = (pEngineChannel->iEngineIndexSelf + 1) % engineChannels.size();
1008                        pSelectedChannel = engineChannels[iChannelIndex];
1009                    }
1010    
1011                    // if we already stole in this fragment, try to proceed on same key
1012                    if (this->itLastStolenVoiceGlobally) {
1013                        itSelectedVoice = this->itLastStolenVoiceGlobally;
1014                        do {
1015                            ++itSelectedVoice;
1016                        } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1017                    }
1018    
1019                    #if CONFIG_DEVMODE
1020                    EngineChannel* pBegin = pSelectedChannel; // to detect endless loop
1021                    #endif // CONFIG_DEVMODE
1022    
1023                    // did we find a 'stealable' voice?
1024                    if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1025                        // remember which voice we stole, so we can simply proceed on next voice stealing
1026                        this->itLastStolenVoiceGlobally = itSelectedVoice;
1027                    } else while (true) { // iterate through engine channels
1028                        // get (next) oldest key
1029                        RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKeyGlobally) ? ++this->iuiLastStolenKeyGlobally : pSelectedChannel->pActiveKeys->first();
1030                        this->iuiLastStolenKeyGlobally = RTList<uint>::Iterator(); // to prevent endless loop (see line above)
1031                        while (iuiSelectedKey) {
1032                            midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];
1033                            itSelectedVoice = pSelectedKey->pActiveVoices->first();
1034                            // proceed iterating if voice was created in this fragment cycle
1035                            while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1036                            // found a "stealable" voice ?
1037                            if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1038                                // remember which voice on which key on which engine channel we stole, so we can simply proceed on next voice stealing
1039                                this->iuiLastStolenKeyGlobally  = iuiSelectedKey;
1040                                this->itLastStolenVoiceGlobally = itSelectedVoice;
1041                                this->pLastStolenChannel        = pSelectedChannel;
1042                                goto stealable_voice_found; // selection succeeded
1043                            }
1044                            ++iuiSelectedKey; // get next key on current engine channel
1045                        }
1046                        // get next engine channel
1047                        iChannelIndex    = (iChannelIndex + 1) % engineChannels.size();
1048                        pSelectedChannel = engineChannels[iChannelIndex];
1049    
1050                        #if CONFIG_DEVMODE
1051                        if (pSelectedChannel == pBegin) {
1052                            dmsg(1,("FATAL ERROR: voice stealing endless loop!\n"));
1053                            dmsg(1,("VoiceSpawnsLeft=%d.\n", VoiceSpawnsLeft));
1054                            dmsg(1,("Exiting.\n"));
1055                            exit(-1);
1056                        }
1057                        #endif // CONFIG_DEVMODE
1058                  }                  }
1059              }              }
1060    
1061              //FIXME: can be removed, just a sanity check for debugging              // jump point if a 'stealable' voice was found
1062              if (!itOldestVoice->IsActive()) dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));              stealable_voice_found:
1063    
1064                #if CONFIG_DEVMODE
1065                if (!itSelectedVoice->IsActive()) {
1066                    dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
1067                    return -1;
1068                }
1069                #endif // CONFIG_DEVMODE
1070    
1071              // now kill the selected voice              // now kill the selected voice
1072              itOldestVoice->Kill(itNoteOnEvent);              itSelectedVoice->Kill(itNoteOnEvent);
1073              // remember which voice on which key we stole, so we can simply proceed for the next voice stealing  
1074              pEngineChannel->itLastStolenVoice = itOldestVoice;              --VoiceSpawnsLeft;
1075              pEngineChannel->iuiLastStolenKey = iuiOldestKey;  
1076                return 0; // success
1077            }
1078            else {
1079                dmsg(1,("Event pool emtpy!\n"));
1080                return -1;
1081          }          }
         else dmsg(1,("Event pool emtpy!\n"));  
1082      }      }
1083    
1084      /**      /**
# Line 835  namespace LinuxSampler { namespace gig { Line 1137  namespace LinuxSampler { namespace gig {
1137      void Engine::ProcessControlChange(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itControlChangeEvent) {      void Engine::ProcessControlChange(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itControlChangeEvent) {
1138          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));
1139    
1140            // update controller value in the engine channel's controller table
1141            pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
1142    
1143          switch (itControlChangeEvent->Param.CC.Controller) {          switch (itControlChangeEvent->Param.CC.Controller) {
1144              case 7: { // volume              case 7: { // volume
1145                  //TODO: not sample accurate yet                  //TODO: not sample accurate yet
1146                  pEngineChannel->GlobalVolume = (float) itControlChangeEvent->Param.CC.Value / 127.0f;                  pEngineChannel->GlobalVolume = (float) itControlChangeEvent->Param.CC.Value / 127.0f;
1147                    pEngineChannel->bStatusChanged = true; // engine channel status has changed, so set notify flag
1148                  break;                  break;
1149              }              }
1150              case 10: { // panpot              case 10: { // panpot
# Line 850  namespace LinuxSampler { namespace gig { Line 1156  namespace LinuxSampler { namespace gig {
1156              }              }
1157              case 64: { // sustain              case 64: { // sustain
1158                  if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {
1159                      dmsg(4,("PEDAL DOWN\n"));                      dmsg(4,("DAMPER (RIGHT) PEDAL DOWN\n"));
1160                      pEngineChannel->SustainPedal = true;                      pEngineChannel->SustainPedal = true;
1161    
1162                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1163                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1164                        #endif
1165    
1166                      // cancel release process of voices if necessary                      // cancel release process of voices if necessary
1167                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1168                      if (iuiKey) {                      for (; iuiKey; ++iuiKey) {
1169                          itControlChangeEvent->Type = Event::type_cancel_release; // transform event type                          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1170                          while (iuiKey) {                          if (!pKey->KeyPressed) {
1171                              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1172                              ++iuiKey;                              if (itNewEvent) {
1173                              if (!pKey->KeyPressed) {                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1174                                  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"));  
1175                              }                              }
1176                                else dmsg(1,("Event pool emtpy!\n"));
1177                          }                          }
1178                      }                      }
1179                  }                  }
1180                  if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {
1181                      dmsg(4,("PEDAL UP\n"));                      dmsg(4,("DAMPER (RIGHT) PEDAL UP\n"));
1182                      pEngineChannel->SustainPedal = false;                      pEngineChannel->SustainPedal = false;
1183    
1184                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1185                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1186                        #endif
1187    
1188                      // release voices if their respective key is not pressed                      // release voices if their respective key is not pressed
1189                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1190                      if (iuiKey) {                      for (; iuiKey; ++iuiKey) {
1191                          itControlChangeEvent->Type = Event::type_release; // transform event type                          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1192                          while (iuiKey) {                          if (!pKey->KeyPressed && ShouldReleaseVoice(pEngineChannel, *iuiKey)) {
1193                              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1194                              ++iuiKey;                              if (itNewEvent) {
1195                              if (!pKey->KeyPressed) {                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1196                                  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"));  
1197                              }                              }
1198                                else dmsg(1,("Event pool emtpy!\n"));
1199                          }                          }
1200                      }                      }
1201                  }                  }
1202                  break;                  break;
1203              }              }
1204          }              case 66: { // sostenuto
1205                    if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SostenutoPedal) {
1206                        dmsg(4,("SOSTENUTO (CENTER) PEDAL DOWN\n"));
1207                        pEngineChannel->SostenutoPedal = true;
1208    
1209                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1210                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1211                        #endif
1212    
1213          // update controller value in the engine's controller table                      SostenutoKeyCount = 0;
1214          pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;                      // Remeber the pressed keys
1215                        RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1216                        for (; iuiKey; ++iuiKey) {
1217                            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1218                            if (pKey->KeyPressed && SostenutoKeyCount < 128) SostenutoKeys[SostenutoKeyCount++] = *iuiKey;
1219                        }
1220                    }
1221                    if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SostenutoPedal) {
1222                        dmsg(4,("SOSTENUTO (CENTER) PEDAL UP\n"));
1223                        pEngineChannel->SostenutoPedal = false;
1224    
1225                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1226                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1227                        #endif
1228    
1229                        // release voices if the damper pedal is up and their respective key is not pressed
1230                        for (int i = 0; i < SostenutoKeyCount; i++) {
1231                            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[SostenutoKeys[i]];
1232                            if (!pKey->KeyPressed && !pEngineChannel->SustainPedal) {
1233                                RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1234                                if (itNewEvent) {
1235                                    *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1236                                    itNewEvent->Type = Event::type_release; // transform event type
1237                                }
1238                                else dmsg(1,("Event pool emtpy!\n"));
1239                            }
1240                        }
1241                    }
1242                    break;
1243                }
1244    
1245    
1246                // Channel Mode Messages
1247    
1248          // move event from the unsorted event list to the control change event list              case 120: { // all sound off
1249          itControlChangeEvent.moveToEndOf(pCCEvents);                  KillAllVoices(pEngineChannel, itControlChangeEvent);
1250                    break;
1251                }
1252                case 121: { // reset all controllers
1253                    pEngineChannel->ResetControllers();
1254                    break;
1255                }
1256                case 123: { // all notes off
1257                    ReleaseAllVoices(pEngineChannel, itControlChangeEvent);
1258                    break;
1259                }
1260            }
1261      }      }
1262    
1263      /**      /**
# Line 913  namespace LinuxSampler { namespace gig { Line 1275  namespace LinuxSampler { namespace gig {
1275    
1276          switch (id) {          switch (id) {
1277              case 0x41: { // Roland              case 0x41: { // Roland
1278                    dmsg(3,("Roland Sysex\n"));
1279                  uint8_t device_id, model_id, cmd_id;                  uint8_t device_id, model_id, cmd_id;
1280                  if (!reader.pop(&device_id)) goto free_sysex_data;                  if (!reader.pop(&device_id)) goto free_sysex_data;
1281                  if (!reader.pop(&model_id))  goto free_sysex_data;                  if (!reader.pop(&model_id))  goto free_sysex_data;
# Line 925  namespace LinuxSampler { namespace gig { Line 1288  namespace LinuxSampler { namespace gig {
1288                  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
1289                  if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;                  if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;
1290                  if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters                  if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters
1291                        dmsg(3,("\tSystem Parameter\n"));
1292                  }                  }
1293                  else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters                  else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters
1294                        dmsg(3,("\tCommon Parameter\n"));
1295                  }                  }
1296                  else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)                  else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)
1297                      switch (addr[3]) {                      dmsg(3,("\tPart Parameter\n"));
1298                        switch (addr[2]) {
1299                          case 0x40: { // scale tuning                          case 0x40: { // scale tuning
1300                                dmsg(3,("\t\tScale Tuning\n"));
1301                              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
1302                              if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;                              if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;
1303                              uint8_t checksum;                              uint8_t checksum;
1304                              if (!reader.pop(&checksum))                      goto free_sysex_data;                              if (!reader.pop(&checksum)) goto free_sysex_data;
1305                              if (GSCheckSum(checksum_reader, 12) != checksum) goto free_sysex_data;                              #if CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1306                                if (GSCheckSum(checksum_reader, 12)) goto free_sysex_data;
1307                                #endif // CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1308                              for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;                              for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;
1309                              AdjustScale((int8_t*) scale_tunes);                              AdjustScale((int8_t*) scale_tunes);
1310                                dmsg(3,("\t\t\tNew scale applied.\n"));
1311                              break;                              break;
1312                          }                          }
1313                      }                      }
# Line 982  namespace LinuxSampler { namespace gig { Line 1352  namespace LinuxSampler { namespace gig {
1352      }      }
1353    
1354      /**      /**
1355       * Initialize the parameter sequence for the modulation destination given by       * Releases all voices on an engine channel. All voices will go into
1356       * by 'dst' with the constant value given by val.       * the release stage and thus it might take some time (e.g. dependant to
1357         * their envelope release time) until they actually die.
1358         *
1359         * @param pEngineChannel - engine channel on which all voices should be released
1360         * @param itReleaseEvent - event which caused this releasing of all voices
1361         */
1362        void Engine::ReleaseAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itReleaseEvent) {
1363            RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1364            while (iuiKey) {
1365                midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1366                ++iuiKey;
1367                // append a 'release' event to the key's own event list
1368                RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1369                if (itNewEvent) {
1370                    *itNewEvent = *itReleaseEvent; // copy original event (to the key's event list)
1371                    itNewEvent->Type = Event::type_release; // transform event type
1372                }
1373                else dmsg(1,("Event pool emtpy!\n"));
1374            }
1375        }
1376    
1377        /**
1378         * Kills all voices on an engine channel as soon as possible. Voices
1379         * won't get into release state, their volume level will be ramped down
1380         * as fast as possible.
1381         *
1382         * @param pEngineChannel - engine channel on which all voices should be killed
1383         * @param itKillEvent    - event which caused this killing of all voices
1384       */       */
1385      void Engine::ResetSynthesisParameters(Event::destination_t dst, float val) {      void Engine::KillAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itKillEvent) {
1386          int maxsamples = pAudioOutputDevice->MaxSamplesPerCycle();          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1387          float* m = &pSynthesisParameters[dst][0];          RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
1388          for (int i = 0; i < maxsamples; i += 4) {          while (iuiKey != end) { // iterate through all active keys
1389             m[i]   = val;              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1390             m[i+1] = val;              ++iuiKey;
1391             m[i+2] = val;              RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
1392             m[i+3] = val;              RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
1393                for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
1394                    itVoice->Kill(itKillEvent);
1395                    --VoiceSpawnsLeft; //FIXME: just a temporary workaround, we should check the cause in StealVoice() instead
1396                }
1397          }          }
1398      }      }
1399    
1400        /**
1401         * Determines whether the specified voice should be released.
1402         *
1403         * @param pEngineChannel - The engine channel on which the voice should be checked
1404         * @param Key - The key number
1405         * @returns true if the specified should be released, false otherwise.
1406         */
1407        bool Engine::ShouldReleaseVoice(EngineChannel* pEngineChannel, int Key) {
1408            if (pEngineChannel->SustainPedal) return false;
1409    
1410            if (pEngineChannel->SostenutoPedal) {
1411                for (int i = 0; i < SostenutoKeyCount; i++)
1412                    if (Key == SostenutoKeys[i]) return false;
1413            }
1414    
1415            return true;
1416        }
1417    
1418      uint Engine::VoiceCount() {      uint Engine::VoiceCount() {
1419          return ActiveVoiceCount;          return ActiveVoiceCount;
1420      }      }
# Line 1025  namespace LinuxSampler { namespace gig { Line 1444  namespace LinuxSampler { namespace gig {
1444      }      }
1445    
1446      String Engine::EngineName() {      String Engine::EngineName() {
1447          return "GigEngine";          return LS_GIG_ENGINE_NAME;
1448      }      }
1449    
1450      String Engine::Description() {      String Engine::Description() {
# Line 1033  namespace LinuxSampler { namespace gig { Line 1452  namespace LinuxSampler { namespace gig {
1452      }      }
1453    
1454      String Engine::Version() {      String Engine::Version() {
1455          String s = "$Revision: 1.30 $";          String s = "$Revision: 1.55 $";
1456          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
1457      }      }
1458    

Legend:
Removed from v.438  
changed lines
  Added in v.776

  ViewVC Help
Powered by ViewVC