/[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 246 by schoenebeck, Sun Sep 19 14:12:55 2004 UTC revision 831 by persson, Sat Jan 28 16:55:30 2006 UTC
# Line 3  Line 3 
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6     *   Copyright (C) 2005, 2006 Christian Schoenebeck                        *
7   *                                                                         *   *                                                                         *
8   *   This program is free software; you can redistribute it and/or modify  *   *   This program is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 23  Line 24 
24  #include <sstream>  #include <sstream>
25  #include "DiskThread.h"  #include "DiskThread.h"
26  #include "Voice.h"  #include "Voice.h"
27    #include "EGADSR.h"
28    #include "../EngineFactory.h"
29    
30  #include "Engine.h"  #include "Engine.h"
31    
32  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
33    
34      InstrumentResourceManager Engine::Instruments;      InstrumentResourceManager Engine::instruments;
35    
36        std::map<AudioOutputDevice*,Engine*> Engine::engines;
37    
38        /**
39         * Get a gig::Engine object for the given gig::EngineChannel and the
40         * given AudioOutputDevice. All engine channels which are connected to
41         * the same audio output device will use the same engine instance. This
42         * method will be called by a gig::EngineChannel whenever it's
43         * connecting to a audio output device.
44         *
45         * @param pChannel - engine channel which acquires an engine object
46         * @param pDevice  - the audio output device \a pChannel is connected to
47         */
48        Engine* Engine::AcquireEngine(LinuxSampler::gig::EngineChannel* pChannel, AudioOutputDevice* pDevice) {
49            Engine* pEngine = NULL;
50            // check if there's already an engine for the given audio output device
51            if (engines.count(pDevice)) {
52                dmsg(4,("Using existing gig::Engine.\n"));
53                pEngine = engines[pDevice];
54            } else { // create a new engine (and disk thread) instance for the given audio output device
55                dmsg(4,("Creating new gig::Engine.\n"));
56                pEngine = (Engine*) EngineFactory::Create("gig");
57                pEngine->Connect(pDevice);
58                engines[pDevice] = pEngine;
59            }
60            // register engine channel to the engine instance
61            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()));
65            return pEngine;
66        }
67    
68        /**
69         * Once an engine channel is disconnected from an audio output device,
70         * it wil immediately call this method to unregister itself from the
71         * engine instance and if that engine instance is not used by any other
72         * engine channel anymore, then that engine instance will be destroyed.
73         *
74         * @param pChannel - engine channel which wants to disconnect from it's
75         *                   engine instance
76         * @param pDevice  - audio output device \a pChannel was connected to
77         */
78        void Engine::FreeEngine(LinuxSampler::gig::EngineChannel* pChannel, AudioOutputDevice* pDevice) {
79            dmsg(4,("Disconnecting EngineChannel from gig::Engine.\n"));
80            Engine* pEngine = engines[pDevice];
81            // unregister EngineChannel from the Engine instance
82            pEngine->engineChannels.remove(pChannel);
83            // if the used Engine instance is not used anymore, then destroy it
84            if (pEngine->engineChannels.empty()) {
85                pDevice->Disconnect(pEngine);
86                engines.erase(pDevice);
87                delete pEngine;
88                dmsg(4,("Destroying gig::Engine.\n"));
89            }
90            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() {
         pRIFF              = NULL;  
         pGig               = NULL;  
         pInstrument        = NULL;  
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 RTELMemoryPool<Event>(MAX_EVENTS_PER_FRAGMENT);          pEventPool         = new Pool<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT);
103          pVoicePool         = new RTELMemoryPool<Voice>(MAX_AUDIO_VOICES);          pVoicePool         = new Pool<Voice>(CONFIG_MAX_VOICES);
104          pActiveKeys        = new RTELMemoryPool<uint>(128);          pVoiceStealingQueue = new RTList<Event>(pEventPool);
105          pEvents            = new RTEList<Event>(pEventPool);          pGlobalEvents      = new RTList<Event>(pEventPool);
106          pCCEvents          = new RTEList<Event>(pEventPool);          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
107          for (uint i = 0; i < Event::destination_count; i++) {              iterVoice->SetEngine(this);
             pSynthesisEvents[i] = new RTEList<Event>(pEventPool);  
         }  
         for (uint i = 0; i < 128; i++) {  
             pMIDIKeyInfo[i].pActiveVoices  = new RTEList<Voice>(pVoicePool);  
             pMIDIKeyInfo[i].KeyPressed     = false;  
             pMIDIKeyInfo[i].Active         = false;  
             pMIDIKeyInfo[i].ReleaseTrigger = false;  
             pMIDIKeyInfo[i].pSelf          = NULL;  
             pMIDIKeyInfo[i].pEvents        = new RTEList<Event>(pEventPool);  
         }  
         for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {  
             pVoice->SetEngine(this);  
108          }          }
109          pVoicePool->clear();          pVoicePool->clear();
110    
         pSynthesisParameters[0] = NULL; // we allocate when an audio device is connected  
         pBasicFilterParameters  = NULL;  
         pMainFilterParameters   = NULL;  
   
         InstrumentIdx = -1;  
         InstrumentStat = -1;  
   
         AudioDeviceChannelLeft  = -1;  
         AudioDeviceChannelRight = -1;  
   
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..."));
121              pDiskThread->StopThread();              pDiskThread->StopThread();
122              delete pDiskThread;              delete pDiskThread;
123                dmsg(1,("OK\n"));
124          }          }
         if (pGig)  delete pGig;  
         if (pRIFF) delete pRIFF;  
         for (uint i = 0; i < 128; i++) {  
             if (pMIDIKeyInfo[i].pActiveVoices) delete pMIDIKeyInfo[i].pActiveVoices;  
             if (pMIDIKeyInfo[i].pEvents)       delete pMIDIKeyInfo[i].pEvents;  
         }  
         for (uint i = 0; i < Event::destination_count; i++) {  
             if (pSynthesisEvents[i]) delete pSynthesisEvents[i];  
         }  
         delete[] pSynthesisEvents;  
         if (pEvents)     delete pEvents;  
         if (pCCEvents)   delete pCCEvents;  
125          if (pEventQueue) delete pEventQueue;          if (pEventQueue) delete pEventQueue;
126          if (pEventPool)  delete pEventPool;          if (pEventPool)  delete pEventPool;
127          if (pVoicePool)  delete pVoicePool;          if (pVoicePool) {
128          if (pActiveKeys) delete pActiveKeys;              pVoicePool->clear();
129          if (pSysexBuffer) delete pSysexBuffer;              delete pVoicePool;
130            }
131          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
132          if (pMainFilterParameters) delete[] pMainFilterParameters;          if (pVoiceStealingQueue) delete pVoiceStealingQueue;
133          if (pBasicFilterParameters) delete[] pBasicFilterParameters;          if (pSysexBuffer) delete pSysexBuffer;
134          if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];          EngineFactory::Destroy(this);
135      }      }
136    
137      void Engine::Enable() {      void Engine::Enable() {
# Line 125  namespace LinuxSampler { namespace gig { Line 158  namespace LinuxSampler { namespace gig {
158       */       */
159      void Engine::Reset() {      void Engine::Reset() {
160          DisableAndLock();          DisableAndLock();
   
         //if (pAudioOutputDevice->IsPlaying()) { // if already running  
             /*  
             // signal audio thread not to enter render part anymore  
             SuspensionRequested = true;  
             // sleep until wakened by audio thread  
             pthread_mutex_lock(&__render_state_mutex);  
             pthread_cond_wait(&__render_exit_condition, &__render_state_mutex);  
             pthread_mutex_unlock(&__render_state_mutex);  
             */  
         //}  
   
         //if (wasplaying) pAudioOutputDevice->Stop();  
   
161          ResetInternal();          ResetInternal();
162            ResetScaleTuning();
         // signal audio thread to continue with rendering  
         //SuspensionRequested = false;  
163          Enable();          Enable();
164      }      }
165    
# Line 151  namespace LinuxSampler { namespace gig { Line 168  namespace LinuxSampler { namespace gig {
168       *  control and status variables. This method is not thread safe!       *  control and status variables. This method is not thread safe!
169       */       */
170      void Engine::ResetInternal() {      void Engine::ResetInternal() {
         Pitch               = 0;  
         SustainPedal        = false;  
171          ActiveVoiceCount    = 0;          ActiveVoiceCount    = 0;
172          ActiveVoiceCountMax = 0;          ActiveVoiceCountMax = 0;
         GlobalVolume        = 1.0;  
   
         // reset to normal chromatic scale (means equal temper)  
         memset(&ScaleTuning[0], 0x00, 12);  
173    
174          // set all MIDI controller values to zero          // reset voice stealing parameters
175          memset(ControllerTable, 0x00, 128);          pVoiceStealingQueue->clear();
176            itLastStolenVoice          = RTList<Voice>::Iterator();
177          // reset key info          itLastStolenVoiceGlobally  = RTList<Voice>::Iterator();
178          for (uint i = 0; i < 128; i++) {          iuiLastStolenKey           = RTList<uint>::Iterator();
179              pMIDIKeyInfo[i].pActiveVoices->clear();          iuiLastStolenKeyGlobally   = RTList<uint>::Iterator();
180              pMIDIKeyInfo[i].pEvents->clear();          pLastStolenChannel         = NULL;
             pMIDIKeyInfo[i].KeyPressed     = false;  
             pMIDIKeyInfo[i].Active         = false;  
             pMIDIKeyInfo[i].ReleaseTrigger = false;  
             pMIDIKeyInfo[i].pSelf          = NULL;  
         }  
   
         // reset all key groups  
         map<uint,uint*>::iterator iter = ActiveKeyGroups.begin();  
         for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;  
181    
182          // reset all voices          // reset all voices
183          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
184              pVoice->Reset();              iterVoice->Reset();
185          }          }
186          pVoicePool->clear();          pVoicePool->clear();
187    
         // free all active keys  
         pActiveKeys->clear();  
   
188          // reset disk thread          // reset disk thread
189          if (pDiskThread) pDiskThread->Reset();          if (pDiskThread) pDiskThread->Reset();
190    
191          // delete all input events          // delete all input events
192          pEventQueue->init();          pEventQueue->init();
193            pSysexBuffer->init();
194      }      }
195    
196      /**      /**
197       *  Load an instrument from a .gig file.       * Reset to normal, chromatic scale (means equal tempered).
      *  
      *  @param FileName   - file name of the Gigasampler instrument file  
      *  @param Instrument - index of the instrument in the .gig file  
      *  @throws LinuxSamplerException  on error  
      *  @returns          detailed description of the method call result  
      */  
     void Engine::LoadInstrument(const char* FileName, uint Instrument) {  
   
         DisableAndLock();  
   
         ResetInternal(); // reset engine  
   
         // free old instrument  
         if (pInstrument) {  
             // give old instrument back to instrument manager  
             Instruments.HandBack(pInstrument, this);  
         }  
   
         InstrumentFile = FileName;  
         InstrumentIdx = Instrument;  
         InstrumentStat = 0;  
   
         // delete all key groups  
         ActiveKeyGroups.clear();  
   
         // request gig instrument from instrument manager  
         try {  
             instrument_id_t instrid;  
             instrid.FileName    = FileName;  
             instrid.iInstrument = Instrument;  
             pInstrument = Instruments.Borrow(instrid, this);  
             if (!pInstrument) {  
                 InstrumentStat = -1;  
                 dmsg(1,("no instrument loaded!!!\n"));  
                 exit(EXIT_FAILURE);  
             }  
         }  
         catch (RIFF::Exception e) {  
             InstrumentStat = -2;  
             String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;  
             throw LinuxSamplerException(msg);  
         }  
         catch (InstrumentResourceManagerException e) {  
             InstrumentStat = -3;  
             String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();  
             throw LinuxSamplerException(msg);  
         }  
         catch (...) {  
             InstrumentStat = -4;  
             throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");  
         }  
   
         // rebuild ActiveKeyGroups map with key groups of current instrument  
         for (::gig::Region* pRegion = pInstrument->GetFirstRegion(); pRegion; pRegion = pInstrument->GetNextRegion())  
             if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL;  
   
         InstrumentStat = 100;  
   
         // inform audio driver for the need of two channels  
         try {  
             if (pAudioOutputDevice) pAudioOutputDevice->AcquireChannels(2); // gig Engine only stereo  
         }  
         catch (AudioOutputException e) {  
             String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();  
             throw LinuxSamplerException(msg);  
         }  
   
         Enable();  
     }  
   
     /**  
      * Will be called by the InstrumentResourceManager when the instrument  
      * we are currently using in this engine is going to be updated, so we  
      * can stop playback before that happens.  
198       */       */
199      void Engine::ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {      void Engine::ResetScaleTuning() {
200          dmsg(3,("gig::Engine: Received instrument update message.\n"));          memset(&ScaleTuning[0], 0x00, 12);
         DisableAndLock();  
         ResetInternal();  
         this->pInstrument = NULL;  
201      }      }
202    
203      /**      /**
204       * Will be called by the InstrumentResourceManager when the instrument       * Connect this engine instance with the given audio output device.
205       * update process was completed, so we can continue with playback.       * 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       */       */
     void Engine::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {  
         this->pInstrument = pNewResource; //TODO: there are couple of engine parameters we should update here as well if the instrument was updated (see LoadInstrument())  
         Enable();  
     }  
   
