/[svn]/linuxsampler/trunk/src/engines/gig/EngineChannel.cpp
ViewVC logotype

Diff of /linuxsampler/trunk/src/engines/gig/EngineChannel.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 554 by schoenebeck, Thu May 19 19:25:14 2005 UTC revision 1826 by iliev, Sat Jan 24 14:32:35 2009 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                              *   *   Copyright (C) 2005 - 2008 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 23 
23    
24  #include "EngineChannel.h"  #include "EngineChannel.h"
25    
26    #include "../../common/global_private.h"
27    #include "../../Sampler.h"
28    
29  namespace LinuxSampler { namespace gig {  namespace LinuxSampler { namespace gig {
30    
31      EngineChannel::EngineChannel() {      EngineChannel::EngineChannel() :
32            InstrumentChangeCommandReader(InstrumentChangeCommand),
33            virtualMidiDevicesReader_AudioThread(virtualMidiDevices),
34            virtualMidiDevicesReader_MidiThread(virtualMidiDevices)
35        {
36          pMIDIKeyInfo = new midi_key_info_t[128];          pMIDIKeyInfo = new midi_key_info_t[128];
37          pEngine      = NULL;          pEngine      = NULL;
38          pInstrument  = NULL;          pInstrument  = NULL;
39          pEvents      = NULL; // we allocate when we retrieve the right Engine object          pEvents      = NULL; // we allocate when we retrieve the right Engine object
40          pCCEvents    = NULL; // we allocate when we retrieve the right Engine object          pEventQueue  = new RingBuffer<Event,false>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);
         pEventQueue  = new RingBuffer<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);  
41          pActiveKeys  = new Pool<uint>(128);          pActiveKeys  = new Pool<uint>(128);
42          for (uint i = 0; i < 128; i++) {          for (uint i = 0; i < 128; i++) {
43              pMIDIKeyInfo[i].pActiveVoices  = NULL; // we allocate when we retrieve the right Engine object              pMIDIKeyInfo[i].pActiveVoices  = NULL; // we allocate when we retrieve the right Engine object
# Line 42  namespace LinuxSampler { namespace gig { Line 48  namespace LinuxSampler { namespace gig {
48              pMIDIKeyInfo[i].VoiceTheftsQueued = 0;              pMIDIKeyInfo[i].VoiceTheftsQueued = 0;
49              pMIDIKeyInfo[i].RoundRobinIndex = 0;              pMIDIKeyInfo[i].RoundRobinIndex = 0;
50          }          }
         for (uint i = 0; i < Event::destination_count; i++) {  
             pSynthesisEvents[i] = NULL; // we allocate when we retrieve the right Engine object  
         }  
51          InstrumentIdx  = -1;          InstrumentIdx  = -1;
52          InstrumentStat = -1;          InstrumentStat = -1;
53            pChannelLeft  = NULL;
54            pChannelRight = NULL;
55          AudioDeviceChannelLeft  = -1;          AudioDeviceChannelLeft  = -1;
56          AudioDeviceChannelRight = -1;          AudioDeviceChannelRight = -1;
57            pMidiInputPort = NULL;
58            midiChannel = midi_chan_all;
59            ResetControllers();
60            SoloMode       = false;
61            PortamentoMode = false;
62            PortamentoTime = CONFIG_PORTAMENTO_TIME_DEFAULT;
63      }      }
64    
65      EngineChannel::~EngineChannel() {      EngineChannel::~EngineChannel() {
66          DisconnectAudioOutputDevice();          DisconnectAudioOutputDevice();
67          if (pInstrument) Engine::instruments.HandBack(pInstrument, this);  
68            // In case the channel was removed before the instrument was
69            // fully loaded, try to give back instrument again (see bug #113)
70            instrument_change_command_t& cmd = ChangeInstrument(NULL);
71            if (cmd.pInstrument) {
72                    Engine::instruments.HandBack(cmd.pInstrument, this);
73            }
74            ///////
75    
76          if (pEventQueue) delete pEventQueue;          if (pEventQueue) delete pEventQueue;
77          if (pActiveKeys) delete pActiveKeys;          if (pActiveKeys) delete pActiveKeys;
78          if (pMIDIKeyInfo) delete[] pMIDIKeyInfo;          if (pMIDIKeyInfo) delete[] pMIDIKeyInfo;
79            RemoveAllFxSends();
80        }
81    
82        /**
83         * Implementation of virtual method from abstract EngineChannel interface.
84         * This method will periodically be polled (e.g. by the LSCP server) to
85         * check if some engine channel parameter has changed since the last
86         * StatusChanged() call.
87         *
88         * This method can also be used to mark the engine channel as changed
89         * from outside, e.g. by a MIDI input device. The optional argument
90         * \a nNewStatus can be used for this.
91         *
92         * TODO: This "poll method" is just a lazy solution and might be
93         *       replaced in future.
94         * @param bNewStatus - (optional, default: false) sets the new status flag
95         * @returns true if engine channel status has changed since last
96         *          StatusChanged() call
97         */
98        bool EngineChannel::StatusChanged(bool bNewStatus) {
99            bool b = bStatusChanged;
100            bStatusChanged = bNewStatus;
101            return b;
102        }
103    
104        void EngineChannel::Reset() {
105            if (pEngine) pEngine->DisableAndLock();
106            ResetInternal();
107            ResetControllers();
108            if (pEngine) {
109                pEngine->Enable();
110                pEngine->Reset();
111            }
112      }      }
113    
114      /**      /**
115       * This method is not thread safe!       * This method is not thread safe!
116       */       */
117      void EngineChannel::ResetInternal() {      void EngineChannel::ResetInternal() {
         Pitch               = 0;  
         SustainPedal        = false;  
         GlobalVolume        = 1.0;  
         GlobalPanLeft       = 1.0f;  
         GlobalPanRight      = 1.0f;  
118          CurrentKeyDimension = 0;          CurrentKeyDimension = 0;
119    
         ResetControllers();  
   
120          // reset key info          // reset key info
121          for (uint i = 0; i < 128; i++) {          for (uint i = 0; i < 128; i++) {
122              if (pMIDIKeyInfo[i].pActiveVoices)              if (pMIDIKeyInfo[i].pActiveVoices)
# Line 84  namespace LinuxSampler { namespace gig { Line 129  namespace LinuxSampler { namespace gig {
129              pMIDIKeyInfo[i].itSelf         = Pool<uint>::Iterator();              pMIDIKeyInfo[i].itSelf         = Pool<uint>::Iterator();
130              pMIDIKeyInfo[i].VoiceTheftsQueued = 0;              pMIDIKeyInfo[i].VoiceTheftsQueued = 0;
131          }          }
132            SoloKey       = -1;    // no solo key active yet
133            PortamentoPos = -1.0f; // no portamento active yet
134    
135          // reset all key groups          // reset all key groups
136          std::map<uint,uint*>::iterator iter = ActiveKeyGroups.begin();          std::map<uint,uint*>::iterator iter = ActiveKeyGroups.begin();
# Line 96  namespace LinuxSampler { namespace gig { Line 143  namespace LinuxSampler { namespace gig {
143          pEventQueue->init();          pEventQueue->init();
144    
145          if (pEngine) pEngine->ResetInternal();          if (pEngine) pEngine->ResetInternal();
146    
147            // status of engine channel has changed, so set notify flag
148            bStatusChanged = true;
149      }      }
150    
151      LinuxSampler::Engine* EngineChannel::GetEngine() {      LinuxSampler::Engine* EngineChannel::GetEngine() {
# Line 124  namespace LinuxSampler { namespace gig { Line 174  namespace LinuxSampler { namespace gig {
174       * This method will then actually start to load the instrument and block       * This method will then actually start to load the instrument and block
175       * the calling thread until loading was completed.       * the calling thread until loading was completed.
176       *       *
      * @returns detailed description of the method call result  
177       * @see PrepareLoadInstrument()       * @see PrepareLoadInstrument()
178       */       */
179      void EngineChannel::LoadInstrument() {      void EngineChannel::LoadInstrument() {
180            // make sure we don't trigger any new notes with an old
181          if (pEngine) pEngine->DisableAndLock();          // instrument
182            instrument_change_command_t& cmd = ChangeInstrument(0);
183          ResetInternal();          if (cmd.pInstrument) {
184                // give old instrument back to instrument manager, but
185          // free old instrument              // keep the dimension regions and samples that are in use
186          if (pInstrument) {              Engine::instruments.HandBackInstrument(cmd.pInstrument, this, cmd.pDimRegionsInUse);
             // give old instrument back to instrument manager  
             Engine::instruments.HandBack(pInstrument, this);  
187          }          }
188            cmd.pDimRegionsInUse->clear();
189    
190          // delete all key groups          // delete all key groups
191          ActiveKeyGroups.clear();          ActiveKeyGroups.clear();
192    
193          // request gig instrument from instrument manager          // request gig instrument from instrument manager
194            ::gig::Instrument* newInstrument;
195          try {          try {
196              instrument_id_t instrid;              InstrumentManager::instrument_id_t instrid;
197              instrid.FileName    = InstrumentFile;              instrid.FileName  = InstrumentFile;
198              instrid.iInstrument = InstrumentIdx;              instrid.Index     = InstrumentIdx;
199              pInstrument = Engine::instruments.Borrow(instrid, this);              newInstrument = Engine::instruments.Borrow(instrid, this);
200              if (!pInstrument) {              if (!newInstrument) {
201                  InstrumentStat = -1;                  throw InstrumentManagerException("resource was not created");
                 dmsg(1,("no instrument loaded!!!\n"));  
                 exit(EXIT_FAILURE);  
202              }              }
203          }          }
204          catch (RIFF::Exception e) {          catch (RIFF::Exception e) {
205              InstrumentStat = -2;              InstrumentStat = -2;
206                StatusChanged(true);
207              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;
208              throw LinuxSamplerException(msg);              throw Exception(msg);
209          }          }
210          catch (InstrumentResourceManagerException e) {          catch (InstrumentManagerException e) {
211              InstrumentStat = -3;              InstrumentStat = -3;
212                StatusChanged(true);
213              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();              String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();
214              throw LinuxSamplerException(msg);              throw Exception(msg);
215          }          }
216          catch (...) {          catch (...) {
217              InstrumentStat = -4;              InstrumentStat = -4;
218              throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");              StatusChanged(true);
219                throw Exception("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");
220          }          }
221    
222          // rebuild ActiveKeyGroups map with key groups of current instrument          // rebuild ActiveKeyGroups map with key groups of current instrument
223          for (::gig::Region* pRegion = pInstrument->GetFirstRegion(); pRegion; pRegion = pInstrument->GetNextRegion())          for (::gig::Region* pRegion = newInstrument->GetFirstRegion(); pRegion; pRegion = newInstrument->GetNextRegion())
224              if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL;              if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL;
225    
226          InstrumentIdxName = pInstrument->pInfo->Name;          InstrumentIdxName = newInstrument->pInfo->Name;
227          InstrumentStat = 100;          InstrumentStat = 100;
228    
229          // inform audio driver for the need of two channels          ChangeInstrument(newInstrument);
         try {  
             if (pEngine && pEngine->pAudioOutputDevice)  
                 pEngine->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);  
         }  
230    
231          if (pEngine) pEngine->Enable();          StatusChanged(true);
232        }
233    
234    
235        /**
236         * Changes the instrument for an engine channel.
237         *
238         * @param pInstrument - new instrument
239         * @returns the resulting instrument change command after the
240         *          command switch, containing the old instrument and
241         *          the dimregions it is using
242         */
243        EngineChannel::instrument_change_command_t& EngineChannel::ChangeInstrument(::gig::Instrument* pInstrument) {
244            instrument_change_command_t& cmd = InstrumentChangeCommand.GetConfigForUpdate();
245            cmd.pInstrument = pInstrument;
246            cmd.bChangeInstrument = true;
247    
248            return InstrumentChangeCommand.SwitchConfig();
249      }      }
250    
251      /**      /**
# Line 208  namespace LinuxSampler { namespace gig { Line 267  namespace LinuxSampler { namespace gig {
267      void EngineChannel::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {      void EngineChannel::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {
268          this->pInstrument = pNewResource; //TODO: there are couple of engine parameters we should update here as well if the instrument was updated (see LoadInstrument())          this->pInstrument = pNewResource; //TODO: there are couple of engine parameters we should update here as well if the instrument was updated (see LoadInstrument())
269          if (pEngine) pEngine->Enable();          if (pEngine) pEngine->Enable();
270            bStatusChanged = true; // status of engine has changed, so set notify flag
271      }      }
272    
273      /**      /**
# Line 219  namespace LinuxSampler { namespace gig { Line 279  namespace LinuxSampler { namespace gig {
279      void EngineChannel::OnResourceProgress(float fProgress) {      void EngineChannel::OnResourceProgress(float fProgress) {
280          this->InstrumentStat = int(fProgress * 100.0f);          this->InstrumentStat = int(fProgress * 100.0f);
281          dmsg(7,("gig::EngineChannel: progress %d%", InstrumentStat));          dmsg(7,("gig::EngineChannel: progress %d%", InstrumentStat));
282            bStatusChanged = true; // status of engine has changed, so set notify flag
283      }      }
284    
285      void EngineChannel::Connect(AudioOutputDevice* pAudioOut) {      void EngineChannel::Connect(AudioOutputDevice* pAudioOut) {
# Line 228  namespace LinuxSampler { namespace gig { Line 289  namespace LinuxSampler { namespace gig {
289          }          }
290          pEngine = Engine::AcquireEngine(this, pAudioOut);          pEngine = Engine::AcquireEngine(this, pAudioOut);
291          ResetInternal();          ResetInternal();
292          pEvents   = new RTList<Event>(pEngine->pEventPool);          pEvents = new RTList<Event>(pEngine->pEventPool);
293          pCCEvents = new RTList<Event>(pEngine->pEventPool);  
294          for (uint i = 0; i < Event::destination_count; i++) {          // reset the instrument change command struct (need to be done
295              pSynthesisEvents[i] = new RTList<Event>(pEngine->pEventPool);          // twice, as it is double buffered)
296            {
297                instrument_change_command_t& cmd = InstrumentChangeCommand.GetConfigForUpdate();
298                cmd.pDimRegionsInUse = new RTList< ::gig::DimensionRegion*>(pEngine->pDimRegionPool[0]);
299                cmd.pInstrument = 0;
300                cmd.bChangeInstrument = false;
301          }          }
302            {
303                instrument_change_command_t& cmd = InstrumentChangeCommand.SwitchConfig();
304                cmd.pDimRegionsInUse = new RTList< ::gig::DimensionRegion*>(pEngine->pDimRegionPool[1]);
305                cmd.pInstrument = 0;
306                cmd.bChangeInstrument = false;
307            }
308    
309          for (uint i = 0; i < 128; i++) {          for (uint i = 0; i < 128; i++) {
310              pMIDIKeyInfo[i].pActiveVoices = new RTList<Voice>(pEngine->pVoicePool);              pMIDIKeyInfo[i].pActiveVoices = new RTList<Voice>(pEngine->pVoicePool);
311              pMIDIKeyInfo[i].pEvents       = new RTList<Event>(pEngine->pEventPool);              pMIDIKeyInfo[i].pEvents       = new RTList<Event>(pEngine->pEventPool);
312          }          }
313          AudioDeviceChannelLeft  = 0;          AudioDeviceChannelLeft  = 0;
314          AudioDeviceChannelRight = 1;          AudioDeviceChannelRight = 1;
315          pOutputLeft             = pAudioOut->Channel(0)->Buffer();          if (fxSends.empty()) { // render directly into the AudioDevice's output buffers
316          pOutputRight            = pAudioOut->Channel(1)->Buffer();              pChannelLeft  = pAudioOut->Channel(AudioDeviceChannelLeft);
317                pChannelRight = pAudioOut->Channel(AudioDeviceChannelRight);
318            } else { // use local buffers for rendering and copy later
319                // ensure the local buffers have the correct size
320                if (pChannelLeft)  delete pChannelLeft;
321                if (pChannelRight) delete pChannelRight;
322                pChannelLeft  = new AudioChannel(0, pAudioOut->MaxSamplesPerCycle());
323                pChannelRight = new AudioChannel(1, pAudioOut->MaxSamplesPerCycle());
324            }
325            if (pEngine->EngineDisabled.GetUnsafe()) pEngine->Enable();
326            MidiInputPort::AddSysexListener(pEngine);
327      }      }
328    
329      void EngineChannel::DisconnectAudioOutputDevice() {      void EngineChannel::DisconnectAudioOutputDevice() {
330          if (pEngine) { // if clause to prevent disconnect loops          if (pEngine) { // if clause to prevent disconnect loops
331    
332                // delete the structures used for instrument change
333                RTList< ::gig::DimensionRegion*>* d = InstrumentChangeCommand.GetConfigForUpdate().pDimRegionsInUse;
334                if (d) delete d;
335                EngineChannel::instrument_change_command_t& cmd = InstrumentChangeCommand.SwitchConfig();
336                d = cmd.pDimRegionsInUse;
337    
338                if (cmd.pInstrument) {
339                    // release the currently loaded instrument
340                    Engine::instruments.HandBackInstrument(cmd.pInstrument, this, d);
341                }
342    
343                if (d) delete d;
344    
345                // release all active dimension regions to resource
346                // manager
347                RTList<uint>::Iterator iuiKey = pActiveKeys->first();
348                RTList<uint>::Iterator end    = pActiveKeys->end();
349                while (iuiKey != end) { // iterate through all active keys
350                    midi_key_info_t* pKey = &pMIDIKeyInfo[*iuiKey];
351                    ++iuiKey;
352    
353                    RTList<Voice>::Iterator itVoice     = pKey->pActiveVoices->first();
354                    RTList<Voice>::Iterator itVoicesEnd = pKey->pActiveVoices->end();
355                    for (; itVoice != itVoicesEnd; ++itVoice) { // iterate through all voices on this key
356                        Engine::instruments.HandBackDimReg(itVoice->pDimRgn);
357                    }
358                }
359    
360              ResetInternal();              ResetInternal();
361              if (pEvents) {              if (pEvents) {
362                  delete pEvents;                  delete pEvents;
363                  pEvents = NULL;                  pEvents = NULL;
364              }              }
             if (pCCEvents) {  
                 delete pCCEvents;  
                 pCCEvents = NULL;  
             }  
365              for (uint i = 0; i < 128; i++) {              for (uint i = 0; i < 128; i++) {
366                  if (pMIDIKeyInfo[i].pActiveVoices) {                  if (pMIDIKeyInfo[i].pActiveVoices) {
367                      delete pMIDIKeyInfo[i].pActiveVoices;                      delete pMIDIKeyInfo[i].pActiveVoices;
# Line 264  namespace LinuxSampler { namespace gig { Line 372  namespace LinuxSampler { namespace gig {
372                      pMIDIKeyInfo[i].pEvents = NULL;                      pMIDIKeyInfo[i].pEvents = NULL;
373                  }                  }
374              }              }
             for (uint i = 0; i < Event::destination_count; i++) {  
                 if (pSynthesisEvents[i]) {  
                     delete pSynthesisEvents[i];  
                     pSynthesisEvents[i] = NULL;  
                 }  
             }  
375              Engine* oldEngine = pEngine;              Engine* oldEngine = pEngine;
376              AudioOutputDevice* oldAudioDevice = pEngine->pAudioOutputDevice;              AudioOutputDevice* oldAudioDevice = pEngine->pAudioOutputDevice;
377              pEngine = NULL;              pEngine = NULL;
378              Engine::FreeEngine(this, oldAudioDevice);              Engine::FreeEngine(this, oldAudioDevice);
379              AudioDeviceChannelLeft  = -1;              AudioDeviceChannelLeft  = -1;
380              AudioDeviceChannelRight = -1;              AudioDeviceChannelRight = -1;
381                if (!fxSends.empty()) { // free the local rendering buffers
382                    if (pChannelLeft)  delete pChannelLeft;
383                    if (pChannelRight) delete pChannelRight;
384                }
385                pChannelLeft  = NULL;
386                pChannelRight = NULL;
387          }          }
388      }      }
389    
390        AudioOutputDevice* EngineChannel::GetAudioOutputDevice() {
391            return (pEngine) ? pEngine->pAudioOutputDevice : NULL;
392        }
393    
394      void EngineChannel::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) {      void EngineChannel::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) {
395          if (!pEngine || !pEngine->pAudioOutputDevice) throw AudioOutputException("No audio output device connected yet.");          if (!pEngine || !pEngine->pAudioOutputDevice) throw AudioOutputException("No audio output device connected yet.");
396    
# Line 286  namespace LinuxSampler { namespace gig { Line 398  namespace LinuxSampler { namespace gig {
398          if (!pChannel) throw AudioOutputException("Invalid audio output device channel " + ToString(AudioDeviceChannel));          if (!pChannel) throw AudioOutputException("Invalid audio output device channel " + ToString(AudioDeviceChannel));
399          switch (EngineAudioChannel) {          switch (EngineAudioChannel) {
400              case 0: // left output channel              case 0: // left output channel
401                  pOutputLeft = pChannel->Buffer();                  if (fxSends.empty()) pChannelLeft = pChannel;
402                  AudioDeviceChannelLeft = AudioDeviceChannel;                  AudioDeviceChannelLeft = AudioDeviceChannel;
403                  break;                  break;
404              case 1: // right output channel              case 1: // right output channel
405                  pOutputRight = pChannel->Buffer();                  if (fxSends.empty()) pChannelRight = pChannel;
406                  AudioDeviceChannelRight = AudioDeviceChannel;                  AudioDeviceChannelRight = AudioDeviceChannel;
407                  break;                  break;
408              default:              default:
409                  throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));                  throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));
410          }          }
411    
412            bStatusChanged = true;
413      }      }
414    
415      int EngineChannel::OutputChannel(uint EngineAudioChannel) {      int EngineChannel::OutputChannel(uint EngineAudioChannel) {
# Line 309  namespace LinuxSampler { namespace gig { Line 423  namespace LinuxSampler { namespace gig {
423          }          }
424      }      }
425    
426        void EngineChannel::Connect(MidiInputPort* pMidiPort, midi_chan_t MidiChannel) {
427            if (!pMidiPort || pMidiPort == this->pMidiInputPort) return;
428            DisconnectMidiInputPort();
429            this->pMidiInputPort = pMidiPort;
430            this->midiChannel    = MidiChannel;
431            pMidiPort->Connect(this, MidiChannel);
432        }
433    
434        void EngineChannel::DisconnectMidiInputPort() {
435            MidiInputPort* pOldPort = this->pMidiInputPort;
436            this->pMidiInputPort = NULL;
437            if (pOldPort) pOldPort->Disconnect(this);
438        }
439    
440        MidiInputPort* EngineChannel::GetMidiInputPort() {
441            return pMidiInputPort;
442        }
443    
444        midi_chan_t EngineChannel::MidiChannel() {
445            return midiChannel;
446        }
447    
448        FxSend* EngineChannel::AddFxSend(uint8_t MidiCtrl, String Name) throw (Exception) {
449            if (pEngine) pEngine->DisableAndLock();
450            FxSend* pFxSend = new FxSend(this, MidiCtrl, Name);
451            if (fxSends.empty()) {
452                if (pEngine && pEngine->pAudioOutputDevice) {
453                    AudioOutputDevice* pDevice = pEngine->pAudioOutputDevice;
454                    // create local render buffers
455                    pChannelLeft  = new AudioChannel(0, pDevice->MaxSamplesPerCycle());
456                    pChannelRight = new AudioChannel(1, pDevice->MaxSamplesPerCycle());
457                } else {
458                    // postpone local render buffer creation until audio device is assigned
459                    pChannelLeft  = NULL;
460                    pChannelRight = NULL;
461                }
462            }
463            fxSends.push_back(pFxSend);
464            if (pEngine) pEngine->Enable();
465            fireFxSendCountChanged(GetSamplerChannel()->Index(), GetFxSendCount());
466    
467            return pFxSend;
468        }
469    
470        FxSend* EngineChannel::GetFxSend(uint FxSendIndex) {
471            return (FxSendIndex < fxSends.size()) ? fxSends[FxSendIndex] : NULL;
472        }
473    
474        uint EngineChannel::GetFxSendCount() {
475            return fxSends.size();
476        }
477    
478        void EngineChannel::RemoveFxSend(FxSend* pFxSend) {
479            if (pEngine) pEngine->DisableAndLock();
480            for (
481                std::vector<FxSend*>::iterator iter = fxSends.begin();
482                iter != fxSends.end(); iter++
483            ) {
484                if (*iter == pFxSend) {
485                    delete pFxSend;
486                    fxSends.erase(iter);
487                    if (fxSends.empty()) {
488                        // destroy local render buffers
489                        if (pChannelLeft)  delete pChannelLeft;
490                        if (pChannelRight) delete pChannelRight;
491                        // fallback to render directly into AudioOutputDevice's buffers
492                        if (pEngine && pEngine->pAudioOutputDevice) {
493                            pChannelLeft  = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannelLeft);
494                            pChannelRight = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannelRight);
495                        } else { // we update the pointers later
496                            pChannelLeft  = NULL;
497                            pChannelRight = NULL;
498                        }
499                    }
500                    break;
501                }
502            }
503            if (pEngine) pEngine->Enable();
504            fireFxSendCountChanged(GetSamplerChannel()->Index(), GetFxSendCount());
505        }
506    
507      /**      /**
508       *  Will be called by the MIDIIn Thread to let the audio thread trigger a new       *  Will be called by the MIDIIn Thread to let the audio thread trigger a new
509       *  voice for the given key.       *  voice for the given key. This method is meant for real time rendering,
510         *  that is an event will immediately be created with the current system
511         *  time as time stamp.
512       *       *
513       *  @param Key      - MIDI key number of the triggered key       *  @param Key      - MIDI key number of the triggered key
514       *  @param Velocity - MIDI velocity value of the triggered key       *  @param Velocity - MIDI velocity value of the triggered key
# Line 325  namespace LinuxSampler { namespace gig { Line 522  namespace LinuxSampler { namespace gig {
522              event.pEngineChannel      = this;              event.pEngineChannel      = this;
523              if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);              if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
524              else dmsg(1,("EngineChannel: Input event queue full!"));              else dmsg(1,("EngineChannel: Input event queue full!"));
525                // inform connected virtual MIDI devices if any ...
526                // (e.g. virtual MIDI keyboard in instrument editor(s))
527                ArrayList<VirtualMidiDevice*>& devices =
528                    const_cast<ArrayList<VirtualMidiDevice*>&>(
529                        virtualMidiDevicesReader_MidiThread.Lock()
530                    );
531                for (int i = 0; i < devices.size(); i++) {
532                    devices[i]->SendNoteOnToDevice(Key, Velocity);
533                }
534                virtualMidiDevicesReader_MidiThread.Unlock();
535            }
536        }
537    
538        /**
539         *  Will be called by the MIDIIn Thread to let the audio thread trigger a new
540         *  voice for the given key. This method is meant for offline rendering
541         *  and / or for cases where the exact position of the event in the current
542         *  audio fragment is already known.
543         *
544         *  @param Key         - MIDI key number of the triggered key
545         *  @param Velocity    - MIDI velocity value of the triggered key
546         *  @param FragmentPos - sample point position in the current audio
547         *                       fragment to which this event belongs to
548         */
549        void EngineChannel::SendNoteOn(uint8_t Key, uint8_t Velocity, int32_t FragmentPos) {
550            if (FragmentPos < 0) {
551                dmsg(1,("EngineChannel::SendNoteOn(): negative FragmentPos! Seems MIDI driver is buggy!"));
552            }
553            else if (pEngine) {
554                Event event               = pEngine->pEventGenerator->CreateEvent(FragmentPos);
555                event.Type                = Event::type_note_on;
556                event.Param.Note.Key      = Key;
557                event.Param.Note.Velocity = Velocity;
558                event.pEngineChannel      = this;
559                if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
560                else dmsg(1,("EngineChannel: Input event queue full!"));
561                // inform connected virtual MIDI devices if any ...
562                // (e.g. virtual MIDI keyboard in instrument editor(s))
563                ArrayList<VirtualMidiDevice*>& devices =
564                    const_cast<ArrayList<VirtualMidiDevice*>&>(
565                        virtualMidiDevicesReader_MidiThread.Lock()
566                    );
567                for (int i = 0; i < devices.size(); i++) {
568                    devices[i]->SendNoteOnToDevice(Key, Velocity);
569                }
570                virtualMidiDevicesReader_MidiThread.Unlock();
571          }          }
572      }      }
573    
574      /**      /**
575       *  Will be called by the MIDIIn Thread to signal the audio thread to release       *  Will be called by the MIDIIn Thread to signal the audio thread to release
576       *  voice(s) on the given key.       *  voice(s) on the given key. This method is meant for real time rendering,
577         *  that is an event will immediately be created with the current system
578         *  time as time stamp.
579       *       *
580       *  @param Key      - MIDI key number of the released key       *  @param Key      - MIDI key number of the released key
581       *  @param Velocity - MIDI release velocity value of the released key       *  @param Velocity - MIDI release velocity value of the released key
# Line 344  namespace LinuxSampler { namespace gig { Line 589  namespace LinuxSampler { namespace gig {
589              event.pEngineChannel      = this;              event.pEngineChannel      = this;
590              if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);              if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
591              else dmsg(1,("EngineChannel: Input event queue full!"));              else dmsg(1,("EngineChannel: Input event queue full!"));
592                // inform connected virtual MIDI devices if any ...
593                // (e.g. virtual MIDI keyboard in instrument editor(s))
594                ArrayList<VirtualMidiDevice*>& devices =
595                    const_cast<ArrayList<VirtualMidiDevice*>&>(
596                        virtualMidiDevicesReader_MidiThread.Lock()
597                    );
598                for (int i = 0; i < devices.size(); i++) {
599                    devices[i]->SendNoteOffToDevice(Key, Velocity);
600                }
601                virtualMidiDevicesReader_MidiThread.Unlock();
602            }
603        }
604    
605        /**
606         *  Will be called by the MIDIIn Thread to signal the audio thread to release
607         *  voice(s) on the given key. This method is meant for offline rendering
608         *  and / or for cases where the exact position of the event in the current
609         *  audio fragment is already known.
610         *
611         *  @param Key         - MIDI key number of the released key
612         *  @param Velocity    - MIDI release velocity value of the released key
613         *  @param FragmentPos - sample point position in the current audio
614         *                       fragment to which this event belongs to
615         */
616        void EngineChannel::SendNoteOff(uint8_t Key, uint8_t Velocity, int32_t FragmentPos) {
617            if (FragmentPos < 0) {
618                dmsg(1,("EngineChannel::SendNoteOff(): negative FragmentPos! Seems MIDI driver is buggy!"));
619            }
620            else if (pEngine) {
621                Event event               = pEngine->pEventGenerator->CreateEvent(FragmentPos);
622                event.Type                = Event::type_note_off;
623                event.Param.Note.Key      = Key;
624                event.Param.Note.Velocity = Velocity;
625                event.pEngineChannel      = this;
626                if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
627                else dmsg(1,("EngineChannel: Input event queue full!"));
628                // inform connected virtual MIDI devices if any ...
629                // (e.g. virtual MIDI keyboard in instrument editor(s))
630                ArrayList<VirtualMidiDevice*>& devices =
631                    const_cast<ArrayList<VirtualMidiDevice*>&>(
632                        virtualMidiDevicesReader_MidiThread.Lock()
633                    );
634                for (int i = 0; i < devices.size(); i++) {
635                    devices[i]->SendNoteOffToDevice(Key, Velocity);
636                }
637                virtualMidiDevicesReader_MidiThread.Unlock();
638          }          }
639      }      }
640    
641      /**      /**
642       *  Will be called by the MIDIIn Thread to signal the audio thread to change       *  Will be called by the MIDIIn Thread to signal the audio thread to change
643       *  the pitch value for all voices.       *  the pitch value for all voices. This method is meant for real time
644         *  rendering, that is an event will immediately be created with the
645         *  current system time as time stamp.
646       *       *
647       *  @param Pitch - MIDI pitch value (-8192 ... +8191)       *  @param Pitch - MIDI pitch value (-8192 ... +8191)
648       */       */
# Line 365  namespace LinuxSampler { namespace gig { Line 658  namespace LinuxSampler { namespace gig {
658      }      }
659    
660      /**      /**
661         *  Will be called by the MIDIIn Thread to signal the audio thread to change
662         *  the pitch value for all voices. This method is meant for offline
663         *  rendering and / or for cases where the exact position of the event in
664         *  the current audio fragment is already known.
665         *
666         *  @param Pitch       - MIDI pitch value (-8192 ... +8191)
667         *  @param FragmentPos - sample point position in the current audio
668         *                       fragment to which this event belongs to
669         */
670        void EngineChannel::SendPitchbend(int Pitch, int32_t FragmentPos) {
671            if (FragmentPos < 0) {
672                dmsg(1,("EngineChannel::SendPitchBend(): negative FragmentPos! Seems MIDI driver is buggy!"));
673            }
674            else if (pEngine) {
675                Event event             = pEngine->pEventGenerator->CreateEvent(FragmentPos);
676                event.Type              = Event::type_pitchbend;
677                event.Param.Pitch.Pitch = Pitch;
678                event.pEngineChannel    = this;
679                if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
680                else dmsg(1,("EngineChannel: Input event queue full!"));
681            }
682        }
683    
684        /**
685       *  Will be called by the MIDIIn Thread to signal the audio thread that a       *  Will be called by the MIDIIn Thread to signal the audio thread that a
686       *  continuous controller value has changed.       *  continuous controller value has changed. This method is meant for real
687         *  time rendering, that is an event will immediately be created with the
688         *  current system time as time stamp.
689       *       *
690       *  @param Controller - MIDI controller number of the occured control change       *  @param Controller - MIDI controller number of the occured control change
691       *  @param Value      - value of the control change       *  @param Value      - value of the control change
# Line 383  namespace LinuxSampler { namespace gig { Line 702  namespace LinuxSampler { namespace gig {
702          }          }
703      }      }
704    
705        /**
706         *  Will be called by the MIDIIn Thread to signal the audio thread that a
707         *  continuous controller value has changed. This method is meant for
708         *  offline rendering and / or for cases where the exact position of the
709         *  event in the current audio fragment is already known.
710         *
711         *  @param Controller  - MIDI controller number of the occured control change
712         *  @param Value       - value of the control change
713         *  @param FragmentPos - sample point position in the current audio
714         *                       fragment to which this event belongs to
715         */
716        void EngineChannel::SendControlChange(uint8_t Controller, uint8_t Value, int32_t FragmentPos) {
717            if (FragmentPos < 0) {
718                dmsg(1,("EngineChannel::SendControlChange(): negative FragmentPos! Seems MIDI driver is buggy!"));
719            }
720            else if (pEngine) {
721                Event event               = pEngine->pEventGenerator->CreateEvent(FragmentPos);
722                event.Type                = Event::type_control_change;
723                event.Param.CC.Controller = Controller;
724                event.Param.CC.Value      = Value;
725                event.pEngineChannel      = this;
726                if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
727                else dmsg(1,("EngineChannel: Input event queue full!"));
728            }
729        }
730    
731      void EngineChannel::ClearEventLists() {      void EngineChannel::ClearEventLists() {
732          pEvents->clear();          pEvents->clear();
         pCCEvents->clear();  
         for (uint i = 0; i < Event::destination_count; i++) {  
             pSynthesisEvents[i]->clear();  
         }  
733          // empty MIDI key specific event lists          // empty MIDI key specific event lists
734          {          {
735              RTList<uint>::Iterator iuiKey = pActiveKeys->first();              RTList<uint>::Iterator iuiKey = pActiveKeys->first();
# Line 400  namespace LinuxSampler { namespace gig { Line 741  namespace LinuxSampler { namespace gig {
741      }      }
742    
743      void EngineChannel::ResetControllers() {      void EngineChannel::ResetControllers() {
744            Pitch          = 0;
745            SustainPedal   = false;
746            SostenutoPedal = false;
747            GlobalVolume   = 1.0f;
748            MidiVolume     = 1.0;
749            GlobalPanLeft  = 1.0f;
750            GlobalPanRight = 1.0f;
751            iLastPanRequest = 64;
752            GlobalTranspose = 0;
753          // set all MIDI controller values to zero          // set all MIDI controller values to zero
754          memset(ControllerTable, 0x00, 128);          memset(ControllerTable, 0x00, 129);
755            // reset all FX Send levels
756            for (
757                std::vector<FxSend*>::iterator iter = fxSends.begin();
758                iter != fxSends.end(); iter++
759            ) {
760                (*iter)->Reset();
761            }
762      }      }
763    
764      /**      /**
# Line 418  namespace LinuxSampler { namespace gig { Line 775  namespace LinuxSampler { namespace gig {
775       *                  current audio cycle       *                  current audio cycle
776       */       */
777      void EngineChannel::ImportEvents(uint Samples) {      void EngineChannel::ImportEvents(uint Samples) {
778          RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();          // import events from pure software MIDI "devices"
779            // (e.g. virtual keyboard in instrument editor)
780            {
781                const int FragmentPos = 0; // randomly chosen, we don't care about jitter for virtual MIDI devices
782                Event event = pEngine->pEventGenerator->CreateEvent(FragmentPos);
783                VirtualMidiDevice::event_t devEvent; // the event format we get from the virtual MIDI device
784                // as we're going to (carefully) write some status to the
785                // synchronized struct, we cast away the const
786                ArrayList<VirtualMidiDevice*>& devices =
787                    const_cast<ArrayList<VirtualMidiDevice*>&>(virtualMidiDevicesReader_AudioThread.Lock());
788                // iterate through all virtual MIDI devices
789                for (int i = 0; i < devices.size(); i++) {
790                    VirtualMidiDevice* pDev = devices[i];
791                    // I think we can simply flush the whole FIFO(s), the user shouldn't be so fast ;-)
792                    while (pDev->GetMidiEventFromDevice(devEvent)) {
793                        event.Type =
794                            (devEvent.Type == VirtualMidiDevice::EVENT_TYPE_NOTEON) ?
795                                Event::type_note_on : Event::type_note_off;
796                        event.Param.Note.Key      = devEvent.Key;
797                        event.Param.Note.Velocity = devEvent.Velocity;
798                        event.pEngineChannel      = this;
799                        // copy event to internal event list
800                        if (pEvents->poolIsEmpty()) {
801                            dmsg(1,("Event pool emtpy!\n"));
802                            goto exitVirtualDevicesLoop;
803                        }
804                        *pEvents->allocAppend() = event;
805                    }
806                }
807            }
808            exitVirtualDevicesLoop:
809            virtualMidiDevicesReader_AudioThread.Unlock();
810    
811            // import events from the regular MIDI devices
812            RingBuffer<Event,false>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
813          Event* pEvent;          Event* pEvent;
814          while (true) {          while (true) {
815              // get next event from input event queue              // get next event from input event queue
# Line 440  namespace LinuxSampler { namespace gig { Line 831  namespace LinuxSampler { namespace gig {
831          eventQueueReader.free(); // free all copied events from input queue          eventQueueReader.free(); // free all copied events from input queue
832      }      }
833    
834        void EngineChannel::RemoveAllFxSends() {
835            if (pEngine) pEngine->DisableAndLock();
836            if (!fxSends.empty()) { // free local render buffers
837                if (pChannelLeft) {
838                    delete pChannelLeft;
839                    if (pEngine && pEngine->pAudioOutputDevice) {
840                        // fallback to render directly to the AudioOutputDevice's buffer
841                        pChannelLeft = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannelLeft);
842                    } else pChannelLeft = NULL;
843                }
844                if (pChannelRight) {
845                    delete pChannelRight;
846                    if (pEngine && pEngine->pAudioOutputDevice) {
847                        // fallback to render directly to the AudioOutputDevice's buffer
848                        pChannelRight = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannelRight);
849                    } else pChannelRight = NULL;
850                }
851            }
852            for (int i = 0; i < fxSends.size(); i++) delete fxSends[i];
853            fxSends.clear();
854            if (pEngine) pEngine->Enable();
855        }
856    
857        void EngineChannel::Connect(VirtualMidiDevice* pDevice) {
858            // double buffer ... double work ...
859            {
860                ArrayList<VirtualMidiDevice*>& devices = virtualMidiDevices.GetConfigForUpdate();
861                devices.add(pDevice);
862            }
863            {
864                ArrayList<VirtualMidiDevice*>& devices = virtualMidiDevices.SwitchConfig();
865                devices.add(pDevice);
866            }
867        }
868    
869        void EngineChannel::Disconnect(VirtualMidiDevice* pDevice) {
870            // double buffer ... double work ...
871            {
872                ArrayList<VirtualMidiDevice*>& devices = virtualMidiDevices.GetConfigForUpdate();
873                devices.remove(pDevice);
874            }
875            {
876                ArrayList<VirtualMidiDevice*>& devices = virtualMidiDevices.SwitchConfig();
877                devices.remove(pDevice);
878            }
879        }
880    
881      float EngineChannel::Volume() {      float EngineChannel::Volume() {
882          return GlobalVolume;          return GlobalVolume;
883      }      }
884    
885      void EngineChannel::Volume(float f) {      void EngineChannel::Volume(float f) {
886          GlobalVolume = f;          GlobalVolume = f;
887            bStatusChanged = true; // status of engine channel has changed, so set notify flag
888        }
889    
890        float EngineChannel::Pan() {
891            return float(iLastPanRequest - 64) / 64.0f;
892        }
893    
894        void EngineChannel::Pan(float f) {
895            int iMidiPan = int(f * 64.0f) + 64;
896            if (iMidiPan > 127) iMidiPan = 127;
897            else if (iMidiPan < 0) iMidiPan = 0;
898            GlobalPanLeft  = Engine::PanCurve[128 - iMidiPan];
899            GlobalPanRight = Engine::PanCurve[iMidiPan];
900            iLastPanRequest = iMidiPan;
901      }      }
902    
903      uint EngineChannel::Channels() {      uint EngineChannel::Channels() {
# Line 471  namespace LinuxSampler { namespace gig { Line 923  namespace LinuxSampler { namespace gig {
923      String EngineChannel::EngineName() {      String EngineChannel::EngineName() {
924          return LS_GIG_ENGINE_NAME;          return LS_GIG_ENGINE_NAME;
925      }      }
926        
927  }} // namespace LinuxSampler::gig  }} // namespace LinuxSampler::gig

Legend:
Removed from v.554  
changed lines
  Added in v.1826

  ViewVC Help
Powered by ViewVC