/[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 411 by schoenebeck, Sat Feb 26 02:01:14 2005 UTC revision 466 by schoenebeck, Tue Mar 15 19:27:01 2005 UTC
# Line 25  Line 25 
25  #include "DiskThread.h"  #include "DiskThread.h"
26  #include "Voice.h"  #include "Voice.h"
27  #include "EGADSR.h"  #include "EGADSR.h"
28    #include "../EngineFactory.h"
29    
30  #include "Engine.h"  #include "Engine.h"
31    
# Line 40  namespace LinuxSampler { namespace gig { Line 41  namespace LinuxSampler { namespace gig {
41    
42      std::map<AudioOutputDevice*,Engine*> Engine::engines;      std::map<AudioOutputDevice*,Engine*> Engine::engines;
43    
44        /**
45         * Get a gig::Engine object for the given gig::EngineChannel and the
46         * given AudioOutputDevice. All engine channels which are connected to
47         * the same audio output device will use the same engine instance. This
48         * method will be called by a gig::EngineChannel whenever it's
49         * connecting to a audio output device.
50         *
51         * @param pChannel - engine channel which acquires an engine object
52         * @param pDevice  - the audio output device \a pChannel is connected to
53         */
54      Engine* Engine::AcquireEngine(LinuxSampler::gig::EngineChannel* pChannel, AudioOutputDevice* pDevice) {      Engine* Engine::AcquireEngine(LinuxSampler::gig::EngineChannel* pChannel, AudioOutputDevice* pDevice) {
55          Engine* pEngine;          Engine* pEngine = NULL;
56            // check if there's already an engine for the given audio output device
57          if (engines.count(pDevice)) {          if (engines.count(pDevice)) {
58                dmsg(4,("Using existing gig::Engine.\n"));
59              pEngine = engines[pDevice];              pEngine = engines[pDevice];
60          } else {          } else { // create a new engine (and disk thread) instance for the given audio output device
61              pEngine = new Engine;              dmsg(4,("Creating new gig::Engine.\n"));
62                pEngine = (Engine*) EngineFactory::Create("gig");
63              pEngine->Connect(pDevice);              pEngine->Connect(pDevice);
64                engines[pDevice] = pEngine;
65          }          }
66          pEngine->samplerChannels.push_back(pChannel);          // register engine channel to the engine instance
67            pEngine->engineChannels.add(pChannel);
68            // remember index in the ArrayList
69            pChannel->iEngineIndexSelf = pEngine->engineChannels.size() - 1;
70            dmsg(4,("This gig::Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));
71          return pEngine;          return pEngine;
72      }      }
73    
74        /**
75         * Once an engine channel is disconnected from an audio output device,
76         * it wil immediately call this method to unregister itself from the
77         * engine instance and if that engine instance is not used by any other
78         * engine channel anymore, then that engine instance will be destroyed.
79         *
80         * @param pChannel - engine channel which wants to disconnect from it's
81         *                   engine instance
82         * @param pDevice  - audio output device \a pChannel was connected to
83         */
84      void Engine::FreeEngine(LinuxSampler::gig::EngineChannel* pChannel, AudioOutputDevice* pDevice) {      void Engine::FreeEngine(LinuxSampler::gig::EngineChannel* pChannel, AudioOutputDevice* pDevice) {
85            dmsg(4,("Disconnecting EngineChannel from gig::Engine.\n"));
86          Engine* pEngine = engines[pDevice];          Engine* pEngine = engines[pDevice];
87          pEngine->samplerChannels.remove(pChannel);          // unregister EngineChannel from the Engine instance
88          if (pEngine->samplerChannels.empty()) delete pEngine;          pEngine->engineChannels.remove(pChannel);
89            // if the used Engine instance is not used anymore, then destroy it
90            if (pEngine->engineChannels.empty()) {
91                pDevice->Disconnect(pEngine);
92                engines.erase(pDevice);
93                delete pEngine;
94                dmsg(4,("Destroying gig::Engine.\n"));
95            }
96            else dmsg(4,("This gig::Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));
97      }      }
98    
99      Engine::Engine() {      Engine::Engine() {
# Line 65  namespace LinuxSampler { namespace gig { Line 103  namespace LinuxSampler { namespace gig {
103          pSysexBuffer       = new RingBuffer<uint8_t>(SYSEX_BUFFER_SIZE, 0);          pSysexBuffer       = new RingBuffer<uint8_t>(SYSEX_BUFFER_SIZE, 0);
104          pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT, 0);          pEventQueue        = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT, 0);
105          pEventPool         = new Pool<Event>(MAX_EVENTS_PER_FRAGMENT);          pEventPool         = new Pool<Event>(MAX_EVENTS_PER_FRAGMENT);
106          pVoicePool         = new Pool<Voice>(MAX_AUDIO_VOICES);                  pVoicePool         = new Pool<Voice>(MAX_AUDIO_VOICES);
107          pVoiceStealingQueue = new RTList<Event>(pEventPool);          pVoiceStealingQueue = new RTList<Event>(pEventPool);
108          pEvents            = new RTList<Event>(pEventPool);          pGlobalEvents      = new RTList<Event>(pEventPool);
         pCCEvents          = new RTList<Event>(pEventPool);  
           
         for (uint i = 0; i < Event::destination_count; i++) {  
             pSynthesisEvents[i] = new RTList<Event>(pEventPool);  
         }  
109          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {          for (RTList<Voice>::Iterator iterVoice = pVoicePool->allocAppend(); iterVoice == pVoicePool->last(); iterVoice = pVoicePool->allocAppend()) {
110              iterVoice->SetEngine(this);              iterVoice->SetEngine(this);
111          }          }
# Line 92  namespace LinuxSampler { namespace gig { Line 125  namespace LinuxSampler { namespace gig {
125              delete pDiskThread;              delete pDiskThread;
126              dmsg(1,("OK\n"));              dmsg(1,("OK\n"));
127          }          }
         for (uint i = 0; i < Event::destination_count; i++) {  
             if (pSynthesisEvents[i]) delete pSynthesisEvents[i];  
         }  
         if (pEvents)     delete pEvents;  
         if (pCCEvents)   delete pCCEvents;  
128          if (pEventQueue) delete pEventQueue;          if (pEventQueue) delete pEventQueue;
129          if (pEventPool)  delete pEventPool;          if (pEventPool)  delete pEventPool;
130          if (pVoicePool) {          if (pVoicePool) {
# Line 109  namespace LinuxSampler { namespace gig { Line 137  namespace LinuxSampler { namespace gig {
137          if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);          if (pSynthesisParameters[0]) free(pSynthesisParameters[0]);
138          if (pVoiceStealingQueue) delete pVoiceStealingQueue;          if (pVoiceStealingQueue) delete pVoiceStealingQueue;
139          if (pSysexBuffer) delete pSysexBuffer;          if (pSysexBuffer) delete pSysexBuffer;
140            EngineFactory::Destroy(this);
141      }      }
142    
143      void Engine::Enable() {      void Engine::Enable() {
# Line 148  namespace LinuxSampler { namespace gig { Line 177  namespace LinuxSampler { namespace gig {
177          ActiveVoiceCountMax = 0;          ActiveVoiceCountMax = 0;
178    
179          // reset voice stealing parameters          // reset voice stealing parameters
         itLastStolenVoice = RTList<Voice>::Iterator();  
         iuiLastStolenKey  = RTList<uint>::Iterator();  
180          pVoiceStealingQueue->clear();          pVoiceStealingQueue->clear();
181            itLastStolenVoice  = RTList<Voice>::Iterator();
182            iuiLastStolenKey   = RTList<uint>::Iterator();
183            pLastStolenChannel = NULL;
184    
185          // reset to normal chromatic scale (means equal temper)          // reset to normal chromatic scale (means equal temper)
186          memset(&ScaleTuning[0], 0x00, 12);          memset(&ScaleTuning[0], 0x00, 12);
# Line 181  namespace LinuxSampler { namespace gig { Line 211  namespace LinuxSampler { namespace gig {
211              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();
212              throw LinuxSamplerException(msg);              throw LinuxSamplerException(msg);
213          }          }
214            
215          this->MaxSamplesPerCycle      = pAudioOutputDevice->MaxSamplesPerCycle();          this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle();
216          this->SampleRate              = pAudioOutputDevice->SampleRate();          this->SampleRate         = pAudioOutputDevice->SampleRate();
217    
218          // FIXME: audio drivers with varying fragment sizes might be a problem here          // FIXME: audio drivers with varying fragment sizes might be a problem here
219          MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * EG_MIN_RELEASE_TIME) - 1;          MaxFadeOutPos = MaxSamplesPerCycle - int(double(SampleRate) * EG_MIN_RELEASE_TIME) - 1;
# Line 242  namespace LinuxSampler { namespace gig { Line 272  namespace LinuxSampler { namespace gig {
272          }          }
273      }      }
274    
275        void Engine::ClearEventLists() {
276            pGlobalEvents->clear();
277        }
278    
279        /**
280         * Copy all events from the engine's global input queue buffer to the
281         * engine's internal event list. This will be done at the beginning of
282         * each audio cycle (that is each RenderAudio() call) to distinguish
283         * all global events which have to be processed in the current audio
284         * cycle. These events are usually just SysEx messages. Every
285         * EngineChannel has it's own input event queue buffer and event list
286         * to handle common events like NoteOn, NoteOff and ControlChange
287         * events.
288         *
289         * @param Samples - number of sample points to be processed in the
290         *                  current audio cycle
291         */
292        void Engine::ImportEvents(uint Samples) {
293            RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
294            Event* pEvent;
295            while (true) {
296                // get next event from input event queue
297                if (!(pEvent = eventQueueReader.pop())) break;
298                // if younger event reached, ignore that and all subsequent ones for now
299                if (pEvent->FragmentPos() >= Samples) {
300                    eventQueueReader--;
301                    dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
302                    pEvent->ResetFragmentPos();
303                    break;
304                }
305                // copy event to internal event list
306                if (pGlobalEvents->poolIsEmpty()) {
307                    dmsg(1,("Event pool emtpy!\n"));
308                    break;
309                }
310                *pGlobalEvents->allocAppend() = *pEvent;
311            }
312            eventQueueReader.free(); // free all copied events from input queue
313        }
314    
315      /**      /**
316       *  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
317       *  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
# Line 249  namespace LinuxSampler { namespace gig { Line 319  namespace LinuxSampler { namespace gig {
319       *  converted to the appropriate value range by the audio output class (e.g.       *  converted to the appropriate value range by the audio output class (e.g.
320       *  AlsaIO or JackIO) right after.       *  AlsaIO or JackIO) right after.
321       *       *
      *  @param pEngineChannel - the engine's channel to be rendered  
322       *  @param Samples - number of sample points to be rendered       *  @param Samples - number of sample points to be rendered
323       *  @returns       0 on success       *  @returns       0 on success
324       */       */
325      int Engine::RenderAudio(LinuxSampler::gig::EngineChannel* pEngineChannel, uint Samples) {      int Engine::RenderAudio(uint Samples) {
326          dmsg(5,("RenderAudio(Samples=%d)\n", Samples));          dmsg(5,("RenderAudio(Samples=%d)\n", Samples));
327    
328          // return if no instrument loaded or engine disabled          // return if engine disabled
329          if (EngineDisabled.Pop()) {          if (EngineDisabled.Pop()) {
330              dmsg(5,("gig::Engine: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));              dmsg(5,("gig::Engine: engine disabled (val=%d)\n",EngineDisabled.GetUnsafe()));
331              return 0;              return 0;
332          }          }
         if (!pEngineChannel->pInstrument) {  
             dmsg(5,("gig::Engine: no instrument loaded\n"));  
             return 0;  
         }  
   
333    
334          // update time of start and end of this audio fragment (as events' time stamps relate to this)          // update time of start and end of this audio fragment (as events' time stamps relate to this)
335          pEventGenerator->UpdateFragmentTime(Samples);          pEventGenerator->UpdateFragmentTime(Samples);
336    
337            // get all events from the engine's global input event queue which belong to the current fragment
338            // (these are usually just SysEx messages)
339            ImportEvents(Samples);
340    
341          // empty the event lists for the new fragment          // process engine global events (these are currently only MIDI System Exclusive messages)
         pEvents->clear();  
         pCCEvents->clear();  
         for (uint i = 0; i < Event::destination_count; i++) {  
             pSynthesisEvents[i]->clear();  
         }  
342          {          {
343              RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();              RTList<Event>::Iterator itEvent = pGlobalEvents->first();
344              RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();              RTList<Event>::Iterator end     = pGlobalEvents->end();
345              for(; iuiKey != end; ++iuiKey) {              for (; itEvent != end; ++itEvent) {
346                  pEngineChannel->pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key                  switch (itEvent->Type) {
347                        case Event::type_sysex:
348                            dmsg(5,("Engine: Sysex received\n"));
349                            ProcessSysex(itEvent);
350                            break;
351                    }
352              }              }
353          }          }
354    
355            // We only allow a maximum of MAX_AUDIO_VOICES voices to be stolen
356            // in each audio fragment. All subsequent request for spawning new
357            // voices in the same audio fragment will be ignored.
358            VoiceTheftsLeft = MAX_AUDIO_VOICES;
359    
360          // get all events from the input event queue which belong to the current fragment          // reset internal voice counter (just for statistic of active voices)
361          {          ActiveVoiceCountTemp = 0;
362              RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();  
363              Event* pEvent;  
364              while (true) {          // handle events on all engine channels
365                  // get next event from input event queue          for (int i = 0; i < engineChannels.size(); i++) {
366                  if (!(pEvent = eventQueueReader.pop())) break;              if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
367                  // if younger event reached, ignore that and all subsequent ones for now              ProcessEvents(engineChannels[i], Samples);
                 if (pEvent->FragmentPos() >= Samples) {  
                     eventQueueReader--;  
                     dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));  
                     pEvent->ResetFragmentPos();  
                     break;  
                 }  
                 // copy event to internal event list  
                 if (pEvents->poolIsEmpty()) {  
                     dmsg(1,("Event pool emtpy!\n"));  
                     break;  
                 }  
                 *pEvents->allocAppend() = *pEvent;  
             }  
             eventQueueReader.free(); // free all copied events from input queue  
368          }          }
369    
370            // render all 'normal', active voices 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                RenderActiveVoices(engineChannels[i], Samples);
374            }
375    
376            // now that all ordinary voices on ALL engine channels are rendered, render new stolen voices
377            RenderStolenVoices(Samples);
378    
379            // handle cleanup on all engine channels for the next audio fragment
380            for (int i = 0; i < engineChannels.size(); i++) {
381                if (!engineChannels[i]->pInstrument) continue; // ignore if no instrument loaded
382                PostProcess(engineChannels[i]);
383            }
384    
385    
386            // empty the engine's event list for the next audio fragment
387            ClearEventLists();
388    
389            // reset voice stealing for the next audio fragment
390            pVoiceStealingQueue->clear();
391            itLastStolenVoice  = RTList<Voice>::Iterator();
392            iuiLastStolenKey   = RTList<uint>::Iterator();
393            pLastStolenChannel = NULL;
394    
395            // just some statistics about this engine instance
396            ActiveVoiceCount = ActiveVoiceCountTemp;
397            if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;
398    
399            return 0;
400        }
401    
402        void Engine::ProcessEvents(EngineChannel* pEngineChannel, uint Samples) {
403            // get all events from the engine channels's input event queue which belong to the current fragment
404            // (these are the common events like NoteOn, NoteOff, ControlChange, etc.)
405            pEngineChannel->ImportEvents(Samples);
406    
407          // process events          // process events
408          {          {
409              RTList<Event>::Iterator itEvent = pEvents->first();              RTList<Event>::Iterator itEvent = pEngineChannel->pEvents->first();
410              RTList<Event>::Iterator end     = pEvents->end();              RTList<Event>::Iterator end     = pEngineChannel->pEvents->end();
411              for (; itEvent != end; ++itEvent) {              for (; itEvent != end; ++itEvent) {
412                  switch (itEvent->Type) {                  switch (itEvent->Type) {
413                      case Event::type_note_on:                      case Event::type_note_on:
414                          dmsg(5,("Engine: Note on received\n"));                          dmsg(5,("Engine: Note on received\n"));
415                          ProcessNoteOn(pEngineChannel, itEvent);                          ProcessNoteOn((EngineChannel*)itEvent->pEngineChannel, itEvent);
416                          break;                          break;
417                      case Event::type_note_off:                      case Event::type_note_off:
418                          dmsg(5,("Engine: Note off received\n"));                          dmsg(5,("Engine: Note off received\n"));
419                          ProcessNoteOff(pEngineChannel, itEvent);                          ProcessNoteOff((EngineChannel*)itEvent->pEngineChannel, itEvent);
420                          break;                          break;
421                      case Event::type_control_change:                      case Event::type_control_change:
422                          dmsg(5,("Engine: MIDI CC received\n"));                          dmsg(5,("Engine: MIDI CC received\n"));
423                          ProcessControlChange(pEngineChannel, itEvent);                          ProcessControlChange((EngineChannel*)itEvent->pEngineChannel, itEvent);
424                          break;                          break;
425                      case Event::type_pitchbend:                      case Event::type_pitchbend:
426                          dmsg(5,("Engine: Pitchbend received\n"));                          dmsg(5,("Engine: Pitchbend received\n"));
427                          ProcessPitchbend(pEngineChannel, itEvent);                          ProcessPitchbend((EngineChannel*)itEvent->pEngineChannel, itEvent);
                         break;  
                     case Event::type_sysex:  
                         dmsg(5,("Engine: Sysex received\n"));  
                         ProcessSysex(itEvent);  
428                          break;                          break;
429                  }                  }
430              }              }
431          }          }
432        }
433    
434        void Engine::RenderActiveVoices(EngineChannel* pEngineChannel, uint Samples) {
435          int active_voices = 0;          RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
436            RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();
437          // render audio from all active voices          while (iuiKey != end) { // iterate through all active keys
438          {              midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];
439              RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();              ++iuiKey;
440              RTList<uint>::Iterator end    = pEngineChannel->pActiveKeys->end();  
441              while (iuiKey != end) { // iterate through all active keys              RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
442                  midi_key_info_t* pKey = &pEngineChannel->pMIDIKeyInfo[*iuiKey];              RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
443                  ++iuiKey;              for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
444                    // now render current voice
445                  RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();                  itVoice->Render(Samples);
446                  RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();                  if (itVoice->IsActive()) ActiveVoiceCountTemp++; // still active
447                  for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key                  else { // voice reached end, is now inactive
448                      // now render current voice                      FreeVoice(pEngineChannel, itVoice); // remove voice from the list of active voices
                     itVoice->Render(Samples);  
                     if (itVoice->IsActive()) active_voices++; // still active  
                     else { // voice reached end, is now inactive  
                         FreeVoice(pEngineChannel, itVoice); // remove voice from the list of active voices  
                     }  
449                  }                  }
450              }              }
451          }          }
452        }
453    
454        void Engine::RenderStolenVoices(uint Samples) {
455          // now render all postponed voices from voice stealing          RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();
456          {          RTList<Event>::Iterator end               = pVoiceStealingQueue->end();
457              RTList<Event>::Iterator itVoiceStealEvent = pVoiceStealingQueue->first();          for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {
458              RTList<Event>::Iterator end               = pVoiceStealingQueue->end();              EngineChannel* pEngineChannel = (EngineChannel*) itVoiceStealEvent->pEngineChannel;
459              for (; itVoiceStealEvent != end; ++itVoiceStealEvent) {              Pool<Voice>::Iterator itNewVoice =
460                  Pool<Voice>::Iterator itNewVoice =                  LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false);
461                      LaunchVoice(pEngineChannel, itVoiceStealEvent, itVoiceStealEvent->Param.Note.Layer, itVoiceStealEvent->Param.Note.ReleaseTrigger, false);              if (itNewVoice) {
462                  if (itNewVoice) {                  itNewVoice->Render(Samples);
463                      for (; itNewVoice; itNewVoice = itNewVoice->itChildVoice) {                  if (itNewVoice->IsActive()) ActiveVoiceCountTemp++; // still active
464                          itNewVoice->Render(Samples);                  else { // voice reached end, is now inactive
465                          if (itNewVoice->IsActive()) active_voices++; // still active                      FreeVoice(pEngineChannel, itNewVoice); // remove voice from the list of active voices
                         else { // voice reached end, is now inactive  
                             FreeVoice(pEngineChannel, itNewVoice); // remove voice from the list of active voices  
                         }  
                     }  
466                  }                  }
                 else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));  
467              }              }
468                else dmsg(1,("gig::Engine: ERROR, voice stealing didn't work out!\n"));
469          }          }
470          // reset voice stealing for the new fragment      }
         pVoiceStealingQueue->clear();  
         itLastStolenVoice = RTList<Voice>::Iterator();  
         iuiLastStolenKey  = RTList<uint>::Iterator();  
   