212      void Engine::Connect(AudioOutputDevice* pAudioOut) {      void Engine::Connect(AudioOutputDevice* pAudioOut) {
213          pAudioOutputDevice = pAudioOut;          pAudioOutputDevice = pAudioOut;
214    
# Line 300  namespace LinuxSampler { namespace gig { Line 223  namespace LinuxSampler { namespace gig {
223              throw LinuxSamplerException(msg);              throw LinuxSamplerException(msg);
224          }          }
225    
226          this->AudioDeviceChannelLeft  = 0;          this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle();
227          this->AudioDeviceChannelRight = 1;          this->SampleRate         = pAudioOutputDevice->SampleRate();
228          this->pOutputLeft             = pAudioOutputDevice->Channel(0)->Buffer();  
229          this->pOutputRight            = pAudioOutputDevice->Channel(1)->Buffer();          // FIXME: audio drivers with varying fragment sizes might be a problem here
230          this->MaxSamplesPerCycle      = pAudioOutputDevice->MaxSamplesPerCycle();          MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * CONFIG_EG_MIN_RELEASE_TIME) - 1;
231          this->SampleRate              = pAudioOutputDevice->SampleRate();          if (MaxFadeOutPos < 0) {
232                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) {
247                dmsg(1,("Stopping disk thread..."));
248              this->pDiskThread->StopThread();              this->pDiskThread->StopThread();
249              delete this->pDiskThread;              delete this->pDiskThread;
250                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);
256          }          }
257    
258          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
259              pVoice->pDiskThread = this->pDiskThread;              iterVoice->pDiskThread = this->pDiskThread;
260              dmsg(3,("d"));              dmsg(3,("d"));
261          }          }
262          pVoicePool->clear();          pVoicePool->clear();
# Line 328  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]) delete[] pSynthesisParameters[0];  
         pSynthesisParameters[0] = new float[Event::destination_count * pAudioOut->MaxSamplesPerCycle()];  
         for (int dst = 1; dst < Event::destination_count; dst++)  
             pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();  
   
         // (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"));
