/[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 412 by schoenebeck, Sat Feb 26 22:44:51 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    
29  #include "Engine.h"  #include "Engine.h"
30    
31    #if defined(__APPLE__)
32    # include <stdlib.h>
33    #else
34    # include <malloc.h>
35    #endif
36    
37  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
38    
39      InstrumentResourceManager Engine::Instruments;      InstrumentResourceManager Engine::instruments;
40    
41        std::map<AudioOutputDevice*,Engine*> Engine::engines;
42    
43        /**
44         * Get a gig::Engine object for the given gig::EngineChannel and the
45         * given AudioOutputDevice. All engine channels which are connected to
46         * the same audio output device will use the same engine instance. This
47         * method will be called by a gig::EngineChannel whenever it's
48         * connecting to a audio output device.
49         *
50         * @param pChannel - engine channel which acquires an engine object
51         * @param pDevice  - the audio output device \a pChannel is connected to
52         */
53        Engine* Engine::AcquireEngine(LinuxSampler::gig::EngineChannel* pChannel, AudioOutputDevice* pDevice) {
54            Engine* pEngine = NULL;
55            // check if there's already an engine for the given audio output device
56            if (engines.count(pDevice)) {
57                dmsg(4,("Using existing gig::Engine.\n"));
58                pEngine = engines[pDevice];            
59            } else { // create a new engine (and disk thread) instance for the given audio output device
60                dmsg(4,("Creating new gig::Engine.\n"));
61                pEngine = new Engine;
62                pEngine->Connect(pDevice);
63                engines[pDevice] = pEngine;            
64            }
65            // register engine channel to the engine instance
66            pEngine->engineChannels.push_back(pChannel);
67            dmsg(4,("This gig::Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));
68            return pEngine;
69        }
70    
71        /**
72         * Once an engine channel is disconnected from an audio output device,
73         * it wil immediately call this method to unregister itself from the
74         * engine instance and if that engine instance is not used by any other
75         * engine channel anymore, then that engine instance will be destroyed.
76         *
77         * @param pChannel - engine channel which wants to disconnect from it's
78         *                   engine instance
79         * @param pDevice  - audio output device \a pChannel was connected to
80         */
81        void Engine::FreeEngine(LinuxSampler::gig::EngineChannel* pChannel, AudioOutputDevice* pDevice) {
82            dmsg(4,("Disconnecting EngineChannel from gig::Engine.\n"));
83            Engine* pEngine = engines[pDevice];
84            // unregister EngineChannel from the Engine instance
85            pEngine->engineChannels.remove(pChannel);
86            // if the used Engine instance is not used anymore, then destroy it
87            if (pEngine->engineChannels.empty()) {
88                pDevice->Disconnect(pEngine);
89                engines.erase(pDevice);
90                delete pEngine;
91                dmsg(4,("Destroying gig::Engine.\n"));
92            }
93            else dmsg(4,("This gig::Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));
94        }
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>(SYSEX_BUFFER_SIZE, 0);
101          pEventPool         = new RTELMemoryPool<Event>(MAX_EVENTS_PER_FRAGMENT);          pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT, 0);
102          pVoicePool         = new RTELMemoryPool<Voice>(MAX_AUDIO_VOICES);          pEventPool         = new Pool<Event>(MAX_EVENTS_PER_FRAGMENT);
103          pActiveKeys        = new RTELMemoryPool<uint>(128);          pVoicePool         = new Pool<Voice>(MAX_AUDIO_VOICES);        
104          pEvents            = new RTEList<Event>(pEventPool);          pVoiceStealingQueue = new RTList<Event>(pEventPool);
105          pCCEvents          = new RTEList<Event>(pEventPool);          pEvents            = new RTList<Event>(pEventPool);
106            pCCEvents          = new RTList<Event>(pEventPool);
107            
108          for (uint i = 0; i < Event::destination_count; i++) {          for (uint i = 0; i < Event::destination_count; i++) {
109              pSynthesisEvents[i] = new RTEList<Event>(pEventPool);              pSynthesisEvents[i] = new RTList<Event>(pEventPool);
         }  
         for (uint i = 0; i < 128; i++) {  
             pMIDIKeyInfo[i].pActiveVoices  = new RTEList<Voice>(pVoicePool);  
             pMIDIKeyInfo[i].KeyPressed     = false;  
             pMIDIKeyInfo[i].Active         = false;  
             pMIDIKeyInfo[i].ReleaseTrigger = false;  
             pMIDIKeyInfo[i].pSelf          = NULL;  
             pMIDIKeyInfo[i].pEvents        = new RTEList<Event>(pEventPool);  
110          }          }
111          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
112              pVoice->SetEngine(this);              iterVoice->SetEngine(this);
113          }          }
114          pVoicePool->clear();          pVoicePool->clear();
115    
# Line 63  namespace LinuxSampler { namespace gig { Line 117  namespace LinuxSampler { namespace gig {
117          pBasicFilterParameters  = NULL;          pBasicFilterParameters  = NULL;
118          pMainFilterParameters   = NULL;          pMainFilterParameters   = NULL;
119    
         InstrumentIdx = -1;  
         InstrumentStat = -1;  
   
         AudioDeviceChannelLeft  = -1;  
         AudioDeviceChannelRight = -1;  
   
120          ResetInternal();          ResetInternal();
121      }      }
122    
123      Engine::~Engine() {      Engine::~Engine() {
124          if (pDiskThread) {          if (pDiskThread) {
125                dmsg(1,("Stopping disk thread..."));
126              pDiskThread->StopThread();              pDiskThread->StopThread();
127              delete pDiskThread;              delete pDiskThread;
128          }              dmsg(1,("OK\n"));
         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;  
129          }          }
130          for (uint i = 0; i < Event::destination_count; i++) {          for (uint i = 0; i < Event::destination_count; i++) {
131              if (pSynthesisEvents[i]) delete pSynthesisEvents[i];              if (pSynthesisEvents[i]) delete pSynthesisEvents[i];
132          }          }
         delete[] pSynthesisEvents;  
133          if (pEvents)     delete pEvents;          if (pEvents)     delete pEvents;
134          if (pCCEvents)   delete pCCEvents;          if (pCCEvents)   delete pCCEvents;
135          if (pEventQueue) delete pEventQueue;          if (pEventQueue) delete pEventQueue;
136          if (pEventPool)  delete pEventPool;          if (pEventPool)  delete pEventPool;
137          if (pVoicePool)  delete pVoicePool;          if (pVoicePool) {
138          if (pActiveKeys) delete pActiveKeys;              pVoicePool->clear();
139                delete pVoicePool;
140            }
141          if (pEventGenerator) delete pEventGenerator;          if (pEventGenerator) delete pEventGenerator;
142          if (pMainFilterParameters) delete[] pMainFilterParameters;          if (pMainFilterParameters) delete[] pMainFilterParameters;
143          if (pBasicFilterParameters) delete[] pBasicFilterParameters;          if (pBasicFilterParameters) delete[] pBasicFilterParameters;
144          if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];          if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
145            if (pVoiceStealingQueue) delete pVoiceStealingQueue;
146            if (pSysexBuffer) delete pSysexBuffer;
147      }      }
148    
149      void Engine::Enable() {      void Engine::Enable() {
# Line 123  namespace LinuxSampler { namespace gig { Line 170  namespace LinuxSampler { namespace gig {
170       */       */
171      void Engine::Reset() {      void Engine::Reset() {
172          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();  
   
173          ResetInternal();          ResetInternal();
   
         // signal audio thread to continue with rendering  
         //SuspensionRequested = false;  
174          Enable();          Enable();
175      }      }
176    
# Line 149  namespace LinuxSampler { namespace gig { Line 179  namespace LinuxSampler { namespace gig {
179       *  control and status variables. This method is not thread safe!       *  control and status variables. This method is not thread safe!
180       */       */
181      void Engine::ResetInternal() {      void Engine::ResetInternal() {
         Pitch               = 0;  
         SustainPedal        = false;  
182          ActiveVoiceCount    = 0;          ActiveVoiceCount    = 0;
183          ActiveVoiceCountMax = 0;          ActiveVoiceCountMax = 0;
         GlobalVolume        = 1.0;  
184    
185          // set all MIDI controller values to zero          // reset voice stealing parameters
186          memset(ControllerTable, 0x00, 128);          pVoiceStealingQueue->clear();
187    
188          // reset key info          // reset to normal chromatic scale (means equal temper)
189          for (uint i = 0; i < 128; i++) {          memset(&ScaleTuning[0], 0x00, 12);
             pMIDIKeyInfo[i].pActiveVoices->clear();  
             pMIDIKeyInfo[i].pEvents->clear();  
             pMIDIKeyInfo[i].KeyPressed     = false;  
             pMIDIKeyInfo[i].Active         = false;  
             pMIDIKeyInfo[i].ReleaseTrigger = false;  
             pMIDIKeyInfo[i].pSelf          = NULL;  
         }  
   
         // reset all key groups  
         map<uint,uint*>::iterator iter = ActiveKeyGroups.begin();  
         for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;  
190    
191          // reset all voices          // reset all voices
192          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
193              pVoice->Reset();              iterVoice->Reset();
194          }          }
195          pVoicePool->clear();          pVoicePool->clear();
196    
         // free all active keys  
         pActiveKeys->clear();  
   
197          // reset disk thread          // reset disk thread
198          if (pDiskThread) pDiskThread->Reset();          if (pDiskThread) pDiskThread->Reset();
199    
200          // delete all input events          // delete all input events
201          pEventQueue->init();          pEventQueue->init();
202      }      }    
   
     /**  
      *  Load an instrument from a .gig file.  
      *  
      *  @param FileName   - file name of the Gigasampler instrument file  
      *  @param Instrument - index of the instrument in the .gig file  
      *  @throws LinuxSamplerException  on error  
      *  @returns          detailed description of the method call result  
      */  
     void Engine::LoadInstrument(const char* FileName, uint Instrument) {  
   
         DisableAndLock();  
   
         ResetInternal(); // reset engine  
   
         // free old instrument  
         if (pInstrument) {  
             // give old instrument back to instrument manager  
             Instruments.HandBack(pInstrument, this);  
         }  
   
         InstrumentFile = FileName;  
         InstrumentIdx = Instrument;  
         InstrumentStat = 0;  
   
         // delete all key groups  
         ActiveKeyGroups.clear();  
   
         // request gig instrument from instrument manager  
         try {  
             instrument_id_t instrid;  
             instrid.FileName    = FileName;  
             instrid.iInstrument = Instrument;  
             pInstrument = Instruments.Borrow(instrid, this);  
             if (!pInstrument) {  
                 InstrumentStat = -1;  
                 dmsg(1,("no instrument loaded!!!\n"));  
                 exit(EXIT_FAILURE);  
             }  
         }  
         catch (RIFF::Exception e) {  
             InstrumentStat = -2;  
             String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;  
             throw LinuxSamplerException(msg);  
         }  
         catch (InstrumentResourceManagerException e) {  
             InstrumentStat = -3;  
             String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();  
             throw LinuxSamplerException(msg);  
         }  
         catch (...) {  
             InstrumentStat = -4;  
             throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");  
         }  
   
         // rebuild ActiveKeyGroups map with key groups of current instrument  
         for (::gig::Region* pRegion = pInstrument->GetFirstRegion(); pRegion; pRegion = pInstrument->GetNextRegion())  
             if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL;  
   
         InstrumentStat = 100;  
   
         // inform audio driver for the need of two channels  
         try {  
             if (pAudioOutputDevice) pAudioOutputDevice->AcquireChannels(2); // gig Engine only stereo  
         }  
         catch (AudioOutputException e) {  
             String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();  
             throw LinuxSamplerException(msg);  
         }  
   
         Enable();  
     }  
   
     /**  
      * Will be called by the InstrumentResourceManager when the instrument  
      * we are currently using in this engine is going to be updated, so we  
      * can stop playback before that happens.  
      */  
     void Engine::ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {  
         dmsg(3,("gig::Engine: Received instrument update message.\n"));  
         DisableAndLock();  
         ResetInternal();  
         this->pInstrument = NULL;  
     }  
   
     /**  
      * Will be called by the InstrumentResourceManager when the instrument  
      * update process was completed, so we can continue with playback.  
      */  
     void Engine::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {  
         this->pInstrument = pNewResource; //TODO: there are couple of engine parameters we should update here as well if the instrument was updated (see LoadInstrument())  
         Enable();  
     }  
