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

Legend:
Removed from v.242  
changed lines
  Added in v.769

  ViewVC Help
Powered by ViewVC