271    
272          for (Voice* pVoice = pVoicePool->first(); pVoice; pVoice = pVoicePool->next()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
273              if (!pVoice->pDiskThread) {              if (!iterVoice->pDiskThread) {
274                  dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));                  dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));
275                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
276              }              }
277          }          }
278      }      }
279    
280      void Engine::DisconnectAudioOutputDevice() {      /**
281          if (pAudioOutputDevice) { // if clause to prevent disconnect loops       * Clear all engine global event lists.
282              AudioOutputDevice* olddevice = pAudioOutputDevice;       */
283              pAudioOutputDevice = NULL;      void Engine::ClearEventLists() {
284              olddevice->Disconnect(this);          pGlobalEvents->clear();
285              AudioDeviceChannelLeft  = -1;      }
286              AudioDeviceChannelRight = -1;  
287        /**
288         * Copy all events from the engine's global input queue buffer to the
289         * engine's internal event list. This will be done at the beginning of
290         * each audio cycle (that is each RenderAudio() call) to distinguish
291         * all global events which have to be processed in the current audio
292         * cycle. These events are usually just SysEx messages. Every
293         * EngineChannel has it's own input event queue buffer and event list
294         * to handle common events like NoteOn, NoteOff and ControlChange
295         * events.
296         *
297         * @param Samples - number of sample points to be processed in the
298         *                  current audio cycle
299         */
300        void Engine::ImportEvents(uint Samples) {
301            RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
302            Event* pEvent;
303            while (true) {
304                // get next event from input event queue
305                if (!(pEvent = eventQueueReader.pop())) break;
306                // if younger event reached, ignore that and all subsequent ones for now
307                if (pEvent->FragmentPos() >= Samples) {
308                    eventQueueReader--;
309                    dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
310                    pEvent->ResetFragmentPos();
311                    break;
312                }
313                // copy event to internal event list
314                if (pGlobalEvents->poolIsEmpty()) {
315                    dmsg(1,("Event pool emtpy!\n"));
316                    break;
317                }
318                *pGlobalEvents->allocAppend() = *pEvent;
319          }          }
320            eventQueueReader.free(); // free all copied events from input queue
321      }      }
322    
323      /**      /**
# Line 375  namespace LinuxSampler { namespace gig { Line 333  namespace LinuxSampler { namespace gig {
333      int Engine::RenderAudio(uint Samples) {      int Engine::RenderAudio(uint Samples) {
334          dmsg(5,("RenderAudio(Samples=%d)\n", Samples));          dmsg(5,("RenderAudio(Samples=%d)\n", Samples));
335    
336          // return if no instrument loaded or engine disabled          // return if engine disabled
337          if (EngineDisabled.Pop()) {          if (EngineDisabled.Pop()) {
338              dmsg(5,("gig::Engine: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));              dmsg(5,("gig::Engine: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));
339              return 0;              return 0;
340          }          }
         if (!pInstrument) {  
             dmsg(5,("gig::Engine: no instrument loaded\n"));  
             return 0;  
         }  
341    
342            // update time of start and end of this audio fragment (as events' time stamps relate to this)
343            pEventGenerator->UpdateFragmentTime(Samples);
344    
345          // empty the event lists for the new fragment          // We only allow a maximum of CONFIG_MAX_VOICES voices to be spawned
346          pEvents->clear();          // in each audio fragment. All subsequent request for spawning new
347          pCCEvents->clear();          // voices in the same audio fragment will be ignored.
348          for (uint i = 0; i < Event::destination_count; i++) {          VoiceSpawnsLeft = CONFIG_MAX_VOICES;
349              pSynthesisEvents[i]->clear();  
350            // get all events from the engine's global input event queue which belong to the current fragment
351            // (these are usually just SysEx messages)
352            ImportEvents(Samples);
353    
354            // process engine global events (these are currently only MIDI System Exclusive messages)
355            {
356                RTList<Event>::Iterator itEvent = pGlobalEvents->first();
357                RTList<Event>::Iterator end     = pGlobalEvents->end();
358                for (; itEvent != end; ++itEvent) {
359                    switch (itEvent->Type) {
360                        case Event::type_sysex:
361                            dmsg(5,("Engine: Sysex received\n"));
362                            ProcessSysex(itEvent);
363                            break;
364                    }
365                }
366          }          }
367    
368          // read and copy events from input queue          // reset internal voice counter (just for statistic of active voices)
369          Event event = pEventGenerator->CreateEvent();          ActiveVoiceCountTemp = 0;
         while (true) {  
             if (!pEventQueue->pop(&event)) break;  
             pEvents->alloc_assign(event);  
         }  
370    
371            // handle events on all engine channels
372            for (int i = 0; i < engineChannels.size(); i++) {
373                if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
374                ProcessEvents(engineChannels[i], Samples);
375            }
376    
377          // update time of start and end of this audio fragment (as events' time stamps relate to this)          // render all 'normal', active voices on all engine channels
378          pEventGenerator->UpdateFragmentTime(Samples);          for (int i = 0; i < engineChannels.size(); i++) {
379                if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
380                RenderActiveVoices(engineChannels[i], Samples);
381            }
382    
383            // now that all ordinary voices on ALL engine channels are rendered, render new stolen voices
384            RenderStolenVoices(Samples);
385    
386          // process events          // handle cleanup on all engine channels for the next audio fragment
387          Event* pNextEvent = pEvents->first();          for (int i = 0; i < engineChannels.size(); i++) {
388          while (pNextEvent) {              if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
389              Event* pEvent = pNextEvent;              PostProcess(engineChannels[i]);
             pEvents->set_current(pEvent);  
             pNextEvent = pEvents->next();  
             switch (pEvent->Type) {  
                 case Event::type_note_on:  
                     dmsg(5,("Engine: Note on received\n"));  
                     ProcessNoteOn(pEvent);  
                     break;  
                 case Event::type_note_off:  
                     dmsg(5,("Engine: Note off received\n"));  
                     ProcessNoteOff(pEvent);  
                     break;  
                 case Event::type_control_change:  
                     dmsg(5,("Engine: MIDI CC received\n"));  
                     ProcessControlChange(pEvent);  
                     break;  
                 case Event::type_pitchbend:  
                     dmsg(5,("Engine: Pitchbend received\n"));  
                     ProcessPitchbend(pEvent);  
                     break;  
                 case Event::type_sysex:  
                     dmsg(5,("Engine: Sysex received\n"));  
                     ProcessSysex(pEvent);  
                     break;  
             }  
390          }          }
391    
392    
393          // render audio from all active voices          // empty the engine's event list for the next audio fragment
394          int active_voices = 0;          ClearEventLists();
         uint* piKey = pActiveKeys->first();  
         while (piKey) { // iterate through all active keys  
             midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];  
             pActiveKeys->set_current(piKey);  
             piKey = pActiveKeys->next();  
   
             Voice* pVoiceNext = pKey->pActiveVoices->first();  
             while (pVoiceNext) { // iterate through all voices on this key  
                 // already get next voice on key  
                 Voice* pVoice = pVoiceNext;  
                 pKey->pActiveVoices->set_current(pVoice);  
                 pVoiceNext = pKey->pActiveVoices->next();  
   
                 // now render current voice  
                 pVoice->Render(Samples);  
                 if (pVoice->IsActive()) active_voices++; // still active  
                 else { // voice reached end, is now inactive  
                     KillVoiceImmediately(pVoice); // remove voice from the list of active voices  
                 }  
             }  
             pKey->pEvents->clear(); // free all events on the key  
         }  
395    
396            // reset voice stealing for the next audio fragment
397            pVoiceStealingQueue->clear();
398    
399          // write that to the disk thread class so that it can print it          // just some statistics about this engine instance
400          // on the console for debugging purposes          ActiveVoiceCount = ActiveVoiceCountTemp;
         ActiveVoiceCount = active_voices;  
401          if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;          if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;
402    
403            FrameTime += Samples;
404    
405          return 0;          return 0;
406      }      }
407    
408      /**      /**
409       *  Will be called by the MIDIIn Thread to let the audio thread trigger a new       * Dispatch and handle all events in this audio fragment for the given
410       *  voice for the given key.       * engine channel.
411       *       *
412       *  @param Key      - MIDI key number of the triggered key       * @param pEngineChannel - engine channel on which events should be
413       *  @param Velocity - MIDI velocity value of the triggered key       *                         processed
414       */       * @param Samples        - amount of sample points to be processed in
415      void Engine::SendNoteOn(uint8_t Key, uint8_t Velocity) {       *                         this audio fragment cycle
416          Event event               = pEventGenerator->CreateEvent();       */
417          event.Type                = Event::type_note_on;      void Engine::ProcessEvents(EngineChannel* pEngineChannel, uint Samples) {
418          event.Param.Note.Key      = Key;          // get all events from the engine channels's input event queue which belong to the current fragment
419          event.Param.Note.Velocity = Velocity;          // (these are the common events like NoteOn, NoteOff, ControlChange, etc.)
420          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          pEngineChannel->ImportEvents(Samples);
421          else dmsg(1,("Engine: Input event queue full!"));  
422            // process events
423            {
424                RTList<Event>::Iterator itEvent = pEngineChannel->pEvents->first();
425                RTList<Event>::Iterator end     = pEngineChannel->pEvents->end();
426                for (; itEvent != end; ++itEvent) {
427                    switch (itEvent->Type) {
428                        case Event::type_note_on:
429                            dmsg(5,("Engine: Note on received\n"));
430                            ProcessNoteOn((EngineChannel*)itEvent->pEngineChannel, itEvent);
431                            break;
432                        case Event::type_note_off:
433                            dmsg(5,("Engine: Note off received\n"));
434                            ProcessNoteOff((EngineChannel*)itEvent->pEngineChannel, itEvent);
435                            break;
436                        case Event::type_control_change:
437                            dmsg(5,("Engine: MIDI CC received\n"));
438                            ProcessControlChange((EngineChannel*)itEvent->pEngineChannel, itEvent);
439                            break;
440                        case Event::type_pitchbend:
441                            dmsg(5,("Engine: Pitchbend received\n"));
442                            ProcessPitchbend((EngineChannel*)itEvent->pEngineChannel, itEvent);
443                            break;
444                    }
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      /**      /**
457       *  Will be called by the MIDIIn Thread to signal the audio thread to release       * Render all 'normal' voices (that is voices which were not stolen in
458       *  voice(s) on the given key.       * this fragment) on the given engine channel.
459       *       *
460       *  @param Key      - MIDI key number of the released key       * @param pEngineChannel - engine channel on which audio should be
461       *  @param Velocity - MIDI release velocity value of the released key       *                         rendered
462       */       * @param Samples        - amount of sample points to be rendered in
463      void Engine::SendNoteOff(uint8_t Key, uint8_t Velocity) {       *                         this audio fragment cycle
464          Event event               = pEventGenerator->CreateEvent();       */
465          event.Type                = Event::type_note_off;      void Engine::RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {
466          event.Param.Note.Key      = Key;          #if !CONFIG_PROCESS_MUTED_CHANNELS
467          event.Param.Note.Velocity = Velocity;          if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
468          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          #endif
469          else dmsg(1,("Engine: Input event queue full!"));  
470            RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
471            RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
472            while (iuiKey != end) { // iterate through all active keys
473                midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
474                ++iuiKey;
475    
476                RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
477                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       *  Will be called by the MIDIIn Thread to signal the audio thread to change       * Render all stolen voices (only voices which were stolen in this
491       *  the pitch value for all voices.       * fragment) on the given engine channel. Stolen voices are rendered
492         * after all normal voices have been rendered; this is needed to render
493         * audio of those voices which were selected for voice stealing until
494         * the point were the stealing (that is the take over of the voice)
495         * actually happened.
496       *       *
497       *  @param Pitch - MIDI pitch value (-8192 ... +8191)       * @param pEngineChannel - engine channel on which audio should be
498       */       *                         rendered
499      void Engine::SendPitchbend(int Pitch) {       * @param Samples        - amount of sample points to be rendered in
500          Event event             = pEventGenerator->CreateEvent();       *                         this audio fragment cycle
501          event.Type              = Event::type_pitchbend;       */
502          event.Param.Pitch.Pitch = Pitch;      void Engine::RenderStolenVoices(uint Samples) {
503          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();
504          else dmsg(1,("Engine: Input event queue full!"));          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                    }
515                }
516                else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));
517    
518                // we need to clear the key's event list explicitly here in case key was never active
519                midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itVoiceStealEvent->Param.Note.Key];
520                pKey->VoiceTheftsQueued--;
521                if (!pKey->Active && !pKey->VoiceTheftsQueued) pKey->pEvents->clear();
522            }
523      }      }
524    
525      /**      /**
526       *  Will be called by the MIDIIn Thread to signal the audio thread that a       * Free all keys which have turned inactive in this audio fragment, from
527       *  continuous controller value has changed.       * the list of active keys and clear all event lists on that engine
528         * channel.
529       *       *
530       *  @param Controller - MIDI controller number of the occured control change       * @param pEngineChannel - engine channel to cleanup
      *  @param Value      - value of the control change  
531       */       */
532      void Engine::SendControlChange(uint8_t Controller, uint8_t Value) {      void Engine::PostProcess(EngineChannel* pEngineChannel) {
533          Event event               = pEventGenerator->CreateEvent();          // free all keys which have no active voices left
534          event.Type                = Event::type_control_change;          {
535          event.Param.CC.Controller = Controller;              RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
536          event.Param.CC.Value      = Value;              RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
537          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);              while (iuiKey != end) { // iterate through all active keys
538          else dmsg(1,("Engine: Input event queue full!"));                  midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
539                    ++iuiKey;
540                    if (pKey->pActiveVoices->isEmpty()) FreeKey(pEngineChannel, pKey);
541                    #if CONFIG_DEVMODE
542                    else { // just a sanity check for debugging
543                        RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
544                        RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
545                        for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
546                            if (itVoice->itKillEvent) {
547                                dmsg(1,("gig::Engine: ERROR, killed voice survived !!!\n"));
548                            }
549                        }
550                    }
551                    #endif // CONFIG_DEVMODE
552                }
553            }
554    
555            // empty the engine channel's own event lists
556            pEngineChannel->ClearEventLists();
557      }      }
558    
559      /**      /**
# Line 544  namespace LinuxSampler { namespace gig { Line 567  namespace LinuxSampler { namespace gig {
567          Event event             = pEventGenerator->CreateEvent();          Event event             = pEventGenerator->CreateEvent();
568          event.Type              = Event::type_sysex;          event.Type              = Event::type_sysex;
569          event.Param.Sysex.Size  = Size;          event.Param.Sysex.Size  = Size;
570            event.pEngineChannel    = NULL; // as Engine global event
571          if (pEventQueue->write_space() > 0) {          if (pEventQueue->write_space() > 0) {
572              if (pSysexBuffer->write_space() >= Size) {              if (pSysexBuffer->write_space() >= Size) {
573                  // copy sysex data to input buffer                  // copy sysex data to input buffer
# Line 559  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 567  namespace LinuxSampler { namespace gig { Line 591  namespace LinuxSampler { namespace gig {
591      /**      /**
592       *  Assigns and triggers a new voice for the respective MIDI key.       *  Assigns and triggers a new voice for the respective MIDI key.
593       *       *
594       *  @param pNoteOnEvent - key, velocity and time stamp of the event       *  @param pEngineChannel - engine channel on which this event occured on
595         *  @param itNoteOnEvent - key, velocity and time stamp of the event
596       */       */
597      void Engine::ProcessNoteOn(Event* pNoteOnEvent) {      void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
598          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Param.Note.Key];          #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;
603            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];
604    
605            // move note on event to the key's own event list
606            RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
607    
608            // if Solo Mode then kill all already active voices
609            if (pEngineChannel->SoloMode) {
610                Pool<uint>::Iterator itYoungestKey = pEngineChannel->pActiveKeys->last();
611                if (itYoungestKey) {
612                    const int iYoungestKey = *itYoungestKey;
613                    const midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[iYoungestKey];
614                    if (pOtherKey->Active) {
615                        // get final portamento position of currently active voice
616                        if (pEngineChannel->PortamentoMode) {
617                            RTList<Voice>::Iterator itVoice = pOtherKey->pActiveVoices->last();
618                            if (itVoice) itVoice->UpdatePortamentoPos(itNoteOnEventOnKeyList);
619                        }
620                        // kill all voices on the (other) key
621                        RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
622                        RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
623                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
624                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger)
625                                itVoiceToBeKilled->Kill(itNoteOnEventOnKeyList);
626                        }
627                    }
628                }
629                // set this key as 'currently active solo key'
630                pEngineChannel->SoloKey = key;
631            }
632    
633            // Change key dimension value if key is in keyswitching area
634            {
635                const ::gig::Instrument* pInstrument = pEngineChannel->pInstrument;
636                if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high)
637                    pEngineChannel->CurrentKeyDimension = ((key - pInstrument->DimensionKeyRange.low) * 128) /
638                        (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);
639            }
640    
641          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
642            pKey->Velocity   = itNoteOnEventOnKeyList->Param.Note.Velocity;
643            pKey->NoteOnTime = FrameTime + itNoteOnEventOnKeyList->FragmentPos(); // will be used to calculate note length
644    
645          // cancel release process of voices on this key if needed          // cancel release process of voices on this key if needed
646          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !pEngineChannel->SustainPedal) {
647              Event* pCancelReleaseEvent = pKey->pEvents->alloc();              RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
648              if (pCancelReleaseEvent) {              if (itCancelReleaseEvent) {
649                  *pCancelReleaseEvent = *pNoteOnEvent;                  *itCancelReleaseEvent = *itNoteOnEventOnKeyList;         // copy event
650                  pCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type                  itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type
651              }              }
652              else dmsg(1,("Event pool emtpy!\n"));              else dmsg(1,("Event pool emtpy!\n"));
653          }          }
654    
655          // allocate and trigger a new voice for the key          // allocate and trigger new voice(s) for the key
656          LaunchVoice(pNoteOnEvent);          {
657                // first, get total amount of required voices (dependant on amount of layers)
658                ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOnEventOnKeyList->Param.Note.Key);
659                if (pRegion) {
660                    int voicesRequired = pRegion->Layers;
661                    // now launch the required amount of voices
662                    for (int i = 0; i < voicesRequired; i++)
663                        LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true, true);
664                }
665            }
666    
667            // if neither a voice was spawned or postponed then remove note on event from key again
668            if (!pKey->Active && !pKey->VoiceTheftsQueued)
669                pKey->pEvents->free(itNoteOnEventOnKeyList);
670    
671          // finally move note on event to the key's own event list          if (!pEngineChannel->SoloMode || pEngineChannel->PortamentoPos < 0.0f) pEngineChannel->PortamentoPos = (float) key;
672          pEvents->move(pNoteOnEvent, pKey->pEvents);          pKey->RoundRobinIndex++;
673      }      }
674    
675      /**      /**
# Line 597  namespace LinuxSampler { namespace gig { Line 678  namespace LinuxSampler { namespace gig {
678       *  sustain pedal will be released or voice turned inactive by itself (e.g.       *  sustain pedal will be released or voice turned inactive by itself (e.g.
679       *  due to completion of sample playback).       *  due to completion of sample playback).
680       *       *
681       *  @param pNoteOffEvent - key, velocity and time stamp of the event       *  @param pEngineChannel - engine channel on which this event occured on
682         *  @param itNoteOffEvent - key, velocity and time stamp of the event
683       */       */
684      void Engine::ProcessNoteOff(Event* pNoteOffEvent) {      void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {
685          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOffEvent->Param.Note.Key];          #if !CONFIG_PROCESS_MUTED_CHANNELS
686            if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
687            #endif
688    
689            const int iKey = itNoteOffEvent->Param.Note.Key;
690            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[iKey];
691          pKey->KeyPressed = false; // the MIDI key was now released          pKey->KeyPressed = false; // the MIDI key was now released
692    
693          // release voices on this key if needed          // move event to the key's own event list
694          if (pKey->Active && !SustainPedal) {          RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
695              pNoteOffEvent->Type = Event::type_release; // transform event type  
696            bool bShouldRelease = pKey->Active && ShouldReleaseVoice(pEngineChannel, itNoteOffEventOnKeyList->Param.Note.Key);
697    
698            // in case Solo Mode is enabled, kill all voices on this key and respawn a voice on the highest pressed key (if any)
699            if (pEngineChannel->SoloMode) { //TODO: this feels like too much code just for handling solo mode :P
700                bool bOtherKeysPressed = false;
701                if (iKey == pEngineChannel->SoloKey) {
702                    pEngineChannel->SoloKey = -1;
703                    // if there's still a key pressed down, respawn a voice (group) on the highest key
704                    for (int i = 127; i > 0; i--) {
705                        midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[i];
706                        if (pOtherKey->KeyPressed) {
707                            bOtherKeysPressed = true;
708                            // make the other key the new 'currently active solo key'
709                            pEngineChannel->SoloKey = i;
710                            // get final portamento position of currently active voice
711                            if (pEngineChannel->PortamentoMode) {
712                                RTList<Voice>::Iterator itVoice = pKey->pActiveVoices->first();
713                                if (itVoice) itVoice->UpdatePortamentoPos(itNoteOffEventOnKeyList);
714                            }
715                            // create a pseudo note on event
716                            RTList<Event>::Iterator itPseudoNoteOnEvent = pOtherKey->pEvents->allocAppend();
717                            if (itPseudoNoteOnEvent) {
718                                // copy event
719                                *itPseudoNoteOnEvent = *itNoteOffEventOnKeyList;
720                                // transform event to a note on event
721                                itPseudoNoteOnEvent->Type                = Event::type_note_on;
722                                itPseudoNoteOnEvent->Param.Note.Key      = i;
723                                itPseudoNoteOnEvent->Param.Note.Velocity = pOtherKey->Velocity;
724                                // allocate and trigger new voice(s) for the other key
725                                {
726                                    // first, get total amount of required voices (dependant on amount of layers)
727                                    ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(i);
728                                    if (pRegion) {
729                                        int voicesRequired = pRegion->Layers;
730                                        // now launch the required amount of voices
731                                        for (int iLayer = 0; iLayer < voicesRequired; iLayer++)
732                                            LaunchVoice(pEngineChannel, itPseudoNoteOnEvent, iLayer, false, true, false);
733                                    }
734                                }
735                                // if neither a voice was spawned or postponed then remove note on event from key again
736                                if (!pOtherKey->Active && !pOtherKey->VoiceTheftsQueued)
737                                    pOtherKey->pEvents->free(itPseudoNoteOnEvent);
738    
739                            } else dmsg(1,("Could not respawn voice, no free event left\n"));
740                            break; // done
741                        }
742                    }
743                }
744                if (bOtherKeysPressed) {
745                    if (pKey->Active) { // kill all voices on this key
746                        bShouldRelease = false; // no need to release, as we kill it here
747                        RTList<Voice>::Iterator itVoiceToBeKilled = pKey->pActiveVoices->first();
748                        RTList<Voice>::Iterator end               = pKey->pActiveVoices->end();
749                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
750                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger)
751                                itVoiceToBeKilled->Kill(itNoteOffEventOnKeyList);
752                        }
753                    }
754                } else pEngineChannel->PortamentoPos = -1.0f;
755          }          }
756    
757          // spawn release triggered voice(s) if needed          // if no solo mode (the usual case) or if solo mode and no other key pressed, then release voices on this key if needed
758          if (pKey->ReleaseTrigger) {          if (bShouldRelease) {
759              LaunchVoice(pNoteOffEvent, 0, true);              itNoteOffEventOnKeyList->Type = Event::type_release; // transform event type
760              pKey->ReleaseTrigger = false;  
761                // spawn release triggered voice(s) if needed
762                if (pKey->ReleaseTrigger) {
763                    // first, get total amount of required voices (dependant on amount of layers)
764                    ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOffEventOnKeyList->Param.Note.Key);
765                    if (pRegion) {
766                        int voicesRequired = pRegion->Layers;
767    
768                        // MIDI note-on velocity is used instead of note-off velocity
769                        itNoteOffEventOnKeyList->Param.Note.Velocity = pKey->Velocity;
770    
771                        // now launch the required amount of voices
772                        for (int i = 0; i < voicesRequired; i++)
773                            LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, i, true, false, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
774                    }
775                    pKey->ReleaseTrigger = false;
776                }
777          }          }
778    
779          // move event to the key's own event list          // if neither a voice was spawned or postponed on this key then remove note off event from key again
780          pEvents->move(pNoteOffEvent, pKey->pEvents);          if (!pKey->Active && !pKey->VoiceTheftsQueued)
781                pKey->pEvents->free(itNoteOffEventOnKeyList);
782      }      }
783    
784      /**      /**
785       *  Moves pitchbend event from the general (input) event list to the pitch       *  Moves pitchbend event from the general (input) event list to the engine
786       *  event list.       *  channel's event list. It will actually processed later by the
787         *  respective voice.
788       *       *
789       *  @param pPitchbendEvent - absolute pitch value and time stamp of the event       *  @param pEngineChannel - engine channel on which this event occured on
790         *  @param itPitchbendEvent - absolute pitch value and time stamp of the event
791       */       */
792      void Engine::ProcessPitchbend(Event* pPitchbendEvent) {      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {
793          this->Pitch = pPitchbendEvent->Param.Pitch.Pitch; // store current pitch value          pEngineChannel->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value
         pEvents->move(pPitchbendEvent, pSynthesisEvents[Event::destination_vco]);  
794      }      }
795    
796      /**      /**
# Line 635  namespace LinuxSampler { namespace gig { Line 798  namespace LinuxSampler { namespace gig {
798       *  called by the ProcessNoteOn() method and by the voices itself       *  called by the ProcessNoteOn() method and by the voices itself
799       *  (e.g. to spawn further voices on the same key for layered sounds).       *  (e.g. to spawn further voices on the same key for layered sounds).
800       *       *
801       *  @param pNoteOnEvent        - key, velocity and time stamp of the event       *  @param pEngineChannel      - engine channel on which this event occured on
802         *  @param itNoteOnEvent       - key, velocity and time stamp of the event
803       *  @param iLayer              - layer index for the new voice (optional - only       *  @param iLayer              - layer index for the new voice (optional - only
804       *                               in case of layered sounds of course)       *                               in case of layered sounds of course)
805       *  @param ReleaseTriggerVoice - if new voice is a release triggered voice       *  @param ReleaseTriggerVoice - if new voice is a release triggered voice
806       *                               (optional, default = false)       *                               (optional, default = false)
807       */       *  @param VoiceStealing       - if voice stealing should be performed
808      void Engine::LaunchVoice(Event* pNoteOnEvent, int iLayer, bool ReleaseTriggerVoice) {       *                               when there is no free voice
809          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Param.Note.Key];       *                               (optional, default = true)
810         *  @param HandleKeyGroupConflicts - if voices should be killed due to a
811         *                                   key group conflict
812         *  @returns pointer to new voice or NULL if there was no free voice or
813         *           if the voice wasn't triggered (for example when no region is
814         *           defined for the given key).
815         */
816        Pool<Voice>::Iterator Engine::LaunchVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing, bool HandleKeyGroupConflicts) {
817            int MIDIKey            = itNoteOnEvent->Param.Note.Key;
818            midi_key_info_t* pKey  = &pEngineChannel->pMIDIKeyInfo[MIDIKey];
819            ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(MIDIKey);
820    
821            // if nothing defined for this key
822            if (!pRegion) return Pool<Voice>::Iterator(); // nothing to do
823    
824            // only mark the first voice of a layered voice (group) to be in a
825            // key group, so the layered voices won't kill each other
826            int iKeyGroup = (iLayer == 0 && !ReleaseTriggerVoice) ? pRegion->KeyGroup : 0;
827    
828            // handle key group (a.k.a. exclusive group) conflicts
829            if (HandleKeyGroupConflicts) {
830                if (iKeyGroup) { // if this voice / key belongs to a key group
831                    uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[iKeyGroup];
832                    if (*ppKeyGroup) { // if there's already an active key in that key group
833                        midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[**ppKeyGroup];
834                        // kill all voices on the (other) key
835                        RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
836                        RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
837                        for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
838                            if (itVoiceToBeKilled->Type != Voice::type_release_trigger) {
839                                itVoiceToBeKilled->Kill(itNoteOnEvent);
840                                --VoiceSpawnsLeft; //FIXME: just a hack, we should better check in StealVoice() if the voice was killed due to key conflict
841                            }
842                        }
843                    }
844                }
845            }
846    
847            Voice::type_t VoiceType = Voice::type_normal;
848    
849            // get current dimension values to select the right dimension region
850            //TODO: for stolen voices this dimension region selection block is processed twice, this should be changed
851            //FIXME: controller values for selecting the dimension region here are currently not sample accurate
852            uint DimValues[8] = { 0 };
853            for (int i = pRegion->Dimensions - 1; i >= 0; i--) {
854                switch (pRegion->pDimensionDefinitions[i].dimension) {
855                    case ::gig::dimension_samplechannel:
856                        DimValues[i] = 0; //TODO: we currently ignore this dimension
857                        break;
858                    case ::gig::dimension_layer:
859                        DimValues[i] = iLayer;
860                        break;
861                    case ::gig::dimension_velocity:
862                        DimValues[i] = itNoteOnEvent->Param.Note.Velocity;
863                        break;
864                    case ::gig::dimension_channelaftertouch:
865                        DimValues[i] = 0; //TODO: we currently ignore this dimension
866                        break;
867                    case ::gig::dimension_releasetrigger:
868                        VoiceType = (ReleaseTriggerVoice) ? Voice::type_release_trigger : (!iLayer) ? Voice::type_release_trigger_required : Voice::type_normal;
869                        DimValues[i] = (uint) ReleaseTriggerVoice;
870                        break;
871                    case ::gig::dimension_keyboard:
872                        DimValues[i] = (uint) pEngineChannel->CurrentKeyDimension;
873                        break;
874                    case ::gig::dimension_roundrobin:
875                        DimValues[i] = (uint) pEngineChannel->pMIDIKeyInfo[MIDIKey].RoundRobinIndex; // incremented for each note on
876                        break;
877                    case ::gig::dimension_random:
878                        RandomSeed   = RandomSeed * 1103515245 + 12345; // classic pseudo random number generator
879                        DimValues[i] = (uint) RandomSeed >> (32 - pRegion->pDimensionDefinitions[i].bits); // highest bits are most random
880                        break;
881                    case ::gig::dimension_modwheel:
882                        DimValues[i] = pEngineChannel->ControllerTable[1];
883                        break;
884                    case ::gig::dimension_breath:
885                        DimValues[i] = pEngineChannel->ControllerTable[2];
886                        break;
887                    case ::gig::dimension_foot:
888                        DimValues[i] = pEngineChannel->ControllerTable[4];
889                        break;
890                    case ::gig::dimension_portamentotime:
891                        DimValues[i] = pEngineChannel->ControllerTable[5];
892                        break;
893                    case ::gig::dimension_effect1:
894                        DimValues[i] = pEngineChannel->ControllerTable[12];
895                        break;
896                    case ::gig::dimension_effect2:
897                        DimValues[i] = pEngineChannel->ControllerTable[13];
898                        break;
899                    case ::gig::dimension_genpurpose1:
900                        DimValues[i] = pEngineChannel->ControllerTable[16];
901                        break;
902                    case ::gig::dimension_genpurpose2:
903                        DimValues[i] = pEngineChannel->ControllerTable[17];
904                        break;
905                    case ::gig::dimension_genpurpose3:
906                        DimValues[i] = pEngineChannel->ControllerTable[18];
907                        break;
908                    case ::gig::dimension_genpurpose4:
909                        DimValues[i] = pEngineChannel->ControllerTable[19];
910                        break;
911                    case ::gig::dimension_sustainpedal:
912                        DimValues[i] = pEngineChannel->ControllerTable[64];
913                        break;
914                    case ::gig::dimension_portamento:
915                        DimValues[i] = pEngineChannel->ControllerTable[65];
916                        break;
917                    case ::gig::dimension_sostenutopedal:
918                        DimValues[i] = pEngineChannel->ControllerTable[66];
919                        break;
920                    case ::gig::dimension_softpedal:
921                        DimValues[i] = pEngineChannel->ControllerTable[67];
922                        break;
923                    case ::gig::dimension_genpurpose5:
924                        DimValues[i] = pEngineChannel->ControllerTable[80];
925                        break;
926                    case ::gig::dimension_genpurpose6:
927                        DimValues[i] = pEngineChannel->ControllerTable[81];
928                        break;
929                    case ::gig::dimension_genpurpose7:
930                        DimValues[i] = pEngineChannel->ControllerTable[82];
931                        break;
932                    case ::gig::dimension_genpurpose8:
933                        DimValues[i] = pEngineChannel->ControllerTable[83];
934                        break;
935                    case ::gig::dimension_effect1depth:
936                        DimValues[i] = pEngineChannel->ControllerTable[91];
937                        break;
938                    case ::gig::dimension_effect2depth:
939                        DimValues[i] = pEngineChannel->ControllerTable[92];
940                        break;
941                    case ::gig::dimension_effect3depth:
942                        DimValues[i] = pEngineChannel->ControllerTable[93];
943                        break;
944                    case ::gig::dimension_effect4depth:
945                        DimValues[i] = pEngineChannel->ControllerTable[94];
946                        break;
947                    case ::gig::dimension_effect5depth:
948                        DimValues[i] = pEngineChannel->ControllerTable[95];
949                        break;
950                    case ::gig::dimension_none:
951                        std::cerr << "gig::Engine::LaunchVoice() Error: dimension=none\n" << std::flush;
952                        break;
953                    default:
954                        std::cerr << "gig::Engine::LaunchVoice() Error: Unknown dimension\n" << std::flush;
955                }
956            }
957            ::gig::DimensionRegion* pDimRgn = pRegion->GetDimensionRegionByValue(DimValues);
958    
959            // no need to continue if sample is silent
960            if (!pDimRgn->pSample || !pDimRgn->pSample->SamplesTotal) return Pool<Voice>::Iterator();
961    
962          // allocate a new voice for the key          // allocate a new voice for the key
963          Voice* pNewVoice = pKey->pActiveVoices->alloc();          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
964          if (pNewVoice) {          if (itNewVoice) {
965              // launch the new voice              // launch the new voice
966              if (pNewVoice->Trigger(pNoteOnEvent, this->Pitch, this->pInstrument, iLayer, ReleaseTriggerVoice) < 0) {              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pDimRgn, VoiceType, iKeyGroup) < 0) {
967                  dmsg(1,("Triggering new voice failed!\n"));                  dmsg(4,("Voice not triggered\n"));
968                  pKey->pActiveVoices->free(pNewVoice);                  pKey->pActiveVoices->free(itNewVoice);
969              }              }
970              else { // on success              else { // on success
971                  uint** ppKeyGroup = NULL;                  --VoiceSpawnsLeft;
972                  if (pNewVoice->KeyGroup) { // if this voice / key belongs to a key group                  if (!pKey->Active) { // mark as active key
973                      ppKeyGroup = &ActiveKeyGroups[pNewVoice->KeyGroup];                      pKey->Active = true;
974                      if (*ppKeyGroup) { // if there's already an active key in that key group                      pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();
975                          midi_key_info_t* pOtherKey = &pMIDIKeyInfo[**ppKeyGroup];                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
976                          // kill all voices on the (other) key                  }
977                          Voice* pVoiceToBeKilled = pOtherKey->pActiveVoices->first();                  if (itNewVoice->KeyGroup) {
978                          while (pVoiceToBeKilled) {                      uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup];
979                              Voice* pVoiceToBeKilledNext = pOtherKey->pActiveVoices->next();                      *ppKeyGroup = &*pKey->itSelf; // put key as the (new) active key to its key group
980                              if (pVoiceToBeKilled->Type != Voice::type_release_trigger) pVoiceToBeKilled->Kill(pNoteOnEvent);                  }
981                              pOtherKey->pActiveVoices->set_current(pVoiceToBeKilled);                  if (itNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)
982                              pVoiceToBeKilled = pVoiceToBeKilledNext;                  return itNewVoice; // success
983                }
984            }
985            else if (VoiceStealing) {
986                // try to steal one voice
987                int result = StealVoice(pEngineChannel, itNoteOnEvent);
988                if (!result) { // voice stolen successfully
989                    // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died
990                    RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();
991                    if (itStealEvent) {
992                        *itStealEvent = *itNoteOnEvent; // copy event
993                        itStealEvent->Param.Note.Layer = iLayer;
994                        itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;
995                        pKey->VoiceTheftsQueued++;
996                    }
997                    else dmsg(1,("Voice stealing queue full!\n"));
998                }
999            }
1000    
1001            return Pool<Voice>::Iterator(); // no free voice or error
1002        }
1003    
1004        /**
1005         *  Will be called by LaunchVoice() method in case there are no free
1006         *  voices left. This method will select and kill one old voice for
1007         *  voice stealing and postpone the note-on event until the selected
1008         *  voice actually died.
1009         *
1010         *  @param pEngineChannel - engine channel on which this event occured on
1011         *  @param itNoteOnEvent - key, velocity and time stamp of the event
1012         *  @returns 0 on success, a value < 0 if no active voice could be picked for voice stealing
1013         */
1014        int Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
1015            if (VoiceSpawnsLeft <= 0) {
1016                dmsg(1,("Max. voice thefts per audio fragment reached (you may raise CONFIG_MAX_VOICES).\n"));
1017                return -1;
1018            }
1019            if (!pEventPool->poolIsEmpty()) {
1020    
1021                RTList<Voice>::Iterator itSelectedVoice;
1022    
1023                // Select one voice for voice stealing
1024                switch (CONFIG_VOICE_STEAL_ALGO) {
1025    
1026                    // try to pick the oldest voice on the key where the new
1027                    // voice should be spawned, if there is no voice on that
1028                    // key, or no voice left to kill, then procceed with
1029                    // 'oldestkey' algorithm
1030                    case voice_steal_algo_oldestvoiceonkey: {
1031                        midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
1032                        itSelectedVoice = pSelectedKey->pActiveVoices->first();
1033                        // proceed iterating if voice was created in this fragment cycle
1034                        while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1035                        // if we haven't found a voice then proceed with algorithm 'oldestkey'
1036                        if (itSelectedVoice && itSelectedVoice->IsStealable()) break;
1037                    } // no break - intentional !
1038    
1039                    // try to pick the oldest voice on the oldest active key
1040                    // from the same engine channel
1041                    // (caution: must stay after 'oldestvoiceonkey' algorithm !)
1042                    case voice_steal_algo_oldestkey: {
1043                        // if we already stole in this fragment, try to proceed on same key
1044                        if (this->itLastStolenVoice) {
1045                            itSelectedVoice = this->itLastStolenVoice;
1046                            do {
1047                                ++itSelectedVoice;
1048                            } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1049                            // found a "stealable" voice ?
1050                            if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1051                                // remember which voice we stole, so we can simply proceed on next voice stealing
1052                                this->itLastStolenVoice = itSelectedVoice;
1053                                break; // selection succeeded
1054                            }
1055                        }
1056                        // get (next) oldest key
1057                        RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKey) ? ++this->iuiLastStolenKey : pEngineChannel->pActiveKeys->first();
1058                        while (iuiSelectedKey) {
1059                            midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];
1060                            itSelectedVoice = pSelectedKey->pActiveVoices->first();
1061                            // proceed iterating if voice was created in this fragment cycle
1062                            while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1063                            // found a "stealable" voice ?
1064                            if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1065                                // remember which voice on which key we stole, so we can simply proceed on next voice stealing
1066                                this->iuiLastStolenKey  = iuiSelectedKey;
1067                                this->itLastStolenVoice = itSelectedVoice;
1068                                break; // selection succeeded
1069                          }                          }
1070                            ++iuiSelectedKey; // get next oldest key
1071                      }                      }
1072                        break;
1073                  }                  }
1074                  if (!pKey->Active) { // mark as active key  
1075                      pKey->Active = true;                  // don't steal anything
1076                      pKey->pSelf  = pActiveKeys->alloc();                  case voice_steal_algo_none:
1077                      *pKey->pSelf = pNoteOnEvent->Param.Note.Key;                  default: {
1078                        dmsg(1,("No free voice (voice stealing disabled)!\n"));
1079                        return -1;
1080                    }
1081                }
1082    
1083                // if we couldn't steal a voice from the same engine channel then
1084                // steal oldest voice on the oldest key from any other engine channel
1085                // (the smaller engine channel number, the higher priority)
1086                if (!itSelectedVoice || !itSelectedVoice->IsStealable()) {
1087                    EngineChannel* pSelectedChannel;
1088                    int            iChannelIndex;
1089                    // select engine channel
1090                    if (pLastStolenChannel) {
1091                        pSelectedChannel = pLastStolenChannel;
1092                        iChannelIndex    = pSelectedChannel->iEngineIndexSelf;
1093                    } else { // pick the engine channel followed by this engine channel
1094                        iChannelIndex    = (pEngineChannel->iEngineIndexSelf + 1) % engineChannels.size();
1095                        pSelectedChannel = engineChannels[iChannelIndex];
1096                    }
1097    
1098                    // if we already stole in this fragment, try to proceed on same key
1099                    if (this->itLastStolenVoiceGlobally) {
1100                        itSelectedVoice = this->itLastStolenVoiceGlobally;
1101                        do {
1102                            ++itSelectedVoice;
1103                        } while (itSelectedVoice && !itSelectedVoice->IsStealable()); // proceed iterating if voice was created in this fragment cycle
1104                  }                  }
1105                  if (pNewVoice->KeyGroup) {  
1106                      *ppKeyGroup = pKey->pSelf; // put key as the (new) active key to its key group                  #if CONFIG_DEVMODE
1107                    EngineChannel* pBegin = pSelectedChannel; // to detect endless loop
1108                    #endif // CONFIG_DEVMODE
1109    
1110                    // did we find a 'stealable' voice?
1111                    if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1112                        // remember which voice we stole, so we can simply proceed on next voice stealing
1113                        this->itLastStolenVoiceGlobally = itSelectedVoice;
1114                    } else while (true) { // iterate through engine channels
1115                        // get (next) oldest key
1116                        RTList<uint>::Iterator iuiSelectedKey = (this->iuiLastStolenKeyGlobally) ? ++this->iuiLastStolenKeyGlobally : pSelectedChannel->pActiveKeys->first();
1117                        this->iuiLastStolenKeyGlobally = RTList<uint>::Iterator(); // to prevent endless loop (see line above)
1118                        while (iuiSelectedKey) {
1119                            midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];
1120                            itSelectedVoice = pSelectedKey->pActiveVoices->first();
1121                            // proceed iterating if voice was created in this fragment cycle
1122                            while (itSelectedVoice && !itSelectedVoice->IsStealable()) ++itSelectedVoice;
1123                            // found a "stealable" voice ?
1124                            if (itSelectedVoice && itSelectedVoice->IsStealable()) {
1125                                // remember which voice on which key on which engine channel we stole, so we can simply proceed on next voice stealing
1126                                this->iuiLastStolenKeyGlobally  = iuiSelectedKey;
1127                                this->itLastStolenVoiceGlobally = itSelectedVoice;
1128                                this->pLastStolenChannel        = pSelectedChannel;
1129                                goto stealable_voice_found; // selection succeeded
1130                            }
1131                            ++iuiSelectedKey; // get next key on current engine channel
1132                        }
1133                        // get next engine channel
1134                        iChannelIndex    = (iChannelIndex + 1) % engineChannels.size();
1135                        pSelectedChannel = engineChannels[iChannelIndex];
1136    
1137                        #if CONFIG_DEVMODE
1138                        if (pSelectedChannel == pBegin) {
1139                            dmsg(1,("FATAL ERROR: voice stealing endless loop!\n"));
1140                            dmsg(1,("VoiceSpawnsLeft=%d.\n", VoiceSpawnsLeft));
1141                            dmsg(1,("Exiting.\n"));
1142                            exit(-1);
1143                        }
1144                        #endif // CONFIG_DEVMODE
1145                  }                  }
                 if (pNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)  