471    
472        void Engine::PostProcess(EngineChannel* pEngineChannel) {
473          // free all keys which have no active voices left          // free all keys which have no active voices left
474          {          {
475              RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();              RTList<uint>::Iterator iuiKey = pEngineChannel->pActiveKeys->first();
# Line 413  namespace LinuxSampler { namespace gig { Line 492  namespace LinuxSampler { namespace gig {
492              }              }
493          }          }
494    
495            // empty the engine channel's own event lists
496          // write that to the disk thread class so that it can print it          pEngineChannel->ClearEventLists();
497          // on the console for debugging purposes      }
         ActiveVoiceCount = active_voices;  
         if (ActiveVoiceCount > ActiveVoiceCountMax) ActiveVoiceCountMax = ActiveVoiceCount;  
   
   
         return 0;  
     }      
498    
499      /**      /**
500       *  Will be called by the MIDI input device whenever a MIDI system       *  Will be called by the MIDI input device whenever a MIDI system
# Line 434  namespace LinuxSampler { namespace gig { Line 507  namespace LinuxSampler { namespace gig {
507          Event event             = pEventGenerator->CreateEvent();          Event event             = pEventGenerator->CreateEvent();
508          event.Type              = Event::type_sysex;          event.Type              = Event::type_sysex;
509          event.Param.Sysex.Size  = Size;          event.Param.Sysex.Size  = Size;
510            event.pEngineChannel    = NULL; // as Engine global event
511          if (pEventQueue->write_space() > 0) {          if (pEventQueue->write_space() > 0) {
512              if (pSysexBuffer->write_space() >= Size) {              if (pSysexBuffer->write_space() >= Size) {
513                  // copy sysex data to input buffer                  // copy sysex data to input buffer
# Line 461  namespace LinuxSampler { namespace gig { Line 535  namespace LinuxSampler { namespace gig {
535       *  @param itNoteOnEvent - key, velocity and time stamp of the event       *  @param itNoteOnEvent - key, velocity and time stamp of the event
536       */       */
537      void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {      void Engine::ProcessNoteOn(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
538            
539          const int key = itNoteOnEvent->Param.Note.Key;          const int key = itNoteOnEvent->Param.Note.Key;
540    
541          // Change key dimension value if key is in keyswitching area          // Change key dimension value if key is in keyswitching area
# Line 489  namespace LinuxSampler { namespace gig { Line 563  namespace LinuxSampler { namespace gig {
563          // move note on event to the key's own event list          // move note on event to the key's own event list
564          RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);          RTList<Event>::Iterator itNoteOnEventOnKeyList = itNoteOnEvent.moveToEndOf(pKey->pEvents);
565    
566          // allocate and trigger a new voice for the key          // allocate and trigger new voice(s) for the key
567          LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, 0, false, true);          {
568                // first, get total amount of required voices (dependant on amount of layers)
569                ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOnEventOnKeyList->Param.Note.Key);
570                if (pRegion) {
571                    int voicesRequired = pRegion->Layers;
572                    // now launch the required amount of voices
573                    for (int i = 0; i < voicesRequired; i++)
574                        LaunchVoice(pEngineChannel, itNoteOnEventOnKeyList, i, false, true);
575                }
576            }
577    
578            pKey->RoundRobinIndex++;
579      }      }
580    
581      /**      /**
# Line 517  namespace LinuxSampler { namespace gig { Line 602  namespace LinuxSampler { namespace gig {
602    
603          // spawn release triggered voice(s) if needed          // spawn release triggered voice(s) if needed
604          if (pKey->ReleaseTrigger) {          if (pKey->ReleaseTrigger) {
605              LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, 0, true, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples              // first, get total amount of required voices (dependant on amount of layers)
606                ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOffEventOnKeyList->Param.Note.Key);
607                if (pRegion) {
608                    int voicesRequired = pRegion->Layers;
609                    // now launch the required amount of voices
610                    for (int i = 0; i < voicesRequired; i++)
611                        LaunchVoice(pEngineChannel, itNoteOffEventOnKeyList, i, true, false); //FIXME: for the moment we don't perform voice stealing for release triggered samples
612                }
613              pKey->ReleaseTrigger = false;              pKey->ReleaseTrigger = false;
614          }          }
615      }      }
# Line 531  namespace LinuxSampler { namespace gig { Line 623  namespace LinuxSampler { namespace gig {
623       */       */
624      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {      void Engine::ProcessPitchbend(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {
625          pEngineChannel->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value          pEngineChannel->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value
626          itPitchbendEvent.moveToEndOf(pSynthesisEvents[Event::destination_vco]);          itPitchbendEvent.moveToEndOf(pEngineChannel->pSynthesisEvents[Event::destination_vco]);
627      }      }
628    
629      /**      /**
# Line 590  namespace LinuxSampler { namespace gig { Line 682  namespace LinuxSampler { namespace gig {
682              }              }
683          }          }
684          else if (VoiceStealing) {          else if (VoiceStealing) {
685              // first, get total amount of required voices (dependant on amount of layers)  
686              ::gig::Region* pRegion = pEngineChannel->pInstrument->GetRegion(itNoteOnEvent->Param.Note.Key);              // try to steal one voice
687              if (!pRegion) return Pool<Voice>::Iterator(); // nothing defined for this MIDI key, so no voice needed              StealVoice(pEngineChannel, itNoteOnEvent);
             int voicesRequired = pRegion->Layers;  
   
             // now steal the (remaining) amount of voices  
             for (int i = iLayer; i < voicesRequired; i++)  
                 StealVoice(pEngineChannel, itNoteOnEvent);  
688    
689              // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died              // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died
690              RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();              RTList<Event>::Iterator itStealEvent = pVoiceStealingQueue->allocAppend();
# Line 622  namespace LinuxSampler { namespace gig { Line 709  namespace LinuxSampler { namespace gig {
709       *  @param itNoteOnEvent - key, velocity and time stamp of the event       *  @param itNoteOnEvent - key, velocity and time stamp of the event
710       */       */
711      void Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {      void Engine::StealVoice(EngineChannel* pEngineChannel, Pool<Event>::Iterator& itNoteOnEvent) {
712            if (!VoiceTheftsLeft) {
713                dmsg(1,("Max. voice thefts per audio fragment reached (you may raise MAX_AUDIO_VOICES).\n"));
714                return;
715            }
716          if (!pEventPool->poolIsEmpty()) {          if (!pEventPool->poolIsEmpty()) {
717    
718              RTList<uint>::Iterator  iuiOldestKey;              RTList<Voice>::Iterator itSelectedVoice;
             RTList<Voice>::Iterator itOldestVoice;  
719    
720              // Select one voice for voice stealing              // Select one voice for voice stealing
721              switch (VOICE_STEAL_ALGORITHM) {              switch (VOICE_STEAL_ALGORITHM) {
# Line 634  namespace LinuxSampler { namespace gig { Line 724  namespace LinuxSampler { namespace gig {
724                  // voice should be spawned, if there is no voice on that                  // voice should be spawned, if there is no voice on that
725                  // key, or no voice left to kill there, then procceed with                  // key, or no voice left to kill there, then procceed with
726                  // 'oldestkey' algorithm                  // 'oldestkey' algorithm
727                  case voice_steal_algo_keymask: {                  case voice_steal_algo_oldestvoiceonkey: {
728                      midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];                  #if 0 // FIXME: broken
729                      if (itLastStolenVoice) {                      midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[itNoteOnEvent->Param.Note.Key];
730                          itOldestVoice = itLastStolenVoice;                      if (this->itLastStolenVoice) {
731                          ++itOldestVoice;                          itSelectedVoice = this->itLastStolenVoice;
732                            ++itSelectedVoice;
733                      }                      }
734                      else { // no voice stolen in this audio fragment cycle yet                      else { // no voice stolen in this audio fragment cycle yet
735                          itOldestVoice = pOldestKey->pActiveVoices->first();                          itSelectedVoice = pSelectedKey->pActiveVoices->first();
736                      }                      }
737                      if (itOldestVoice) {                      if (itSelectedVoice) {
738                          iuiOldestKey = pOldestKey->itSelf;                          iuiSelectedKey = pSelectedKey->itSelf;
739                          break; // selection succeeded                          break; // selection succeeded
740                      }                      }
741                    #endif
742                  } // no break - intentional !                  } // no break - intentional !
743    
744                  // try to pick the oldest voice on the oldest active key                  // try to pick the oldest voice on the oldest active key
745                  // (caution: must stay after 'keymask' algorithm !)                  // (caution: must stay after 'oldestvoiceonkey' algorithm !)
746                  case voice_steal_algo_oldestkey: {                  case voice_steal_algo_oldestkey: {
747                      if (itLastStolenVoice) {                      if (this->itLastStolenVoice) {
748                          midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[*iuiLastStolenKey];                          itSelectedVoice = this->itLastStolenVoice;
749                          itOldestVoice = itLastStolenVoice;                          ++itSelectedVoice;
750                          ++itOldestVoice;                          if (itSelectedVoice) break; // selection succeeded
751                          if (!itOldestVoice) {                          RTList<uint>::Iterator iuiSelectedKey = this->iuiLastStolenKey;
752                              iuiOldestKey = iuiLastStolenKey;                          ++iuiSelectedKey;
753                              ++iuiOldestKey;                          if (iuiSelectedKey) {
754                              if (iuiOldestKey) {                              this->iuiLastStolenKey = iuiSelectedKey;
755                                  midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[*iuiOldestKey];                              midi_key_info_t* pSelectedKey = &pEngineChannel->pMIDIKeyInfo[*iuiSelectedKey];
756                                  itOldestVoice = pOldestKey->pActiveVoices->first();                              itSelectedVoice = pSelectedKey->pActiveVoices->first();
757                              }                              break; // selection succeeded
                             else {  
                                 dmsg(1,("gig::Engine: Warning, too less voices, even for voice stealing! - Better recompile with higher MAX_AUDIO_VOICES.\n"));  
                                 return;  
                             }  
758                          }                          }
                         else iuiOldestKey = iuiLastStolenKey;  
                     }  
                     else { // no voice stolen in this audio fragment cycle yet  
                         iuiOldestKey = pEngineChannel->pActiveKeys->first();  
                         midi_key_info_t* pOldestKey = &pEngineChannel->pMIDIKeyInfo[*iuiOldestKey];  
                         itOldestVoice = pOldestKey->pActiveVoices->first();  
759                      }                      }
760                      break;                      break;
761                  }                  }
# Line 686  namespace LinuxSampler { namespace gig { Line 768  namespace LinuxSampler { namespace gig {
768                  }                  }
769              }              }
770    
771                // steal oldest voice on the oldest key from this or any other engine channel
772                if (!itSelectedVoice) {
773                    EngineChannel* pSelectedChannel = (pLastStolenChannel) ? pLastStolenChannel : pEngineChannel;
774                    int iChannelIndex = pSelectedChannel->iEngineIndexSelf;
775                    while (true) {
776                        RTList<uint>::Iterator iuiSelectedKey = pSelectedChannel->pActiveKeys->first();
777                        if (iuiSelectedKey) {
778                            midi_key_info_t* pSelectedKey = &pSelectedChannel->pMIDIKeyInfo[*iuiSelectedKey];
779                            itSelectedVoice    = pSelectedKey->pActiveVoices->first();
780                            iuiLastStolenKey   = iuiSelectedKey;
781                            pLastStolenChannel = pSelectedChannel;
782                            break; // selection succeeded
783                        }
784                        iChannelIndex    = (iChannelIndex + 1) % engineChannels.size();
785                        pSelectedChannel =  engineChannels[iChannelIndex];
786                    }
787                }
788    
789              //FIXME: can be removed, just a sanity check for debugging              //FIXME: can be removed, just a sanity check for debugging
790              if (!itOldestVoice->IsActive()) dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));              if (!itSelectedVoice->IsActive()) dmsg(1,("gig::Engine: ERROR, tried to steal a voice which was not active !!!\n"));
791    
792              // now kill the selected voice              // now kill the selected voice
793              itOldestVoice->Kill(itNoteOnEvent);              itSelectedVoice->Kill(itNoteOnEvent);
794              // remember which voice on which key we stole, so we can simply proceed for the next voice stealing  
795              this->itLastStolenVoice = itOldestVoice;              // remember which voice we stole, so we can simply proceed for the next voice stealing
796              this->iuiLastStolenKey = iuiOldestKey;              itLastStolenVoice = itSelectedVoice;
797    
798                --VoiceTheftsLeft;
799          }          }
800          else dmsg(1,("Event pool emtpy!\n"));          else dmsg(1,("Event pool emtpy!\n"));
801      }      }
# Line 755  namespace LinuxSampler { namespace gig { Line 857  namespace LinuxSampler { namespace gig {
857          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", itControlChangeEvent->Param.CC.Controller, itControlChangeEvent->Param.CC.Value));          dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", itControlChangeEvent->Param.CC.Controller, itControlChangeEvent->Param.CC.Value));
858    
859          switch (itControlChangeEvent->Param.CC.Controller) {          switch (itControlChangeEvent->Param.CC.Controller) {
860              case 64: {              case 7: { // volume
861                    //TODO: not sample accurate yet
862                    pEngineChannel->GlobalVolume = (float) itControlChangeEvent->Param.CC.Value / 127.0f;
863                    break;
864                }
865                case 10: { // panpot
866                    //TODO: not sample accurate yet
867                    const int pan = (int) itControlChangeEvent->Param.CC.Value - 64;
868                    pEngineChannel->GlobalPanLeft  = 1.0f - float(RTMath::Max(pan, 0)) /  63.0f;
869                    pEngineChannel->GlobalPanRight = 1.0f - float(RTMath::Min(pan, 0)) / -64.0f;
870                    break;
871                }
872                case 64: { // sustain
873                  if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {                  if (itControlChangeEvent->Param.CC.Value >= 64 && !pEngineChannel->SustainPedal) {
874                      dmsg(4,("PEDAL DOWN\n"));                      dmsg(4,("PEDAL DOWN\n"));
875                      pEngineChannel->SustainPedal = true;                      pEngineChannel->SustainPedal = true;
# Line 802  namespace LinuxSampler { namespace gig { Line 916  namespace LinuxSampler { namespace gig {
916          pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;          pEngineChannel->ControllerTable[itControlChangeEvent->Param.CC.Controller] = itControlChangeEvent->Param.CC.Value;
917    
918          // 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
919          itControlChangeEvent.moveToEndOf(pCCEvents);          itControlChangeEvent.moveToEndOf(pEngineChannel->pCCEvents);
920      }      }
921    
922      /**      /**
# Line 901  namespace LinuxSampler { namespace gig { Line 1015  namespace LinuxSampler { namespace gig {
1015             m[i+2] = val;             m[i+2] = val;
1016             m[i+3] = val;             m[i+3] = val;
1017          }          }
1018      }          }
1019    
1020      uint Engine::VoiceCount() {      uint Engine::VoiceCount() {
1021          return ActiveVoiceCount;          return ActiveVoiceCount;
# Line 940  namespace LinuxSampler { namespace gig { Line 1054  namespace LinuxSampler { namespace gig {
1054      }      }
1055    
1056      String Engine::Version() {      String Engine::Version() {
1057          String s = "$Revision: 1.26 $";          String s = "$Revision: 1.32 $";
1058          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
1059      }      }
1060    

Legend:
Removed from v.411  
changed lines
  Added in v.466

  ViewVC Help
Powered by ViewVC