203    
204      void Engine::Connect(AudioOutputDevice* pAudioOut) {      void Engine::Connect(AudioOutputDevice* pAudioOut) {
205          pAudioOutputDevice = pAudioOut;          pAudioOutputDevice = pAudioOut;
# Line 294  namespace LinuxSampler { namespace gig { Line 214  namespace LinuxSampler { namespace gig {
214              String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();              String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();
215              throw LinuxSamplerException(msg);              throw LinuxSamplerException(msg);
216          }          }
217            
         this->AudioDeviceChannelLeft  = 0;  
         this->AudioDeviceChannelRight = 1;  
         this->pOutputLeft             = pAudioOutputDevice->Channel(0)->Buffer();  
         this->pOutputRight            = pAudioOutputDevice->Channel(1)->Buffer();  
218          this->MaxSamplesPerCycle      = pAudioOutputDevice->MaxSamplesPerCycle();          this->MaxSamplesPerCycle      = pAudioOutputDevice->MaxSamplesPerCycle();
219          this->SampleRate              = pAudioOutputDevice->SampleRate();          this->SampleRate              = pAudioOutputDevice->SampleRate();
220    
221            // FIXME: audio drivers with varying fragment sizes might be a problem here
222            MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * EG_MIN_RELEASE_TIME) - 1;
223            if (MaxFadeOutPos < 0)
224                throw LinuxSamplerException("EG_MIN_RELEASE_TIME in EGADSR.h too big for current audio fragment size / sampling rate!");
225    
226          // (re)create disk thread          // (re)create disk thread
227          if (this->pDiskThread) {          if (this->pDiskThread) {
228                dmsg(1,("Stopping disk thread..."));
229              this->pDiskThread->StopThread();              this->pDiskThread->StopThread();
230              delete this->pDiskThread;              delete this->pDiskThread;
231                dmsg(1,("OK\n"));
232          }          }
233          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo          this->pDiskThread = new DiskThread(((pAudioOut->MaxSamplesPerCycle() << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo
234          if (!pDiskThread) {          if (!pDiskThread) {
# Line 313  namespace LinuxSampler { namespace gig { Line 236  namespace LinuxSampler { namespace gig {
236              exit(EXIT_FAILURE);              exit(EXIT_FAILURE);
237          }          }
238    
239          for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
240              pVoice->pDiskThread = this->pDiskThread;              iterVoice->pDiskThread = this->pDiskThread;
241              dmsg(3,("d"));              dmsg(3,("d"));
242          }          }
243          pVoicePool->clear();          pVoicePool->clear();
# Line 324  namespace LinuxSampler { namespace gig { Line 247  namespace LinuxSampler { namespace gig {
247          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());          pEventGenerator = new EventGenerator(pAudioOut->SampleRate());
248    
249          // (re)allocate synthesis parameter matrix          // (re)allocate synthesis parameter matrix
250          if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0];          if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
251          pSynthesisParameters[0] = new float[Event::destination_count * pAudioOut->MaxSamplesPerCycle()];  
252            #if defined(__APPLE__)
253            pSynthesisParameters[0] = (float *) malloc(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle());
254            #else
255            pSynthesisParameters[0] = (float *) memalign(16,(Event::destination_count * sizeof(float) * pAudioOut->MaxSamplesPerCycle()));
256            #endif
257          for (int dst = 1; dst < Event::destination_count; dst++)          for (int dst = 1; dst < Event::destination_count; dst++)
258              pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();              pSynthesisParameters[dst] = pSynthesisParameters[dst - 1] + pAudioOut->MaxSamplesPerCycle();
259    
# Line 339  namespace LinuxSampler { namespace gig { Line 267  namespace LinuxSampler { namespace gig {
267          pDiskThread->StartThread();          pDiskThread->StartThread();
268          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
269    
270          for (Voice* pVoice = pVoicePool->first(); pVoice; pVoice = pVoicePool->next()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
271              if (!pVoice->pDiskThread) {              if (!iterVoice->pDiskThread) {
272                  dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));                  dmsg(0,("Engine -> voice::trigger: !pDiskThread\n"));
273                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
274              }              }
275          }          }
276      }      }
277    
278      void Engine::DisconnectAudioOutputDevice() {      void Engine::ClearEventLists() {
279          if (pAudioOutputDevice) { // if clause to prevent disconnect loops          pEvents->clear();
280              AudioOutputDevice* olddevice = pAudioOutputDevice;          pCCEvents->clear();
281              pAudioOutputDevice = NULL;          for (uint i = 0; i < Event::destination_count; i++) {
282              olddevice->Disconnect(this);              pSynthesisEvents[i]->clear();
             AudioDeviceChannelLeft  = -1;  
             AudioDeviceChannelRight = -1;  
283          }          }
284      }      }
285    
286      /**      /**
287         * Copy all events from the given input queue buffer to the engine's
288         * internal event list. This will be done at the beginning of each audio
289         * cycle (that is each RenderAudio() call) to get all events which have
290         * to be processed in the current audio cycle. Each EngineChannel has
291         * it's own input event queue for the common channel specific events
292         * (like NoteOn, NoteOff and ControlChange events). Beside that, the
293         * engine also has a input event queue for global events (usually SysEx
294         * message).
295         *
296         * @param pEventQueue - input event buffer to read from
297         * @param Samples     - number of sample points to be processed in the
298         *                      current audio cycle
299         */
300        void Engine::ImportEvents(RingBuffer<Event>* pEventQueue, uint Samples) {
301            RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
302            Event* pEvent;
303            while (true) {
304                // get next event from input event queue
305                if (!(pEvent = eventQueueReader.pop())) break;
306                // if younger event reached, ignore that and all subsequent ones for now
307                if (pEvent->FragmentPos() >= Samples) {
308                    eventQueueReader--;
309                    dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
310                    pEvent->ResetFragmentPos();
311                    break;
312                }
313                // copy event to internal event list
314                if (pEvents->poolIsEmpty()) {
315                    dmsg(1,("Event pool emtpy!\n"));
316                    break;
317                }
318                *pEvents->allocAppend() = *pEvent;
319            }
320            eventQueueReader.free(); // free all copied events from input queue
321        }    
322    
323        /**
324       *  Let this engine proceed to render the given amount of sample points. The       *  Let this engine proceed to render the given amount of sample points. The
325       *  calculated audio data of all voices of this engine will be placed into       *  calculated audio data of all voices of this engine will be placed into
326       *  the engine's audio sum buffer which has to be copied and eventually be       *  the engine's audio sum buffer which has to be copied and eventually be
# Line 370  namespace LinuxSampler { namespace gig { Line 333  namespace LinuxSampler { namespace gig {
333      int Engine::RenderAudio(uint Samples) {      int Engine::RenderAudio(uint Samples) {
334          dmsg(5,("RenderAudio(Samples=%d)\n", Samples));          dmsg(5,("RenderAudio(Samples=%d)\n", Samples));
335    
336          // return if no instrument loaded or engine disabled          // return if engine disabled
337          if (EngineDisabled.Pop()) {          if (EngineDisabled.Pop()) {
338              dmsg(5,("gig::Engine: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));              dmsg(5,("gig::Engine: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));
339              return 0;              return 0;
340          }          }
341          if (!pInstrument) {  
342              dmsg(5,("gig::Engine: no instrument loaded\n"));          // update time of start and end of this audio fragment (as events' time stamps relate to this)
343              return 0;          pEventGenerator->UpdateFragmentTime(Samples);
344    
345            // empty the engine's event lists for the new fragment
346            ClearEventLists();
347    
348            // get all events from the engine's global input event queue which belong to the current fragment
349            // (these are usually just SysEx messages)
350            ImportEvents(this->pEventQueue, Samples);
351    
352            // process engine global events (these are currently only MIDI System Exclusive messages)
353            {
354                RTList<Event>::Iterator itEvent = pEvents->first();
355                RTList<Event>::Iterator end     = pEvents->end();
356                for (; itEvent != end; ++itEvent) {
357                    switch (itEvent->Type) {
358                        case Event::type_sysex:
359                            dmsg(5,("Engine: Sysex received\n"));
360                            ProcessSysex(itEvent);
361                            break;
362                    }
363                }
364          }          }
365    
366            // reset internal voice counter (just for statistic of active voices)
367            ActiveVoiceCountTemp = 0;
368    
369          // empty the event lists for the new fragment          // render audio for all engine channels
370          pEvents->clear();          // TODO: should we make voice stealing engine globally? unfortunately this would mean other disadvantages so I left voice stealing in the engine channel space for now
371          pCCEvents->clear();          {
372          for (uint i = 0; i < Event::destination_count; i++) {              std::list<EngineChannel*>::iterator itChannel = engineChannels.begin();
373              pSynthesisEvents[i]->clear();              std::list<EngineChannel*>::iterator end       = engineChannels.end();
374                for (; itChannel != end; itChannel++) {
375                    if (!(*itChannel)->pInstrument) continue; // ignore if no instrument loaded
376                    RenderAudio(*itChannel, Samples);
377                }
378          }          }
379    
380          // read and copy events from input queue          // just some statistics about this engine instance
381          Event event = pEventGenerator->CreateEvent();          ActiveVoiceCount = ActiveVoiceCountTemp;
382          while (true) {          if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;
383              if (!pEventQueue->pop(&event)) break;  
384              pEvents->alloc_assign(event);          return 0;
385        }
386    
387        void Engine::RenderAudio(EngineChannel* pEngineChannel, uint Samples) {
388            // empty the engine's event lists for the new fragment
389            ClearEventLists();
390            // empty the engine channel's, MIDI key specific event lists
391            {
392                RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
393                RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
394                for(; iuiKey != end; ++iuiKey) {
395                    pEngineChannel->pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key
396                }
397          }          }
398    
399    
400          // update time of start and end of this audio fragment (as events' time stamps relate to this)          // get all events from the engine channels's input event queue which belong to the current fragment
401          pEventGenerator->UpdateFragmentTime(Samples);          // (these are the common events like NoteOn, NoteOff, ControlChange, etc.)
402            ImportEvents(pEngineChannel->pEventQueue, Samples);      
403    
404    
405          // process events          // process events
406          Event* pNextEvent = pEvents->first();          {
407          while (pNextEvent) {              RTList<Event>::Iterator itEvent = pEvents->first();
408              Event* pEvent = pNextEvent;              RTList<Event>::Iterator end     = pEvents->end();
409              pEvents->set_current(pEvent);              for (; itEvent != end; ++itEvent) {
410              pNextEvent = pEvents->next();                  switch (itEvent->Type) {
411              switch (pEvent->Type) {                      case Event::type_note_on:
412                  case Event::type_note_on:                          dmsg(5,("Engine: Note on received\n"));
413                      dmsg(5,("Audio Thread: Note on received\n"));                          ProcessNoteOn((EngineChannel*)itEvent->pEngineChannel, itEvent);
414                      ProcessNoteOn(pEvent);                          break;
415                      break;                      case Event::type_note_off:
416                  case Event::type_note_off:                          dmsg(5,("Engine: Note off received\n"));
417                      dmsg(5,("Audio Thread: Note off received\n"));                          ProcessNoteOff((EngineChannel*)itEvent->pEngineChannel, itEvent);
418                      ProcessNoteOff(pEvent);                          break;
419                      break;                      case Event::type_control_change:
420                  case Event::type_control_change:                          dmsg(5,("Engine: MIDI CC received\n"));
421                      dmsg(5,("Audio Thread: MIDI CC received\n"));                          ProcessControlChange((EngineChannel*)itEvent->pEngineChannel, itEvent);
422                      ProcessControlChange(pEvent);                          break;
423                      break;                      case Event::type_pitchbend:
424                  case Event::type_pitchbend:                          dmsg(5,("Engine: Pitchbend received\n"));
425                      dmsg(5,("Audio Thread: Pitchbend received\n"));                          ProcessPitchbend((EngineChannel*)itEvent->pEngineChannel, itEvent);
426                      ProcessPitchbend(pEvent);                          break;
427                      break;                  }
428              }              }
429          }          }
430    
431    
432          // render audio from all active voices          // render audio from all active voices
433          int active_voices = 0;          {
434          uint* piKey = pActiveKeys->first();              RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
435          while (piKey) { // iterate through all active keys              RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
436              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];              while (iuiKey != end) { // iterate through all active keys
437              pActiveKeys->set_current(piKey);                  midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
438              piKey = pActiveKeys->next();                  ++iuiKey;
439    
440              Voice* pVoiceNext = pKey->pActiveVoices->first();                  RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
441              while (pVoiceNext) { // iterate through all voices on this key                  RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
442                  // already get next voice on key                  for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
443                  Voice* pVoice = pVoiceNext;                      // now render current voice
444                  pKey->pActiveVoices->set_current(pVoice);                      itVoice->Render(Samples);
445                  pVoiceNext = pKey->pActiveVoices->next();                      if (itVoice->IsActive()) ActiveVoiceCountTemp++; // still active
446                        else { // voice reached end, is now inactive
447                  // now render current voice                          FreeVoice(pEngineChannel, itVoice); // remove voice from the list of active voices
448                  pVoice->Render(Samples);                      }
449                  if (pVoice->IsActive()) active_voices++; // still active                  }
450                  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  
451          }          }
452    
453            
454          // write that to the disk thread class so that it can print it          // now render all postponed voices from voice stealing
455          // on the console for debugging purposes          {
456          ActiveVoiceCount = active_voices;              RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();
457          if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;              RTList<Event>::Iterator end               = pVoiceStealingQueue->end();
458                for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
459                    Pool<Voice>::Iterator itNewVoice =
460          return 0;                      LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false);
461      }                  if (itNewVoice) {
462                        for (; itNewVoice; itNewVoice = itNewVoice->itChildVoice) {
463      /**                          itNewVoice->Render(Samples);
464       *  Will be called by the MIDIIn Thread to let the audio thread trigger a new                          if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active
465       *  voice for the given key.                          else { // voice reached end, is now inactive
466       *                              FreeVoice(pEngineChannel, itNewVoice); // remove voice from the list of active voices
467       *  @param Key      - MIDI key number of the triggered key                          }
468       *  @param Velocity - MIDI velocity value of the triggered key                      }
469       */                  }
470      void Engine::SendNoteOn(uint8_t Key, uint8_t Velocity) {                  else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));
471          Event event    = pEventGenerator->CreateEvent();              }
472          event.Type     = Event::type_note_on;          }
473          event.Key      = Key;          // reset voice stealing for the new fragment
474          event.Velocity = Velocity;          pVoiceStealingQueue->clear();
475          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          pEngineChannel->itLastStolenVoice = RTList<Voice>::Iterator();
476          else dmsg(1,("Engine: Input event queue full!"));          pEngineChannel->iuiLastStolenKey  = RTList<uint>::Iterator();
477      }          
478    
479      /**          // free all keys which have no active voices left
480       *  Will be called by the MIDIIn Thread to signal the audio thread to release          {
481       *  voice(s) on the given key.              RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
482       *              RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
483       *  @param Key      - MIDI key number of the released key              while (iuiKey != end) { // iterate through all active keys
484       *  @param Velocity - MIDI release velocity value of the released key                  midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
485       */                  ++iuiKey;
486      void Engine::SendNoteOff(uint8_t Key, uint8_t Velocity) {                  if (pKey->pActiveVoices->isEmpty()) FreeKey(pEngineChannel, pKey);
487          Event event    = pEventGenerator->CreateEvent();                  #if DEVMODE
488          event.Type     = Event::type_note_off;                  else { // FIXME: should be removed before the final release (purpose: just a sanity check for debugging)
489          event.Key      = Key;                      RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
490          event.Velocity = Velocity;                      RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
491          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);                      for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
492          else dmsg(1,("Engine: Input event queue full!"));                          if (itVoice->itKillEvent) {
493                                dmsg(1,("gig::Engine: ERROR, killed voice survived !!!\n"));
494                            }
495                        }
496                    }
497                    #endif // DEVMODE
498                }
499            }
500      }      }
501    
502      /**      /**
503       *  Will be called by the MIDIIn Thread to signal the audio thread to change       *  Will be called by the MIDI input device whenever a MIDI system
504       *  the pitch value for all voices.       *  exclusive message has arrived.
505       *       *
506       *  @param Pitch - MIDI pitch value (-8192 ... +8191)       *  @param pData - pointer to sysex data
507         *  @param Size  - lenght of sysex data (in bytes)
508       */       */
509      void Engine::SendPitchbend(int Pitch) {      void Engine::SendSysex(void* pData, uint Size) {
510          Event event = pEventGenerator->CreateEvent();          Event event             = pEventGenerator->CreateEvent();
511          event.Type  = Event::type_pitchbend;          event.Type              = Event::type_sysex;
512          event.Pitch = Pitch;          event.Param.Sysex.Size  = Size;
513          if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);          event.pEngineChannel    = NULL; // as Engine global event
514          else dmsg(1,("Engine: Input event queue full!"));          if (pEventQueue->write_space() > 0) {
515      }              if (pSysexBuffer->write_space() >= Size) {
516                    // copy sysex data to input buffer
517                    uint toWrite = Size;
518                    uint8_t* pPos = (uint8_t*) pData;
519                    while (toWrite) {
520                        const uint writeNow = RTMath::Min(toWrite, pSysexBuffer->write_space_to_end());
521                        pSysexBuffer->write(pPos, writeNow);
522                        toWrite -= writeNow;
523                        pPos    += writeNow;
524    
525      /**                  }
526       *  Will be called by the MIDIIn Thread to signal the audio thread that a                  // finally place sysex event into input event queue
527       *  continuous controller value has changed.                  pEventQueue->push(&event);
528       *              }
529       *  @param Controller - MIDI controller number of the occured control change              else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,SYSEX_BUFFER_SIZE));
530       *  @param Value      - value of the control change          }
      */  
     void Engine::SendControlChange(uint8_t Controller, uint8_t Value) {  
         Event event      = pEventGenerator->CreateEvent();  
         event.Type       = Event::type_control_change;  
         event.Controller = Controller;  
         event.Value      = Value;  
         if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);  
531          else dmsg(1,("Engine: Input event queue full!"));          else dmsg(1,("Engine: Input event queue full!"));
532      }      }
533    
534      /**      /**
535       *  Assigns and triggers a new voice for the respective MIDI key.       *  Assigns and triggers a new voice for the respective MIDI key.
536       *       *
537       *  @param pNoteOnEvent - key, velocity and time stamp of the event       *  @param pEngineChannel - engine channel on which this event occured on
538         *  @param itNoteOnEvent - key, velocity and time stamp of the event
539       */       */
540      void Engine::ProcessNoteOn(Event* pNoteOnEvent) {      void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
541          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Key];          
542            const int key = itNoteOnEvent->Param.Note.Key;
543    
544            // Change key dimension value if key is in keyswitching area
545            {
546                const ::gig::Instrument* pInstrument = pEngineChannel->pInstrument;
547                if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high)
548                    pEngineChannel->CurrentKeyDimension = ((key - pInstrument->DimensionKeyRange.low) * 128) /
549                        (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1);
550            }
551    
552            midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[key];
553    
554          pKey->KeyPressed = true; // the MIDI key was now pressed down          pKey->KeyPressed = true; // the MIDI key was now pressed down
555    
556          // cancel release process of voices on this key if needed          // cancel release process of voices on this key if needed
557          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !pEngineChannel->SustainPedal) {
558              Event* pCancelReleaseEvent = pKey->pEvents->alloc();              RTList<Event>::Iterator itCancelReleaseEvent = pKey->pEvents->allocAppend();
559              if (pCancelReleaseEvent) {              if (itCancelReleaseEvent) {
560                  *pCancelReleaseEvent = *pNoteOnEvent;                  *itCancelReleaseEvent = *itNoteOnEvent;                  // copy event
561                  pCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type                  itCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type
562              }              }
563              else dmsg(1,("Event pool emtpy!\n"));              else dmsg(1,("Event pool emtpy!\n"));
564          }          }
565    
566          // allocate and trigger a new voice for the key          // move note on event to the key's own event list
567          LaunchVoice(pNoteOnEvent);          RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
568    
569          // finally move note on event to the key's own event list          // allocate and trigger a new voice for the key
570          pEvents->move(pNoteOnEvent, pKey->pEvents);          LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, 0, false, true);
571      }      }
572    
573      /**      /**
# Line 557  namespace LinuxSampler { namespace gig { Line 576  namespace LinuxSampler { namespace gig {
576       *  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.
577       *  due to completion of sample playback).       *  due to completion of sample playback).
578       *       *
579       *  @param pNoteOffEvent - key, velocity and time stamp of the event       *  @param pEngineChannel - engine channel on which this event occured on
580         *  @param itNoteOffEvent - key, velocity and time stamp of the event
581       */       */
582      void Engine::ProcessNoteOff(Event* pNoteOffEvent) {      void Engine::ProcessNoteOff(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOffEvent) {
583          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOffEvent->Key];          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOffEvent->Param.Note.Key];
584    
585          pKey->KeyPressed = false; // the MIDI key was now released          pKey->KeyPressed = false; // the MIDI key was now released
586    
587          // release voices on this key if needed          // release voices on this key if needed
588          if (pKey->Active && !SustainPedal) {          if (pKey->Active && !pEngineChannel->SustainPedal) {
589              pNoteOffEvent->Type = Event::type_release; // transform event type              itNoteOffEvent->Type = Event::type_release; // transform event type
590          }          }
591    
592            // move event to the key's own event list
593            RTList<Event>::Iterator itNoteOffEventOnKeyList = itNoteOffEvent.moveToEndOf(pKey->pEvents);
594    
595          // spawn release triggered voice(s) if needed          // spawn release triggered voice(s) if needed
596          if (pKey->ReleaseTrigger) {          if (pKey->ReleaseTrigger) {
597              LaunchVoice(pNoteOffEvent, 0, true);              LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, 0, true, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
598              pKey->ReleaseTrigger = false;              pKey->ReleaseTrigger = false;
599          }          }
   
         // move event to the key's own event list  
         pEvents->move(pNoteOffEvent, pKey->pEvents);  