1146              }              }
1147    
1148                // jump point if a 'stealable' voice was found
1149                stealable_voice_found:
1150    
1151                #if CONFIG_DEVMODE
1152                if (!itSelectedVoice->IsActive()) {
1153                    dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
1154                    return -1;
1155                }
1156                #endif // CONFIG_DEVMODE
1157    
1158                // now kill the selected voice
1159                itSelectedVoice->Kill(itNoteOnEvent);
1160    
1161                --VoiceSpawnsLeft;
1162    
1163                return 0; // success
1164            }
1165            else {
1166                dmsg(1,("Event pool emtpy!\n"));
1167                return -1;
1168          }          }
         else std::cerr << "No free voice!" << std::endl << std::flush;  
1169      }      }
1170    
1171      /**      /**
1172       *  Immediately kills the voice given with pVoice (no matter if sustain is       *  Removes the given voice from the MIDI key's list of active voices.
1173       *  pressed or not) and removes it from the MIDI key's list of active voice.       *  This method will be called when a voice went inactive, e.g. because
1174       *  This method will e.g. be called if a voice went inactive by itself.       *  it finished to playback its sample, finished its release stage or
1175         *  just was killed.
1176       *       *
1177       *  @param pVoice - points to the voice to be killed       *  @param pEngineChannel - engine channel on which this event occured on
1178         *  @param itVoice - points to the voice to be freed
1179       */       */
1180      void Engine::KillVoiceImmediately(Voice* pVoice) {      void Engine::FreeVoice(EngineChannel* pEngineChannel, Pool<Voice>::Iterator& itVoice) {
1181          if (pVoice) {          if (itVoice) {
1182              if (pVoice->IsActive()) pVoice->KillImmediately();              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itVoice->MIDIKey];
1183    
1184              midi_key_info_t* pKey = &pMIDIKeyInfo[pVoice->MIDIKey];              uint keygroup = itVoice->KeyGroup;
1185    
1186              // free the voice object              // free the voice object
1187              pVoicePool->free(pVoice);              pVoicePool->free(itVoice);
1188    
1189              // check if there are no voices left on the MIDI key and update the key info if so              // if no other voices left and member of a key group, remove from key group
1190              if (pKey->pActiveVoices->is_empty()) {              if (pKey->pActiveVoices->isEmpty() && keygroup) {
1191                  if (pVoice->KeyGroup) { // if voice / key belongs to a key group                  uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[keygroup];
1192                      uint** ppKeyGroup = &ActiveKeyGroups[pVoice->KeyGroup];                  if (*ppKeyGroup == &*pKey->itSelf) *ppKeyGroup = NULL; // remove key from key group
                     if (*ppKeyGroup == pKey->pSelf) *ppKeyGroup = NULL; // remove key from key group  
                 }  
                 pKey->Active = false;  
                 pActiveKeys->free(pKey->pSelf); // remove key from list of active keys  
                 pKey->pSelf = NULL;  
                 pKey->ReleaseTrigger = false;  
                 dmsg(3,("Key has no more voices now\n"));  
1193              }              }
1194          }          }
1195          else std::cerr << "Couldn't release voice! (pVoice == NULL)\n" << std::flush;          else std::cerr << "Couldn't release voice! (!itVoice)\n" << std::flush;
1196        }
1197    
1198        /**
1199         *  Called when there's no more voice left on a key, this call will
1200         *  update the key info respectively.
1201         *
1202         *  @param pEngineChannel - engine channel on which this event occured on
1203         *  @param pKey - key which is now inactive
1204         */
1205        void Engine::FreeKey(EngineChannel* pEngineChannel, midi_key_info_t* pKey) {
1206            if (pKey->pActiveVoices->isEmpty()) {
1207                pKey->Active = false;
1208                pEngineChannel->pActiveKeys->free(pKey->itSelf); // remove key from list of active keys
1209                pKey->itSelf = RTList<uint>::Iterator();
1210                pKey->ReleaseTrigger = false;
1211                pKey->pEvents->clear();
1212                dmsg(3,("Key has no more voices now\n"));
1213            }
1214            else dmsg(1,("gig::Engine: Oops, tried to free a key which contains voices.\n"));
1215      }      }
1216    
1217      /**      /**
1218       *  Reacts on supported control change commands (e.g. pitch bend wheel,       *  Reacts on supported control change commands (e.g. pitch bend wheel,
1219       *  modulation wheel, aftertouch).       *  modulation wheel, aftertouch).
1220       *       *
1221       *  @param pControlChangeEvent - controller, value and time stamp of the event       *  @param pEngineChannel - engine channel on which this event occured on
1222         *  @param itControlChangeEvent - controller, value and time stamp of the event
1223       */       */
1224      void Engine::ProcessControlChange(Event* pControlChangeEvent) {      void Engine::ProcessControlChange(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itControlChangeEvent) {
1225          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", pControlChangeEvent->Param.CC.Controller, pControlChangeEvent->Param.CC.Value));          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", itControlChangeEvent->Param.CC.Controller, itControlChangeEvent->Param.CC.Value));
1226    
1227          switch (pControlChangeEvent->Param.CC.Controller) {          // update controller value in the engine channel's controller table
1228              case 64: {          pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
1229                  if (pControlChangeEvent->Param.CC.Value >= 64 && !SustainPedal) {  
1230                      dmsg(4,("PEDAL DOWN\n"));          switch (itControlChangeEvent->Param.CC.Controller) {
1231                      SustainPedal = true;              case 5: { // portamento time
1232                    pEngineChannel->PortamentoTime = (float) itControlChangeEvent->Param.CC.Value / 127.0f * (float) CONFIG_PORTAMENTO_TIME_MAX + (float) CONFIG_PORTAMENTO_TIME_MIN;
1233                    break;
1234                }
1235                case 7: { // volume
1236                    //TODO: not sample accurate yet
1237                    pEngineChannel->GlobalVolume = VolumeCurve[itControlChangeEvent->Param.CC.Value] *  CONFIG_GLOBAL_ATTENUATION;
1238                    pEngineChannel->bStatusChanged = true; // engine channel status has changed, so set notify flag
1239                    break;
1240                }
1241                case 10: { // panpot
1242                    //TODO: not sample accurate yet
1243                    pEngineChannel->GlobalPanLeft  = PanCurve[128 - itControlChangeEvent->Param.CC.Value];
1244                    pEngineChannel->GlobalPanRight = PanCurve[itControlChangeEvent->Param.CC.Value];
1245                    break;
1246                }
1247                case 64: { // sustain
1248                    if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {
1249                        dmsg(4,("DAMPER (RIGHT) PEDAL DOWN\n"));
1250                        pEngineChannel->SustainPedal = true;
1251    
1252                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1253                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1254                        #endif
1255    
1256                      // cancel release process of voices if necessary                      // cancel release process of voices if necessary
1257                      uint* piKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1258                      if (piKey) {                      for (; iuiKey; ++iuiKey) {
1259                          pControlChangeEvent->Type = Event::type_cancel_release; // transform event type                          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1260                          while (piKey) {                          if (!pKey->KeyPressed) {
1261                              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1262                              pActiveKeys->set_current(piKey);                              if (itNewEvent) {
1263                              piKey = pActiveKeys->next();                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1264                              if (!pKey->KeyPressed) {                                  itNewEvent->Type = Event::type_cancel_release; // transform event type
                                 Event* pNewEvent = pKey->pEvents->alloc();  
                                 if (pNewEvent) *pNewEvent = *pControlChangeEvent; // copy event to the key's own event list  
                                 else dmsg(1,("Event pool emtpy!\n"));  
1265                              }                              }
1266                                else dmsg(1,("Event pool emtpy!\n"));
1267                          }                          }
1268                      }                      }
1269                  }                  }
1270                  if (pControlChangeEvent->Param.CC.Value < 64 && SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {
1271                      dmsg(4,("PEDAL UP\n"));                      dmsg(4,("DAMPER (RIGHT) PEDAL UP\n"));
1272                      SustainPedal = false;                      pEngineChannel->SustainPedal = false;
1273    
1274                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1275                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1276                        #endif
1277    
1278                      // release voices if their respective key is not pressed                      // release voices if their respective key is not pressed
1279                      uint* piKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1280                      if (piKey) {                      for (; iuiKey; ++iuiKey) {
1281                          pControlChangeEvent->Type = Event::type_release; // transform event type                          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1282                          while (piKey) {                          if (!pKey->KeyPressed && ShouldReleaseVoice(pEngineChannel, *iuiKey)) {
1283                              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];                              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1284                              pActiveKeys->set_current(piKey);                              if (itNewEvent) {
1285                              piKey = pActiveKeys->next();                                  *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1286                              if (!pKey->KeyPressed) {                                  itNewEvent->Type = Event::type_release; // transform event type
                                 Event* pNewEvent = pKey->pEvents->alloc();  
                                 if (pNewEvent) *pNewEvent = *pControlChangeEvent; // copy event to the key's own event list  
                                 else dmsg(1,("Event pool emtpy!\n"));  
1287                              }                              }
1288                                else dmsg(1,("Event pool emtpy!\n"));
1289                            }
1290                        }
1291                    }
1292                    break;
1293                }
1294                case 65: { // portamento on / off
1295                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1296                    pEngineChannel->PortamentoMode = itControlChangeEvent->Param.CC.Value >= 64;
1297                    break;
1298                }
1299                case 66: { // sostenuto
1300                    if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SostenutoPedal) {
1301                        dmsg(4,("SOSTENUTO (CENTER) PEDAL DOWN\n"));
1302                        pEngineChannel->SostenutoPedal = true;
1303    
1304                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1305                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1306                        #endif
1307    
1308                        SostenutoKeyCount = 0;
1309                        // Remeber the pressed keys
1310                        RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1311                        for (; iuiKey; ++iuiKey) {
1312                            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1313                            if (pKey->KeyPressed && SostenutoKeyCount < 128) SostenutoKeys[SostenutoKeyCount++] = *iuiKey;
1314                        }
1315                    }
1316                    if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SostenutoPedal) {
1317                        dmsg(4,("SOSTENUTO (CENTER) PEDAL UP\n"));
1318                        pEngineChannel->SostenutoPedal = false;
1319    
1320                        #if !CONFIG_PROCESS_MUTED_CHANNELS
1321                        if (pEngineChannel->GetMute()) return; // skip if sampler channel is muted
1322                        #endif
1323    
1324                        // release voices if the damper pedal is up and their respective key is not pressed
1325                        for (int i = 0; i < SostenutoKeyCount; i++) {
1326                            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[SostenutoKeys[i]];
1327                            if (!pKey->KeyPressed && !pEngineChannel->SustainPedal) {
1328                                RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1329                                if (itNewEvent) {
1330                                    *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
1331                                    itNewEvent->Type = Event::type_release; // transform event type
1332                                }
1333                                else dmsg(1,("Event pool emtpy!\n"));
1334                          }                          }
1335                      }                      }
1336                  }                  }
1337                  break;                  break;
1338              }              }
         }  
1339    
         // update controller value in the engine's controller table  
         ControllerTable[pControlChangeEvent->Param.CC.Controller] = pControlChangeEvent->Param.CC.Value;  
1340    
1341          // move event from the unsorted event list to the control change event list              // Channel Mode Messages
1342          pEvents->move(pControlChangeEvent, pCCEvents);  
1343                case 120: { // all sound off
1344                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1345                    break;
1346                }
1347                case 121: { // reset all controllers
1348                    pEngineChannel->ResetControllers();
1349                    break;
1350                }
1351                case 123: { // all notes off
1352                    ReleaseAllVoices(pEngineChannel, itControlChangeEvent);
1353                    break;
1354                }
1355                case 126: { // mono mode on
1356                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1357                    pEngineChannel->SoloMode = true;
1358                    break;
1359                }
1360                case 127: { // poly mode on
1361                    KillAllVoices(pEngineChannel, itControlChangeEvent);
1362                    pEngineChannel->SoloMode = false;
1363                    break;
1364                }
1365            }
1366      }      }
1367    
1368      /**      /**
1369       *  Reacts on MIDI system exclusive messages.       *  Reacts on MIDI system exclusive messages.
1370       *       *
1371       *  @param pSysexEvent - sysex data size and time stamp of the sysex event       *  @param itSysexEvent - sysex data size and time stamp of the sysex event
1372       */       */
1373      void Engine::ProcessSysex(Event* pSysexEvent) {      void Engine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) {
1374          RingBuffer<uint8_t>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();          RingBuffer<uint8_t>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();
1375    
1376          uint8_t exclusive_status, id;          uint8_t exclusive_status, id;
# Line 791  namespace LinuxSampler { namespace gig { Line 1380  namespace LinuxSampler { namespace gig {
1380    
1381          switch (id) {          switch (id) {
1382              case 0x41: { // Roland              case 0x41: { // Roland
1383                    dmsg(3,("Roland Sysex\n"));
1384                  uint8_t device_id, model_id, cmd_id;                  uint8_t device_id, model_id, cmd_id;
1385                  if (!reader.pop(&device_id)) goto free_sysex_data;                  if (!reader.pop(&device_id)) goto free_sysex_data;
1386                  if (!reader.pop(&model_id))  goto free_sysex_data;                  if (!reader.pop(&model_id))  goto free_sysex_data;
# Line 803  namespace LinuxSampler { namespace gig { Line 1393  namespace LinuxSampler { namespace gig {
1393                  const RingBuffer<uint8_t>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later                  const RingBuffer<uint8_t>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later
1394                  if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;                  if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;
1395                  if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters                  if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters
1396                        dmsg(3,("\tSystem Parameter\n"));
1397                  }                  }
1398                  else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters                  else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters
1399                        dmsg(3,("\tCommon Parameter\n"));
1400                  }                  }
1401                  else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)                  else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)
1402                      switch (addr[3]) {                      dmsg(3,("\tPart Parameter\n"));
1403                        switch (addr[2]) {
1404                          case 0x40: { // scale tuning                          case 0x40: { // scale tuning
1405                                dmsg(3,("\t\tScale Tuning\n"));
1406                              uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave                              uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave
1407                              if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;                              if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;
1408                              uint8_t checksum;                              uint8_t checksum;
1409                              if (!reader.pop(&checksum))                      goto free_sysex_data;                              if (!reader.pop(&checksum)) goto free_sysex_data;
1410                              if (GSCheckSum(checksum_reader, 12) != checksum) goto free_sysex_data;                              #if CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1411                                if (GSCheckSum(checksum_reader, 12)) goto free_sysex_data;
1412                                #endif // CONFIG_ASSERT_GS_SYSEX_CHECKSUM
1413                              for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;                              for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;
1414                              AdjustScale((int8_t*) scale_tunes);                              AdjustScale((int8_t*) scale_tunes);
1415                                dmsg(3,("\t\t\tNew scale applied.\n"));
1416                              break;                              break;
1417                          }                          }
1418                      }                      }
# Line 829  namespace LinuxSampler { namespace gig { Line 1426  namespace LinuxSampler { namespace gig {
1426          }          }
1427    
1428          free_sysex_data: // finally free sysex data          free_sysex_data: // finally free sysex data
1429          pSysexBuffer->increment_read_ptr(pSysexEvent->Param.Sysex.Size);          pSysexBuffer->increment_read_ptr(itSysexEvent->Param.Sysex.Size);
1430      }      }
1431    
1432      /**      /**
# Line 860  namespace LinuxSampler { namespace gig { Line 1457  namespace LinuxSampler { namespace gig {
1457      }      }
1458    
1459      /**      /**
1460       * Initialize the parameter sequence for the modulation destination given by       * Releases all voices on an engine channel. All voices will go into
1461       * by 'dst' with the constant value given by val.       * the release stage and thus it might take some time (e.g. dependant to
1462         * their envelope release time) until they actually die.
1463         *
1464         * @param pEngineChannel - engine channel on which all voices should be released
1465         * @param itReleaseEvent - event which caused this releasing of all voices
1466       */       */
1467      void Engine::ResetSynthesisParameters(Event::destination_t dst, float val) {      void Engine::ReleaseAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itReleaseEvent) {
1468          int maxsamples = pAudioOutputDevice->MaxSamplesPerCycle();          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1469          float* m = &pSynthesisParameters[dst][0];          while (iuiKey) {
1470          for (int i = 0; i < maxsamples; i += 4) {              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1471             m[i]   = val;              ++iuiKey;
1472             m[i+1] = val;              // append a 'release' event to the key's own event list
1473             m[i+2] = val;              RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
1474             m[i+3] = val;              if (itNewEvent) {
1475                    *itNewEvent = *itReleaseEvent; // copy original event (to the key's event list)
1476                    itNewEvent->Type = Event::type_release; // transform event type
1477                }
1478                else dmsg(1,("Event pool emtpy!\n"));
1479          }          }
1480      }      }
1481    
1482      float Engine::Volume() {      /**
1483          return GlobalVolume;       * Kills all voices on an engine channel as soon as possible. Voices
1484      }       * won't get into release state, their volume level will be ramped down
1485         * as fast as possible.
1486      void Engine::Volume(float f) {       *
1487          GlobalVolume = f;       * @param pEngineChannel - engine channel on which all voices should be killed
1488      }       * @param itKillEvent    - event which caused this killing of all voices
1489         */
1490      uint Engine::Channels() {      void Engine::KillAllVoices(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itKillEvent) {
1491          return 2;          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
1492      }          RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
1493            while (iuiKey != end) { // iterate through all active keys
1494      void Engine::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) {              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
1495          AudioChannel* pChannel = pAudioOutputDevice->Channel(AudioDeviceChannel);              ++iuiKey;
1496          if (!pChannel) throw AudioOutputException("Invalid audio output device channel " + ToString(AudioDeviceChannel));              RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
1497          switch (EngineAudioChannel) {              RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
1498              case 0: // left output channel              for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
1499                  pOutputLeft = pChannel->Buffer();                  itVoice->Kill(itKillEvent);
1500                  AudioDeviceChannelLeft = AudioDeviceChannel;                  --VoiceSpawnsLeft; //FIXME: just a temporary workaround, we should check the cause in StealVoice() instead
1501                  break;              }
             case 1: // right output channel  
                 pOutputRight = pChannel->Buffer();  
                 AudioDeviceChannelRight = AudioDeviceChannel;  
                 break;  
             default:  
                 throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));  
1502          }          }
1503      }      }
1504    
1505      int Engine::OutputChannel(uint EngineAudioChannel) {      /**
1506          switch (EngineAudioChannel) {       * Determines whether the specified voice should be released.
1507              case 0: // left channel       *
1508                  return AudioDeviceChannelLeft;       * @param pEngineChannel - The engine channel on which the voice should be checked
1509              case 1: // right channel       * @param Key - The key number
1510                  return AudioDeviceChannelRight;       * @returns true if the specified should be released, false otherwise.
1511              default:       */
1512                  throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));      bool Engine::ShouldReleaseVoice(EngineChannel* pEngineChannel, int Key) {
1513            if (pEngineChannel->SustainPedal) return false;
1514    
1515            if (pEngineChannel->SostenutoPedal) {
1516                for (int i = 0; i < SostenutoKeyCount; i++)
1517                    if (Key == SostenutoKeys[i]) return false;
1518          }          }
1519    
1520            return true;
1521      }      }
1522    
1523      uint Engine::VoiceCount() {      uint Engine::VoiceCount() {
# Line 943  namespace LinuxSampler { namespace gig { Line 1549  namespace LinuxSampler { namespace gig {
1549      }      }
1550    
1551      String Engine::EngineName() {      String Engine::EngineName() {
1552          return "GigEngine";          return LS_GIG_ENGINE_NAME;
     }  
   
     String Engine::InstrumentFileName() {  
         return InstrumentFile;  
     }  
   
     int Engine::InstrumentIndex() {  
         return InstrumentIdx;  
     }  
   
     int Engine::InstrumentStatus() {  
         return InstrumentStat;  
1553      }      }
1554    
1555      String Engine::Description() {      String Engine::Description() {
# Line 963  namespace LinuxSampler { namespace gig { Line 1557  namespace LinuxSampler { namespace gig {
1557      }      }
1558    
1559      String Engine::Version() {      String Engine::Version() {
1560          String s = "$Revision: 1.13 $";          String s = "$Revision: 1.58 $";
1561          return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword          return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword
1562      }      }
1563    
1564        // static constant initializers
1565        const float* Engine::VolumeCurve(InitVolumeCurve());
1566        const float* Engine::PanCurve(InitPanCurve());
1567    
1568        float* Engine::InitVolumeCurve() {
1569            // line-segment approximation
1570            const float segments[] = {
1571                0, 0, 2, 0.0046, 16, 0.016, 31, 0.051, 45, 0.115, 54.5, 0.2,
1572                64.5, 0.39, 74, 0.74, 92, 1.03, 114, 1.94, 119.2, 2.2, 127, 2.2
1573            };
1574            return InitCurve(segments);
1575        }
1576    
1577        float* Engine::InitPanCurve() {
1578            // line-segment approximation
1579            const float segments[] = {
1580                0, 0, 1, 0,
1581                2, 0.05, 31.5, 0.7, 51, 0.851, 74.5, 1.12,
1582                127, 1.41, 128, 1.41
1583            };
1584            return InitCurve(segments, 129);
1585        }
1586    
1587        float* Engine::InitCurve(const float* segments, int size) {
1588            float* y = new float[size];
1589            for (int x = 0 ; x < size ; x++) {
1590                if (x > segments[2]) segments += 2;
1591                y[x] = segments[1] + (x - segments[0]) *
1592                    (segments[3] - segments[1]) / (segments[2] - segments[0]);
1593            }
1594            return y;
1595        }
1596    
1597  }} // namespace LinuxSampler::gig  }} // namespace LinuxSampler::gig

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

  ViewVC Help
Powered by ViewVC