600      }      }
601    
602      /**      /**
603       *  Moves pitchbend event from the general (input) event list to the pitch       *  Moves pitchbend event from the general (input) event list to the pitch
604       *  event list.       *  event list.
605       *       *
606       *  @param pPitchbendEvent - absolute pitch value and time stamp of the event       *  @param pEngineChannel - engine channel on which this event occured on
607         *  @param itPitchbendEvent - absolute pitch value and time stamp of the event
608       */       */
609      void Engine::ProcessPitchbend(Event* pPitchbendEvent) {      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {
610          this->Pitch = pPitchbendEvent->Pitch; // store current pitch value          pEngineChannel->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value
611          pEvents->move(pPitchbendEvent, pSynthesisEvents[Event::destination_vco]);          itPitchbendEvent.moveToEndOf(pSynthesisEvents[Event::destination_vco]);
612      }      }
613    
614      /**      /**
# Line 595  namespace LinuxSampler { namespace gig { Line 616  namespace LinuxSampler { namespace gig {
616       *  called by the ProcessNoteOn() method and by the voices itself       *  called by the ProcessNoteOn() method and by the voices itself
617       *  (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).
618       *       *
619       *  @param pNoteOnEvent        - key, velocity and time stamp of the event       *  @param pEngineChannel      - engine channel on which this event occured on
620         *  @param itNoteOnEvent       - key, velocity and time stamp of the event
621       *  @param iLayer              - layer index for the new voice (optional - only       *  @param iLayer              - layer index for the new voice (optional - only
622       *                               in case of layered sounds of course)       *                               in case of layered sounds of course)
623       *  @param ReleaseTriggerVoice - if new voice is a release triggered voice       *  @param ReleaseTriggerVoice - if new voice is a release triggered voice
624       *                               (optional, default = false)       *                               (optional, default = false)
625         *  @param VoiceStealing       - if voice stealing should be performed
626         *                               when there is no free voice
627         *                               (optional, default = true)
628         *  @returns pointer to new voice or NULL if there was no free voice or
629         *           if the voice wasn't triggered (for example when no region is
630         *           defined for the given key).
631       */       */
632      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) {
633          midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Key];          midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
634    
635          // allocate a new voice for the key          // allocate a new voice for the key
636          Voice* pNewVoice = pKey->pActiveVoices->alloc();          Pool<Voice>::Iterator itNewVoice = pKey->pActiveVoices->allocAppend();
637          if (pNewVoice) {          if (itNewVoice) {
638              // launch the new voice              // launch the new voice
639              if (pNewVoice->Trigger(pNoteOnEvent, this->Pitch, this->pInstrument, iLayer, ReleaseTriggerVoice) < 0) {              if (itNewVoice->Trigger(pEngineChannel, itNoteOnEvent, pEngineChannel->Pitch, pEngineChannel->pInstrument, iLayer, ReleaseTriggerVoice, VoiceStealing) < 0) {
640                  dmsg(1,("Triggering new voice failed!\n"));                  dmsg(4,("Voice not triggered\n"));
641                  pKey->pActiveVoices->free(pNewVoice);                  pKey->pActiveVoices->free(itNewVoice);
642              }              }
643              else { // on success              else { // on success
644                  uint** ppKeyGroup = NULL;                  uint** ppKeyGroup = NULL;
645                  if (pNewVoice->KeyGroup) { // if this voice / key belongs to a key group                  if (itNewVoice->KeyGroup) { // if this voice / key belongs to a key group
646                      ppKeyGroup = &ActiveKeyGroups[pNewVoice->KeyGroup];                      ppKeyGroup = &pEngineChannel->ActiveKeyGroups[itNewVoice->KeyGroup];
647                      if (*ppKeyGroup) { // if there's already an active key in that key group                      if (*ppKeyGroup) { // if there's already an active key in that key group
648                          midi_key_info_t* pOtherKey = &pMIDIKeyInfo[**ppKeyGroup];                          midi_key_info_t* pOtherKey = &pEngineChannel->pMIDIKeyInfo[**ppKeyGroup];
649                          // kill all voices on the (other) key                          // kill all voices on the (other) key
650                          Voice* pVoiceToBeKilled = pOtherKey->pActiveVoices->first();                          RTList<Voice>::Iterator itVoiceToBeKilled = pOtherKey->pActiveVoices->first();
651                          while (pVoiceToBeKilled) {                          RTList<Voice>::Iterator end               = pOtherKey->pActiveVoices->end();
652                              Voice* pVoiceToBeKilledNext = pOtherKey->pActiveVoices->next();                          for (; itVoiceToBeKilled != end; ++itVoiceToBeKilled) {
653                              if (pVoiceToBeKilled->Type != Voice::type_release_trigger) pVoiceToBeKilled->Kill(pNoteOnEvent);                              if (itVoiceToBeKilled->Type != Voice::type_release_trigger) itVoiceToBeKilled->Kill(itNoteOnEvent);
                             pOtherKey->pActiveVoices->set_current(pVoiceToBeKilled);  
                             pVoiceToBeKilled = pVoiceToBeKilledNext;  
654                          }                          }
655                      }                      }
656                  }                  }
657                  if (!pKey->Active) { // mark as active key                  if (!pKey->Active) { // mark as active key
658                      pKey->Active = true;                      pKey->Active = true;
659                      pKey->pSelf  = pActiveKeys->alloc();                      pKey->itSelf = pEngineChannel->pActiveKeys->allocAppend();
660                      *pKey->pSelf = pNoteOnEvent->Key;                      *pKey->itSelf = itNoteOnEvent->Param.Note.Key;
661                  }                  }
662                  if (pNewVoice->KeyGroup) {                  if (itNewVoice->KeyGroup) {
663                      *ppKeyGroup = pKey->pSelf; // put key as the (new) active key to its key group                      *ppKeyGroup = &*pKey->itSelf; // put key as the (new) active key to its key group
664                  }                  }
665                  if (pNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)                  if (itNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s)
666                    return itNewVoice; // success
667              }              }
668          }          }
669          else std::cerr << "No free voice!" << std::endl << std::flush;          else if (VoiceStealing) {
670                // first, get total amount of required voices (dependant on amount of layers)
671                ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOnEvent->Param.Note.Key);
672                if (!pRegion) return Pool<Voice>::Iterator(); // nothing defined for this MIDI key, so no voice needed
673                int voicesRequired = pRegion->Layers;
674    
675                // now steal the (remaining) amount of voices
676                for (int i = iLayer; i < voicesRequired; i++)
677                    StealVoice(pEngineChannel, itNoteOnEvent);
678    
679                // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died
680                RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();
681                if (itStealEvent) {
682                    *itStealEvent = *itNoteOnEvent; // copy event
683                    itStealEvent->Param.Note.Layer = iLayer;
684                    itStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice;
685                }
686                else dmsg(1,("Voice stealing queue full!\n"));
687            }
688    
689            return Pool<Voice>::Iterator(); // no free voice or error
690      }      }
691    
692      /**      /**
693       *  Immediately kills the voice given with pVoice (no matter if sustain is       *  Will be called by LaunchVoice() method in case there are no free
694       *  pressed or not) and removes it from the MIDI key's list of active voice.       *  voices left. This method will select and kill one old voice for
695       *  This method will e.g. be called if a voice went inactive by itself.       *  voice stealing and postpone the note-on event until the selected
696         *  voice actually died.
697       *       *
698       *  @param pVoice - points to the voice to be killed       *  @param pEngineChannel - engine channel on which this event occured on
699         *  @param itNoteOnEvent - key, velocity and time stamp of the event
700       */       */
701      void Engine::KillVoiceImmediately(Voice* pVoice) {      void Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
702          if (pVoice) {          if (!pEventPool->poolIsEmpty()) {
703              if (pVoice->IsActive()) pVoice->KillImmediately();  
704                RTList<uint>::Iterator  iuiOldestKey;
705                RTList<Voice>::Iterator itOldestVoice;
706    
707                // Select one voice for voice stealing
708                switch (VOICE_STEAL_ALGORITHM) {
709    
710                    // try to pick the oldest voice on the key where the new
711                    // voice should be spawned, if there is no voice on that
712                    // key, or no voice left to kill there, then procceed with
713                    // 'oldestkey' algorithm
714                    case voice_steal_algo_keymask: {
715                        midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
716                        if (pEngineChannel->itLastStolenVoice) {
717                            itOldestVoice = pEngineChannel->itLastStolenVoice;
718                            ++itOldestVoice;
719                        }
720                        else { // no voice stolen in this audio fragment cycle yet
721                            itOldestVoice = pOldestKey->pActiveVoices->first();
722                        }
723                        if (itOldestVoice) {
724                            iuiOldestKey = pOldestKey->itSelf;
725                            break; // selection succeeded
726                        }
727                    } // no break - intentional !
728    
729                    // try to pick the oldest voice on the oldest active key
730                    // (caution: must stay after 'keymask' algorithm !)
731                    case voice_steal_algo_oldestkey: {
732                        if (pEngineChannel->itLastStolenVoice) {
733                            midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[*pEngineChannel->iuiLastStolenKey];
734                            itOldestVoice = pEngineChannel->itLastStolenVoice;
735                            ++itOldestVoice;
736                            if (!itOldestVoice) {
737                                iuiOldestKey = pEngineChannel->iuiLastStolenKey;
738                                ++iuiOldestKey;
739                                if (iuiOldestKey) {
740                                    midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[*iuiOldestKey];
741                                    itOldestVoice = pOldestKey->pActiveVoices->first();
742                                }
743                                else {
744                                    dmsg(1,("gig::Engine: Warning, too less voices, even for voice stealing! - Better recompile with higher MAX_AUDIO_VOICES.\n"));
745                                    return;
746                                }
747                            }
748                            else iuiOldestKey = pEngineChannel->iuiLastStolenKey;
749                        }
750                        else { // no voice stolen in this audio fragment cycle yet
751                            iuiOldestKey = pEngineChannel->pActiveKeys->first();
752                            midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[*iuiOldestKey];
753                            itOldestVoice = pOldestKey->pActiveVoices->first();
754                        }
755                        break;
756                    }
757    
758              midi_key_info_t* pKey = &pMIDIKeyInfo[pVoice->MIDIKey];                  // don't steal anything
759                    case voice_steal_algo_none:
760                    default: {
761                        dmsg(1,("No free voice (voice stealing disabled)!\n"));
762                        return;
763                    }
764                }
765    
766                //FIXME: can be removed, just a sanity check for debugging
767                if (!itOldestVoice->IsActive()) dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
768    
769                // now kill the selected voice
770                itOldestVoice->Kill(itNoteOnEvent);
771                // remember which voice on which key we stole, so we can simply proceed for the next voice stealing
772                pEngineChannel->itLastStolenVoice = itOldestVoice;
773                pEngineChannel->iuiLastStolenKey = iuiOldestKey;
774            }
775            else dmsg(1,("Event pool emtpy!\n"));
776        }
777    
778        /**
779         *  Removes the given voice from the MIDI key's list of active voices.
780         *  This method will be called when a voice went inactive, e.g. because
781         *  it finished to playback its sample, finished its release stage or
782         *  just was killed.
783         *
784         *  @param pEngineChannel - engine channel on which this event occured on
785         *  @param itVoice - points to the voice to be freed
786         */
787        void Engine::FreeVoice(EngineChannel* pEngineChannel, Pool<Voice>::Iterator& itVoice) {
788            if (itVoice) {
789                midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[itVoice->MIDIKey];
790    
791                uint keygroup = itVoice->KeyGroup;
792    
793              // free the voice object              // free the voice object
794              pVoicePool->free(pVoice);              pVoicePool->free(itVoice);
795    
796              // 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
797              if (pKey->pActiveVoices->is_empty()) {              if (pKey->pActiveVoices->isEmpty() && keygroup) {
798                  if (pVoice->KeyGroup) { // if voice / key belongs to a key group                  uint** ppKeyGroup = &pEngineChannel->ActiveKeyGroups[keygroup];
799                      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"));  
800              }              }
801          }          }
802          else std::cerr << "Couldn't release voice! (pVoice == NULL)\n" << std::flush;          else std::cerr << "Couldn't release voice! (!itVoice)\n" << std::flush;
803        }
804    
805        /**
806         *  Called when there's no more voice left on a key, this call will
807         *  update the key info respectively.
808         *
809         *  @param pEngineChannel - engine channel on which this event occured on
810         *  @param pKey - key which is now inactive
811         */
812        void Engine::FreeKey(EngineChannel* pEngineChannel, midi_key_info_t* pKey) {
813            if (pKey->pActiveVoices->isEmpty()) {
814                pKey->Active = false;
815                pEngineChannel->pActiveKeys->free(pKey->itSelf); // remove key from list of active keys
816                pKey->itSelf = RTList<uint>::Iterator();
817                pKey->ReleaseTrigger = false;
818                pKey->pEvents->clear();
819                dmsg(3,("Key has no more voices now\n"));
820            }
821            else dmsg(1,("gig::Engine: Oops, tried to free a key which contains voices.\n"));
822      }      }
823    
824      /**      /**
825       *  Reacts on supported control change commands (e.g. pitch bend wheel,       *  Reacts on supported control change commands (e.g. pitch bend wheel,
826       *  modulation wheel, aftertouch).       *  modulation wheel, aftertouch).
827       *       *
828       *  @param pControlChangeEvent - controller, value and time stamp of the event       *  @param pEngineChannel - engine channel on which this event occured on
829         *  @param itControlChangeEvent - controller, value and time stamp of the event
830       */       */
831      void Engine::ProcessControlChange(Event* pControlChangeEvent) {      void Engine::ProcessControlChange(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itControlChangeEvent) {
832          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));
833    
834          switch (pControlChangeEvent->Controller) {          switch (itControlChangeEvent->Param.CC.Controller) {
835              case 64: {              case 64: {
836                  if (pControlChangeEvent->Value >= 64 && !SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {
837                      dmsg(4,("PEDAL DOWN\n"));                      dmsg(4,("PEDAL DOWN\n"));
838                      SustainPedal = true;                      pEngineChannel->SustainPedal = true;
839    
840                      // cancel release process of voices if necessary                      // cancel release process of voices if necessary
841                      uint* piKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
842                      if (piKey) {                      if (iuiKey) {
843                          pControlChangeEvent->Type = Event::type_cancel_release; // transform event type                          itControlChangeEvent->Type = Event::type_cancel_release; // transform event type
844                          while (piKey) {                          while (iuiKey) {
845                              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];                              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
846                              pActiveKeys->set_current(piKey);                              ++iuiKey;
                             piKey = pActiveKeys->next();  
847                              if (!pKey->KeyPressed) {                              if (!pKey->KeyPressed) {
848                                  Event* pNewEvent = pKey->pEvents->alloc();                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
849                                  if (pNewEvent) *pNewEvent = *pControlChangeEvent; // copy event to the key's own event list                                  if (itNewEvent) *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
850                                  else dmsg(1,("Event pool emtpy!\n"));                                  else dmsg(1,("Event pool emtpy!\n"));
851                              }                              }
852                          }                          }
853                      }                      }
854                  }                  }
855                  if (pControlChangeEvent->Value < 64 && SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value < 64 && pEngineChannel->SustainPedal) {
856                      dmsg(4,("PEDAL UP\n"));                      dmsg(4,("PEDAL UP\n"));
857                      SustainPedal = false;                      pEngineChannel->SustainPedal = false;
858    
859                      // release voices if their respective key is not pressed                      // release voices if their respective key is not pressed
860                      uint* piKey = pActiveKeys->first();                      RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
861                      if (piKey) {                      if (iuiKey) {
862                          pControlChangeEvent->Type = Event::type_release; // transform event type                          itControlChangeEvent->Type = Event::type_release; // transform event type
863                          while (piKey) {                          while (iuiKey) {
864                              midi_key_info_t* pKey = &pMIDIKeyInfo[*piKey];                              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
865                              pActiveKeys->set_current(piKey);                              ++iuiKey;
                             piKey = pActiveKeys->next();  
866                              if (!pKey->KeyPressed) {                              if (!pKey->KeyPressed) {
867                                  Event* pNewEvent = pKey->pEvents->alloc();                                  RTList<Event>::Iterator itNewEvent = pKey->pEvents->allocAppend();
868                                  if (pNewEvent) *pNewEvent = *pControlChangeEvent; // copy event to the key's own event list                                  if (itNewEvent) *itNewEvent = *itControlChangeEvent; // copy event to the key's own event list
869                                  else dmsg(1,("Event pool emtpy!\n"));                                  else dmsg(1,("Event pool emtpy!\n"));
870                              }                              }
871                          }                          }
# Line 730  namespace LinuxSampler { namespace gig { Line 876  namespace LinuxSampler { namespace gig {
876          }          }
877    
878          // update controller value in the engine's controller table          // update controller value in the engine's controller table
879          ControllerTable[pControlChangeEvent->Controller] = pControlChangeEvent->Value;          pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
880    
881          // move event from the unsorted event list to the control change event list          // move event from the unsorted event list to the control change event list
882          pEvents->move(pControlChangeEvent, pCCEvents);          itControlChangeEvent.moveToEndOf(pCCEvents);
883        }
884    
885        /**
886         *  Reacts on MIDI system exclusive messages.
887         *
888         *  @param itSysexEvent - sysex data size and time stamp of the sysex event
889         */
890        void Engine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) {
891            RingBuffer<uint8_t>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();
892    
893            uint8_t exclusive_status, id;
894            if (!reader.pop(&exclusive_status)) goto free_sysex_data;
895            if (!reader.pop(&id))               goto free_sysex_data;
896            if (exclusive_status != 0xF0)       goto free_sysex_data;
897    
898            switch (id) {
899                case 0x41: { // Roland
900                    uint8_t device_id, model_id, cmd_id;
901                    if (!reader.pop(&device_id)) goto free_sysex_data;
902                    if (!reader.pop(&model_id))  goto free_sysex_data;
903                    if (!reader.pop(&cmd_id))    goto free_sysex_data;
904                    if (model_id != 0x42 /*GS*/) goto free_sysex_data;
905                    if (cmd_id != 0x12 /*DT1*/)  goto free_sysex_data;
906    
907                    // command address
908                    uint8_t addr[3]; // 2 byte addr MSB, followed by 1 byte addr LSB)
909                    const RingBuffer<uint8_t>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later
910                    if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;
911                    if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters
912                    }
913                    else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters
914                    }
915                    else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)
916                        switch (addr[3]) {
917                            case 0x40: { // scale tuning
918                                uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave
919                                if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;
920                                uint8_t checksum;
921                                if (!reader.pop(&checksum))                      goto free_sysex_data;
922                                if (GSCheckSum(checksum_reader, 12) != checksum) goto free_sysex_data;
923                                for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;
924                                AdjustScale((int8_t*) scale_tunes);
925                                break;
926                            }
927                        }
928                    }
929                    else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x20) { // Part Parameters (2)
930                    }
931                    else if (addr[0] == 0x41) { // Drum Setup Parameters
932                    }
933                    break;
934                }
935            }
936    
937            free_sysex_data: // finally free sysex data
938            pSysexBuffer->increment_read_ptr(itSysexEvent->Param.Sysex.Size);
939        }
940    
941        /**
942         * Calculates the Roland GS sysex check sum.
943         *
944         * @param AddrReader - reader which currently points to the first GS
945         *                     command address byte of the GS sysex message in
946         *                     question
947         * @param DataSize   - size of the GS message data (in bytes)
948         */
949        uint8_t Engine::GSCheckSum(const RingBuffer<uint8_t>::NonVolatileReader AddrReader, uint DataSize) {
950            RingBuffer<uint8_t>::NonVolatileReader reader = AddrReader;
951            uint bytes = 3 /*addr*/ + DataSize;
952            uint8_t addr_and_data[bytes];
953            reader.read(&addr_and_data[0], bytes);
954            uint8_t sum = 0;
955            for (uint i = 0; i < bytes; i++) sum += addr_and_data[i];
956            return 128 - sum % 128;
957        }
958    
959        /**
960         * Allows to tune each of the twelve semitones of an octave.
961         *
962         * @param ScaleTunes - detuning of all twelve semitones (in cents)
963         */
964        void Engine::AdjustScale(int8_t ScaleTunes[12]) {
965            memcpy(&this->ScaleTuning[0], &ScaleTunes[0], 12); //TODO: currently not sample accurate
966      }      }
967    
968      /**      /**
# Line 749  namespace LinuxSampler { namespace gig { Line 978  namespace LinuxSampler { namespace gig {
978             m[i+2] = val;             m[i+2] = val;
979             m[i+3] = val;             m[i+3] = val;
980          }          }
981      }      }    
   
     float Engine::Volume() {  
         return GlobalVolume;  
     }  
   
     void Engine::Volume(float f) {  
         GlobalVolume = f;  
     }  
   
     uint Engine::Channels() {  
         return 2;  
     }  
   
     void Engine::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) {  
         AudioChannel* pChannel = pAudioOutputDevice->Channel(AudioDeviceChannel);  
         if (!pChannel) throw AudioOutputException("Invalid audio output device channel " + ToString(AudioDeviceChannel));  
         switch (EngineAudioChannel) {  
             case 0: // left output channel  
                 pOutputLeft = pChannel->Buffer();  
                 AudioDeviceChannelLeft = AudioDeviceChannel;  
                 break;  
             case 1: // right output channel  
                 pOutputRight = pChannel->Buffer();  
                 AudioDeviceChannelRight = AudioDeviceChannel;  
                 break;  
             default:  
                 throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));  
         }  
     }  
   
     int Engine::OutputChannel(uint EngineAudioChannel) {  
         switch (EngineAudioChannel) {  
             case 0: // left channel  
                 return AudioDeviceChannelLeft;  
             case 1: // right channel  
                 return AudioDeviceChannelRight;  
             default:  
                 throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));  
         }  
     }  
982    
983      uint Engine::VoiceCount() {      uint Engine::VoiceCount() {
984          return ActiveVoiceCount;          return ActiveVoiceCount;
# Line 823  namespace LinuxSampler { namespace gig { Line 1012  namespace LinuxSampler { namespace gig {
1012          return "GigEngine";          return "GigEngine";
1013      }      }
1014    
     String Engine::InstrumentFileName() {  
         return InstrumentFile;  
     }  
   
     int Engine::InstrumentIndex() {  
         return InstrumentIdx;  
     }  
   
     int Engine::InstrumentStatus() {  
         return InstrumentStat;  
     }  
   
1015      String Engine::Description() {      String Engine::Description() {
1016          return "Gigasampler Engine";          return "Gigasampler Engine";
1017      }      }
1018    
1019      String Engine::Version() {      String Engine::Version() {
1020          String s = "$Revision: 1.11 $";          String s = "$Revision: 1.27 $";
1021          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
1022      }      }
1023    

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

  ViewVC Help
Powered by ViewVC