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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1924 - (hide annotations) (download)
Sun Jun 28 16:43:38 2009 UTC (14 years, 9 months ago) by persson
File size: 41532 byte(s)
* made program change handling in MIDI thread real-time safe by moving
  the logic to a non-RT thread

1 schoenebeck 411 /***************************************************************************
2     * *
3     * LinuxSampler - modular, streaming capable sampler *
4     * *
5     * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck *
6 persson 1844 * Copyright (C) 2005 - 2009 Christian Schoenebeck *
7 schoenebeck 411 * *
8     * 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 *
10     * the Free Software Foundation; either version 2 of the License, or *
11     * (at your option) any later version. *
12     * *
13     * This program is distributed in the hope that it will be useful, *
14     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16     * GNU General Public License for more details. *
17     * *
18     * You should have received a copy of the GNU General Public License *
19     * along with this program; if not, write to the Free Software *
20     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
21     * MA 02111-1307 USA *
22     ***************************************************************************/
23    
24     #include "EngineChannel.h"
25    
26 schoenebeck 1424 #include "../../common/global_private.h"
27 iliev 1761 #include "../../Sampler.h"
28 schoenebeck 1424
29 persson 438 namespace LinuxSampler { namespace gig {
30 schoenebeck 411
31 persson 1646 EngineChannel::EngineChannel() :
32 schoenebeck 1659 InstrumentChangeCommandReader(InstrumentChangeCommand),
33 schoenebeck 1662 virtualMidiDevicesReader_AudioThread(virtualMidiDevices),
34     virtualMidiDevicesReader_MidiThread(virtualMidiDevices)
35 schoenebeck 1659 {
36 schoenebeck 411 pMIDIKeyInfo = new midi_key_info_t[128];
37     pEngine = NULL;
38     pInstrument = NULL;
39 schoenebeck 460 pEvents = NULL; // we allocate when we retrieve the right Engine object
40 schoenebeck 970 pEventQueue = new RingBuffer<Event,false>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);
41 schoenebeck 411 pActiveKeys = new Pool<uint>(128);
42     for (uint i = 0; i < 128; i++) {
43     pMIDIKeyInfo[i].pActiveVoices = NULL; // we allocate when we retrieve the right Engine object
44     pMIDIKeyInfo[i].KeyPressed = false;
45     pMIDIKeyInfo[i].Active = false;
46     pMIDIKeyInfo[i].ReleaseTrigger = false;
47     pMIDIKeyInfo[i].pEvents = NULL; // we allocate when we retrieve the right Engine object
48 schoenebeck 473 pMIDIKeyInfo[i].VoiceTheftsQueued = 0;
49 persson 438 pMIDIKeyInfo[i].RoundRobinIndex = 0;
50 schoenebeck 411 }
51     InstrumentIdx = -1;
52     InstrumentStat = -1;
53 schoenebeck 1001 pChannelLeft = NULL;
54     pChannelRight = NULL;
55 schoenebeck 411 AudioDeviceChannelLeft = -1;
56     AudioDeviceChannelRight = -1;
57 schoenebeck 675 pMidiInputPort = NULL;
58     midiChannel = midi_chan_all;
59 schoenebeck 670 ResetControllers();
60 schoenebeck 829 SoloMode = false;
61     PortamentoMode = false;
62     PortamentoTime = CONFIG_PORTAMENTO_TIME_DEFAULT;
63 iliev 1835
64     // reset the instrument change command struct (need to be done
65     // twice, as it is double buffered)
66     {
67     instrument_change_command_t& cmd = InstrumentChangeCommand.GetConfigForUpdate();
68     cmd.pDimRegionsInUse = NULL;
69     cmd.pInstrument = NULL;
70     cmd.bChangeInstrument = false;
71     }
72     {
73     instrument_change_command_t& cmd = InstrumentChangeCommand.SwitchConfig();
74     cmd.pDimRegionsInUse = NULL;
75     cmd.pInstrument = NULL;
76     cmd.bChangeInstrument = false;
77     }
78 schoenebeck 411 }
79    
80     EngineChannel::~EngineChannel() {
81 schoenebeck 460 DisconnectAudioOutputDevice();
82 iliev 1826
83     // In case the channel was removed before the instrument was
84     // fully loaded, try to give back instrument again (see bug #113)
85     instrument_change_command_t& cmd = ChangeInstrument(NULL);
86     if (cmd.pInstrument) {
87     Engine::instruments.HandBack(cmd.pInstrument, this);
88     }
89     ///////
90    
91 schoenebeck 411 if (pEventQueue) delete pEventQueue;
92     if (pActiveKeys) delete pActiveKeys;
93     if (pMIDIKeyInfo) delete[] pMIDIKeyInfo;
94 schoenebeck 1001 RemoveAllFxSends();
95 schoenebeck 411 }
96    
97     /**
98 schoenebeck 660 * Implementation of virtual method from abstract EngineChannel interface.
99     * This method will periodically be polled (e.g. by the LSCP server) to
100     * check if some engine channel parameter has changed since the last
101     * StatusChanged() call.
102     *
103 schoenebeck 670 * This method can also be used to mark the engine channel as changed
104     * from outside, e.g. by a MIDI input device. The optional argument
105     * \a nNewStatus can be used for this.
106     *
107 schoenebeck 660 * TODO: This "poll method" is just a lazy solution and might be
108     * replaced in future.
109 schoenebeck 670 * @param bNewStatus - (optional, default: false) sets the new status flag
110 schoenebeck 660 * @returns true if engine channel status has changed since last
111     * StatusChanged() call
112     */
113 schoenebeck 670 bool EngineChannel::StatusChanged(bool bNewStatus) {
114 schoenebeck 660 bool b = bStatusChanged;
115 schoenebeck 670 bStatusChanged = bNewStatus;
116 schoenebeck 660 return b;
117     }
118    
119 schoenebeck 670 void EngineChannel::Reset() {
120     if (pEngine) pEngine->DisableAndLock();
121     ResetInternal();
122     ResetControllers();
123     if (pEngine) {
124     pEngine->Enable();
125     pEngine->Reset();
126     }
127     }
128    
129 schoenebeck 660 /**
130 schoenebeck 411 * This method is not thread safe!
131     */
132     void EngineChannel::ResetInternal() {
133     CurrentKeyDimension = 0;
134    
135     // reset key info
136     for (uint i = 0; i < 128; i++) {
137     if (pMIDIKeyInfo[i].pActiveVoices)
138     pMIDIKeyInfo[i].pActiveVoices->clear();
139     if (pMIDIKeyInfo[i].pEvents)
140     pMIDIKeyInfo[i].pEvents->clear();
141     pMIDIKeyInfo[i].KeyPressed = false;
142     pMIDIKeyInfo[i].Active = false;
143     pMIDIKeyInfo[i].ReleaseTrigger = false;
144     pMIDIKeyInfo[i].itSelf = Pool<uint>::Iterator();
145 schoenebeck 473 pMIDIKeyInfo[i].VoiceTheftsQueued = 0;
146 schoenebeck 411 }
147 schoenebeck 829 SoloKey = -1; // no solo key active yet
148     PortamentoPos = -1.0f; // no portamento active yet
149 schoenebeck 411
150     // reset all key groups
151     std::map<uint,uint*>::iterator iter = ActiveKeyGroups.begin();
152     for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;
153    
154     // free all active keys
155     pActiveKeys->clear();
156    
157     // delete all input events
158     pEventQueue->init();
159    
160     if (pEngine) pEngine->ResetInternal();
161 schoenebeck 660
162     // status of engine channel has changed, so set notify flag
163     bStatusChanged = true;
164 schoenebeck 411 }
165    
166     LinuxSampler::Engine* EngineChannel::GetEngine() {
167     return pEngine;
168     }
169    
170     /**
171     * More or less a workaround to set the instrument name, index and load
172     * status variable to zero percent immediately, that is without blocking
173     * the calling thread. It might be used in future for other preparations
174     * as well though.
175     *
176     * @param FileName - file name of the Gigasampler instrument file
177     * @param Instrument - index of the instrument in the .gig file
178     * @see LoadInstrument()
179     */
180     void EngineChannel::PrepareLoadInstrument(const char* FileName, uint Instrument) {
181     InstrumentFile = FileName;
182     InstrumentIdx = Instrument;
183     InstrumentStat = 0;
184     }
185    
186     /**
187     * Load an instrument from a .gig file. PrepareLoadInstrument() has to
188     * be called first to provide the information which instrument to load.
189     * This method will then actually start to load the instrument and block
190     * the calling thread until loading was completed.
191     *
192     * @see PrepareLoadInstrument()
193     */
194     void EngineChannel::LoadInstrument() {
195 persson 1646 // make sure we don't trigger any new notes with an old
196     // instrument
197     instrument_change_command_t& cmd = ChangeInstrument(0);
198     if (cmd.pInstrument) {
199     // give old instrument back to instrument manager, but
200     // keep the dimension regions and samples that are in use
201     Engine::instruments.HandBackInstrument(cmd.pInstrument, this, cmd.pDimRegionsInUse);
202 schoenebeck 411 }
203 persson 1646 cmd.pDimRegionsInUse->clear();
204 schoenebeck 411
205     // delete all key groups
206     ActiveKeyGroups.clear();
207    
208     // request gig instrument from instrument manager
209 persson 1038 ::gig::Instrument* newInstrument;
210 schoenebeck 411 try {
211 schoenebeck 947 InstrumentManager::instrument_id_t instrid;
212     instrid.FileName = InstrumentFile;
213     instrid.Index = InstrumentIdx;
214 persson 1038 newInstrument = Engine::instruments.Borrow(instrid, this);
215     if (!newInstrument) {
216 schoenebeck 1212 throw InstrumentManagerException("resource was not created");
217 schoenebeck 411 }
218     }
219     catch (RIFF::Exception e) {
220     InstrumentStat = -2;
221 iliev 1309 StatusChanged(true);
222 schoenebeck 411 String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;
223 schoenebeck 880 throw Exception(msg);
224 schoenebeck 411 }
225 schoenebeck 1212 catch (InstrumentManagerException e) {
226 schoenebeck 411 InstrumentStat = -3;
227 iliev 1309 StatusChanged(true);
228 schoenebeck 411 String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();
229 schoenebeck 880 throw Exception(msg);
230 schoenebeck 411 }
231     catch (...) {
232     InstrumentStat = -4;
233 iliev 1309 StatusChanged(true);
234 schoenebeck 880 throw Exception("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");
235 schoenebeck 411 }
236    
237     // rebuild ActiveKeyGroups map with key groups of current instrument
238 persson 1038 for (::gig::Region* pRegion = newInstrument->GetFirstRegion(); pRegion; pRegion = newInstrument->GetNextRegion())
239 schoenebeck 411 if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL;
240    
241 persson 1038 InstrumentIdxName = newInstrument->pInfo->Name;
242 schoenebeck 411 InstrumentStat = 100;
243    
244 persson 1646 ChangeInstrument(newInstrument);
245    
246 iliev 1298 StatusChanged(true);
247 schoenebeck 411 }
248    
249 persson 1646
250 schoenebeck 411 /**
251 persson 1646 * Changes the instrument for an engine channel.
252     *
253     * @param pInstrument - new instrument
254     * @returns the resulting instrument change command after the
255     * command switch, containing the old instrument and
256     * the dimregions it is using
257     */
258     EngineChannel::instrument_change_command_t& EngineChannel::ChangeInstrument(::gig::Instrument* pInstrument) {
259     instrument_change_command_t& cmd = InstrumentChangeCommand.GetConfigForUpdate();
260     cmd.pInstrument = pInstrument;
261     cmd.bChangeInstrument = true;
262    
263     return InstrumentChangeCommand.SwitchConfig();
264     }
265    
266     /**
267 schoenebeck 411 * Will be called by the InstrumentResourceManager when the instrument
268 schoenebeck 517 * we are currently using on this EngineChannel is going to be updated,
269     * so we can stop playback before that happens.
270 schoenebeck 411 */
271     void EngineChannel::ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {
272     dmsg(3,("gig::Engine: Received instrument update message.\n"));
273     if (pEngine) pEngine->DisableAndLock();
274     ResetInternal();
275     this->pInstrument = NULL;
276     }
277    
278     /**
279     * Will be called by the InstrumentResourceManager when the instrument
280     * update process was completed, so we can continue with playback.
281     */
282     void EngineChannel::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {
283     this->pInstrument = pNewResource; //TODO: there are couple of engine parameters we should update here as well if the instrument was updated (see LoadInstrument())
284     if (pEngine) pEngine->Enable();
285 schoenebeck 660 bStatusChanged = true; // status of engine has changed, so set notify flag
286 schoenebeck 411 }
287    
288 schoenebeck 517 /**
289     * Will be called by the InstrumentResourceManager on progress changes
290     * while loading or realoading an instrument for this EngineChannel.
291     *
292     * @param fProgress - current progress as value between 0.0 and 1.0
293     */
294     void EngineChannel::OnResourceProgress(float fProgress) {
295     this->InstrumentStat = int(fProgress * 100.0f);
296     dmsg(7,("gig::EngineChannel: progress %d%", InstrumentStat));
297 schoenebeck 660 bStatusChanged = true; // status of engine has changed, so set notify flag
298 schoenebeck 517 }
299    
300 schoenebeck 412 void EngineChannel::Connect(AudioOutputDevice* pAudioOut) {
301 schoenebeck 460 if (pEngine) {
302     if (pEngine->pAudioOutputDevice == pAudioOut) return;
303 schoenebeck 412 DisconnectAudioOutputDevice();
304     }
305 schoenebeck 411 pEngine = Engine::AcquireEngine(this, pAudioOut);
306 persson 438 ResetInternal();
307 schoenebeck 738 pEvents = new RTList<Event>(pEngine->pEventPool);
308 persson 1646
309     // reset the instrument change command struct (need to be done
310     // twice, as it is double buffered)
311     {
312     instrument_change_command_t& cmd = InstrumentChangeCommand.GetConfigForUpdate();
313     cmd.pDimRegionsInUse = new RTList< ::gig::DimensionRegion*>(pEngine->pDimRegionPool[0]);
314     cmd.pInstrument = 0;
315     cmd.bChangeInstrument = false;
316     }
317     {
318     instrument_change_command_t& cmd = InstrumentChangeCommand.SwitchConfig();
319     cmd.pDimRegionsInUse = new RTList< ::gig::DimensionRegion*>(pEngine->pDimRegionPool[1]);
320     cmd.pInstrument = 0;
321     cmd.bChangeInstrument = false;
322     }
323    
324 iliev 1847 if (pInstrument != NULL) {
325     pInstrument = NULL;
326     InstrumentStat = -1;
327     InstrumentIdx = -1;
328     InstrumentIdxName = "";
329     InstrumentFile = "";
330     bStatusChanged = true;
331     }
332    
333 schoenebeck 411 for (uint i = 0; i < 128; i++) {
334     pMIDIKeyInfo[i].pActiveVoices = new RTList<Voice>(pEngine->pVoicePool);
335     pMIDIKeyInfo[i].pEvents = new RTList<Event>(pEngine->pEventPool);
336     }
337     AudioDeviceChannelLeft = 0;
338     AudioDeviceChannelRight = 1;
339 schoenebeck 1001 if (fxSends.empty()) { // render directly into the AudioDevice's output buffers
340     pChannelLeft = pAudioOut->Channel(AudioDeviceChannelLeft);
341     pChannelRight = pAudioOut->Channel(AudioDeviceChannelRight);
342     } else { // use local buffers for rendering and copy later
343     // ensure the local buffers have the correct size
344     if (pChannelLeft) delete pChannelLeft;
345     if (pChannelRight) delete pChannelRight;
346     pChannelLeft = new AudioChannel(0, pAudioOut->MaxSamplesPerCycle());
347     pChannelRight = new AudioChannel(1, pAudioOut->MaxSamplesPerCycle());
348     }
349 persson 1039 if (pEngine->EngineDisabled.GetUnsafe()) pEngine->Enable();
350 persson 846 MidiInputPort::AddSysexListener(pEngine);
351 schoenebeck 411 }
352    
353     void EngineChannel::DisconnectAudioOutputDevice() {
354     if (pEngine) { // if clause to prevent disconnect loops
355 persson 1646
356 persson 1844 ResetInternal();
357    
358 persson 1646 // delete the structures used for instrument change
359     RTList< ::gig::DimensionRegion*>* d = InstrumentChangeCommand.GetConfigForUpdate().pDimRegionsInUse;
360     if (d) delete d;
361     EngineChannel::instrument_change_command_t& cmd = InstrumentChangeCommand.SwitchConfig();
362     d = cmd.pDimRegionsInUse;
363 persson 1844 if (d) delete d;
364 persson 1646
365     if (cmd.pInstrument) {
366     // release the currently loaded instrument
367 persson 1844 Engine::instruments.HandBack(cmd.pInstrument, this);
368 persson 1646 }
369 iliev 1761
370 schoenebeck 460 if (pEvents) {
371     delete pEvents;
372     pEvents = NULL;
373     }
374 schoenebeck 411 for (uint i = 0; i < 128; i++) {
375 schoenebeck 420 if (pMIDIKeyInfo[i].pActiveVoices) {
376     delete pMIDIKeyInfo[i].pActiveVoices;
377     pMIDIKeyInfo[i].pActiveVoices = NULL;
378     }
379     if (pMIDIKeyInfo[i].pEvents) {
380     delete pMIDIKeyInfo[i].pEvents;
381     pMIDIKeyInfo[i].pEvents = NULL;
382     }
383 schoenebeck 411 }
384     AudioOutputDevice* oldAudioDevice = pEngine->pAudioOutputDevice;
385     pEngine = NULL;
386     Engine::FreeEngine(this, oldAudioDevice);
387     AudioDeviceChannelLeft = -1;
388 persson 438 AudioDeviceChannelRight = -1;
389 schoenebeck 1001 if (!fxSends.empty()) { // free the local rendering buffers
390     if (pChannelLeft) delete pChannelLeft;
391     if (pChannelRight) delete pChannelRight;
392     }
393     pChannelLeft = NULL;
394     pChannelRight = NULL;
395 schoenebeck 411 }
396     }
397    
398 schoenebeck 1001 AudioOutputDevice* EngineChannel::GetAudioOutputDevice() {
399     return (pEngine) ? pEngine->pAudioOutputDevice : NULL;
400     }
401    
402 schoenebeck 411 void EngineChannel::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) {
403     if (!pEngine || !pEngine->pAudioOutputDevice) throw AudioOutputException("No audio output device connected yet.");
404 persson 438
405 schoenebeck 411 AudioChannel* pChannel = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannel);
406     if (!pChannel) throw AudioOutputException("Invalid audio output device channel " + ToString(AudioDeviceChannel));
407     switch (EngineAudioChannel) {
408     case 0: // left output channel
409 schoenebeck 1001 if (fxSends.empty()) pChannelLeft = pChannel;
410 schoenebeck 411 AudioDeviceChannelLeft = AudioDeviceChannel;
411     break;
412     case 1: // right output channel
413 schoenebeck 1001 if (fxSends.empty()) pChannelRight = pChannel;
414 schoenebeck 411 AudioDeviceChannelRight = AudioDeviceChannel;
415     break;
416     default:
417     throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));
418     }
419 iliev 1267
420     bStatusChanged = true;
421 schoenebeck 411 }
422    
423     int EngineChannel::OutputChannel(uint EngineAudioChannel) {
424     switch (EngineAudioChannel) {
425     case 0: // left channel
426     return AudioDeviceChannelLeft;
427     case 1: // right channel
428     return AudioDeviceChannelRight;
429     default:
430     throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));
431     }
432     }
433    
434 schoenebeck 675 void EngineChannel::Connect(MidiInputPort* pMidiPort, midi_chan_t MidiChannel) {
435     if (!pMidiPort || pMidiPort == this->pMidiInputPort) return;
436     DisconnectMidiInputPort();
437     this->pMidiInputPort = pMidiPort;
438     this->midiChannel = MidiChannel;
439     pMidiPort->Connect(this, MidiChannel);
440     }
441    
442     void EngineChannel::DisconnectMidiInputPort() {
443     MidiInputPort* pOldPort = this->pMidiInputPort;
444     this->pMidiInputPort = NULL;
445     if (pOldPort) pOldPort->Disconnect(this);
446     }
447    
448     MidiInputPort* EngineChannel::GetMidiInputPort() {
449     return pMidiInputPort;
450     }
451    
452     midi_chan_t EngineChannel::MidiChannel() {
453     return midiChannel;
454     }
455    
456 schoenebeck 1001 FxSend* EngineChannel::AddFxSend(uint8_t MidiCtrl, String Name) throw (Exception) {
457     if (pEngine) pEngine->DisableAndLock();
458     FxSend* pFxSend = new FxSend(this, MidiCtrl, Name);
459     if (fxSends.empty()) {
460     if (pEngine && pEngine->pAudioOutputDevice) {
461     AudioOutputDevice* pDevice = pEngine->pAudioOutputDevice;
462     // create local render buffers
463     pChannelLeft = new AudioChannel(0, pDevice->MaxSamplesPerCycle());
464     pChannelRight = new AudioChannel(1, pDevice->MaxSamplesPerCycle());
465     } else {
466     // postpone local render buffer creation until audio device is assigned
467     pChannelLeft = NULL;
468     pChannelRight = NULL;
469     }
470     }
471     fxSends.push_back(pFxSend);
472     if (pEngine) pEngine->Enable();
473 iliev 1761 fireFxSendCountChanged(GetSamplerChannel()->Index(), GetFxSendCount());
474 persson 1646
475 schoenebeck 1001 return pFxSend;
476     }
477    
478     FxSend* EngineChannel::GetFxSend(uint FxSendIndex) {
479     return (FxSendIndex < fxSends.size()) ? fxSends[FxSendIndex] : NULL;
480     }
481    
482     uint EngineChannel::GetFxSendCount() {
483     return fxSends.size();
484     }
485    
486     void EngineChannel::RemoveFxSend(FxSend* pFxSend) {
487     if (pEngine) pEngine->DisableAndLock();
488     for (
489     std::vector<FxSend*>::iterator iter = fxSends.begin();
490     iter != fxSends.end(); iter++
491     ) {
492     if (*iter == pFxSend) {
493     delete pFxSend;
494     fxSends.erase(iter);
495     if (fxSends.empty()) {
496     // destroy local render buffers
497     if (pChannelLeft) delete pChannelLeft;
498     if (pChannelRight) delete pChannelRight;
499     // fallback to render directly into AudioOutputDevice's buffers
500     if (pEngine && pEngine->pAudioOutputDevice) {
501     pChannelLeft = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannelLeft);
502     pChannelRight = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannelRight);
503     } else { // we update the pointers later
504     pChannelLeft = NULL;
505     pChannelRight = NULL;
506     }
507     }
508     break;
509     }
510     }
511     if (pEngine) pEngine->Enable();
512 iliev 1761 fireFxSendCountChanged(GetSamplerChannel()->Index(), GetFxSendCount());
513 schoenebeck 1001 }
514    
515 schoenebeck 411 /**
516     * Will be called by the MIDIIn Thread to let the audio thread trigger a new
517 schoenebeck 906 * voice for the given key. This method is meant for real time rendering,
518     * that is an event will immediately be created with the current system
519     * time as time stamp.
520 schoenebeck 411 *
521     * @param Key - MIDI key number of the triggered key
522     * @param Velocity - MIDI velocity value of the triggered key
523     */
524     void EngineChannel::SendNoteOn(uint8_t Key, uint8_t Velocity) {
525     if (pEngine) {
526     Event event = pEngine->pEventGenerator->CreateEvent();
527     event.Type = Event::type_note_on;
528     event.Param.Note.Key = Key;
529     event.Param.Note.Velocity = Velocity;
530 persson 438 event.pEngineChannel = this;
531 schoenebeck 411 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
532 schoenebeck 412 else dmsg(1,("EngineChannel: Input event queue full!"));
533 schoenebeck 1662 // inform connected virtual MIDI devices if any ...
534     // (e.g. virtual MIDI keyboard in instrument editor(s))
535     ArrayList<VirtualMidiDevice*>& devices =
536     const_cast<ArrayList<VirtualMidiDevice*>&>(
537     virtualMidiDevicesReader_MidiThread.Lock()
538     );
539     for (int i = 0; i < devices.size(); i++) {
540     devices[i]->SendNoteOnToDevice(Key, Velocity);
541     }
542     virtualMidiDevicesReader_MidiThread.Unlock();
543 schoenebeck 411 }
544     }
545    
546     /**
547 schoenebeck 906 * Will be called by the MIDIIn Thread to let the audio thread trigger a new
548     * voice for the given key. This method is meant for offline rendering
549     * and / or for cases where the exact position of the event in the current
550     * audio fragment is already known.
551     *
552     * @param Key - MIDI key number of the triggered key
553     * @param Velocity - MIDI velocity value of the triggered key
554     * @param FragmentPos - sample point position in the current audio
555     * fragment to which this event belongs to
556     */
557     void EngineChannel::SendNoteOn(uint8_t Key, uint8_t Velocity, int32_t FragmentPos) {
558     if (FragmentPos < 0) {
559     dmsg(1,("EngineChannel::SendNoteOn(): negative FragmentPos! Seems MIDI driver is buggy!"));
560     }
561     else if (pEngine) {
562     Event event = pEngine->pEventGenerator->CreateEvent(FragmentPos);
563     event.Type = Event::type_note_on;
564     event.Param.Note.Key = Key;
565     event.Param.Note.Velocity = Velocity;
566     event.pEngineChannel = this;
567     if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
568     else dmsg(1,("EngineChannel: Input event queue full!"));
569 schoenebeck 1662 // inform connected virtual MIDI devices if any ...
570     // (e.g. virtual MIDI keyboard in instrument editor(s))
571     ArrayList<VirtualMidiDevice*>& devices =
572     const_cast<ArrayList<VirtualMidiDevice*>&>(
573     virtualMidiDevicesReader_MidiThread.Lock()
574     );
575     for (int i = 0; i < devices.size(); i++) {
576     devices[i]->SendNoteOnToDevice(Key, Velocity);
577     }
578     virtualMidiDevicesReader_MidiThread.Unlock();
579 schoenebeck 906 }
580     }
581    
582     /**
583 schoenebeck 411 * Will be called by the MIDIIn Thread to signal the audio thread to release
584 schoenebeck 906 * voice(s) on the given key. This method is meant for real time rendering,
585     * that is an event will immediately be created with the current system
586     * time as time stamp.
587 schoenebeck 411 *
588     * @param Key - MIDI key number of the released key
589     * @param Velocity - MIDI release velocity value of the released key
590     */
591     void EngineChannel::SendNoteOff(uint8_t Key, uint8_t Velocity) {
592     if (pEngine) {
593     Event event = pEngine->pEventGenerator->CreateEvent();
594     event.Type = Event::type_note_off;
595     event.Param.Note.Key = Key;
596     event.Param.Note.Velocity = Velocity;
597 schoenebeck 412 event.pEngineChannel = this;
598 schoenebeck 411 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
599 schoenebeck 412 else dmsg(1,("EngineChannel: Input event queue full!"));
600 schoenebeck 1662 // inform connected virtual MIDI devices if any ...
601     // (e.g. virtual MIDI keyboard in instrument editor(s))
602     ArrayList<VirtualMidiDevice*>& devices =
603     const_cast<ArrayList<VirtualMidiDevice*>&>(
604     virtualMidiDevicesReader_MidiThread.Lock()
605     );
606     for (int i = 0; i < devices.size(); i++) {
607     devices[i]->SendNoteOffToDevice(Key, Velocity);
608     }
609     virtualMidiDevicesReader_MidiThread.Unlock();
610 schoenebeck 411 }
611     }
612    
613     /**
614 schoenebeck 906 * Will be called by the MIDIIn Thread to signal the audio thread to release
615     * voice(s) on the given key. This method is meant for offline rendering
616     * and / or for cases where the exact position of the event in the current
617     * audio fragment is already known.
618     *
619     * @param Key - MIDI key number of the released key
620     * @param Velocity - MIDI release velocity value of the released key
621     * @param FragmentPos - sample point position in the current audio
622     * fragment to which this event belongs to
623     */
624     void EngineChannel::SendNoteOff(uint8_t Key, uint8_t Velocity, int32_t FragmentPos) {
625     if (FragmentPos < 0) {
626     dmsg(1,("EngineChannel::SendNoteOff(): negative FragmentPos! Seems MIDI driver is buggy!"));
627     }
628     else if (pEngine) {
629     Event event = pEngine->pEventGenerator->CreateEvent(FragmentPos);
630     event.Type = Event::type_note_off;
631     event.Param.Note.Key = Key;
632     event.Param.Note.Velocity = Velocity;
633     event.pEngineChannel = this;
634     if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
635     else dmsg(1,("EngineChannel: Input event queue full!"));
636 schoenebeck 1662 // inform connected virtual MIDI devices if any ...
637     // (e.g. virtual MIDI keyboard in instrument editor(s))
638     ArrayList<VirtualMidiDevice*>& devices =
639     const_cast<ArrayList<VirtualMidiDevice*>&>(
640     virtualMidiDevicesReader_MidiThread.Lock()
641     );
642     for (int i = 0; i < devices.size(); i++) {
643     devices[i]->SendNoteOffToDevice(Key, Velocity);
644     }
645     virtualMidiDevicesReader_MidiThread.Unlock();
646 schoenebeck 906 }
647     }
648    
649     /**
650 schoenebeck 411 * Will be called by the MIDIIn Thread to signal the audio thread to change
651 schoenebeck 906 * the pitch value for all voices. This method is meant for real time
652     * rendering, that is an event will immediately be created with the
653     * current system time as time stamp.
654 schoenebeck 411 *
655     * @param Pitch - MIDI pitch value (-8192 ... +8191)
656     */
657     void EngineChannel::SendPitchbend(int Pitch) {
658 persson 438 if (pEngine) {
659 schoenebeck 411 Event event = pEngine->pEventGenerator->CreateEvent();
660     event.Type = Event::type_pitchbend;
661     event.Param.Pitch.Pitch = Pitch;
662 schoenebeck 412 event.pEngineChannel = this;
663 schoenebeck 411 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
664 schoenebeck 412 else dmsg(1,("EngineChannel: Input event queue full!"));
665 schoenebeck 411 }
666     }
667    
668     /**
669 schoenebeck 906 * Will be called by the MIDIIn Thread to signal the audio thread to change
670     * the pitch value for all voices. This method is meant for offline
671     * rendering and / or for cases where the exact position of the event in
672     * the current audio fragment is already known.
673     *
674     * @param Pitch - MIDI pitch value (-8192 ... +8191)
675     * @param FragmentPos - sample point position in the current audio
676     * fragment to which this event belongs to
677     */
678     void EngineChannel::SendPitchbend(int Pitch, int32_t FragmentPos) {
679     if (FragmentPos < 0) {
680     dmsg(1,("EngineChannel::SendPitchBend(): negative FragmentPos! Seems MIDI driver is buggy!"));
681     }
682     else if (pEngine) {
683     Event event = pEngine->pEventGenerator->CreateEvent(FragmentPos);
684     event.Type = Event::type_pitchbend;
685     event.Param.Pitch.Pitch = Pitch;
686     event.pEngineChannel = this;
687     if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
688     else dmsg(1,("EngineChannel: Input event queue full!"));
689     }
690     }
691    
692     /**
693 schoenebeck 411 * Will be called by the MIDIIn Thread to signal the audio thread that a
694 schoenebeck 906 * continuous controller value has changed. This method is meant for real
695     * time rendering, that is an event will immediately be created with the
696     * current system time as time stamp.
697 schoenebeck 411 *
698     * @param Controller - MIDI controller number of the occured control change
699     * @param Value - value of the control change
700     */
701     void EngineChannel::SendControlChange(uint8_t Controller, uint8_t Value) {
702     if (pEngine) {
703     Event event = pEngine->pEventGenerator->CreateEvent();
704     event.Type = Event::type_control_change;
705     event.Param.CC.Controller = Controller;
706     event.Param.CC.Value = Value;
707 schoenebeck 412 event.pEngineChannel = this;
708 schoenebeck 411 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
709 schoenebeck 412 else dmsg(1,("EngineChannel: Input event queue full!"));
710 schoenebeck 411 }
711     }
712    
713 schoenebeck 906 /**
714     * Will be called by the MIDIIn Thread to signal the audio thread that a
715     * continuous controller value has changed. This method is meant for
716     * offline rendering and / or for cases where the exact position of the
717     * event in the current audio fragment is already known.
718     *
719     * @param Controller - MIDI controller number of the occured control change
720     * @param Value - value of the control change
721     * @param FragmentPos - sample point position in the current audio
722     * fragment to which this event belongs to
723     */
724     void EngineChannel::SendControlChange(uint8_t Controller, uint8_t Value, int32_t FragmentPos) {
725     if (FragmentPos < 0) {
726     dmsg(1,("EngineChannel::SendControlChange(): negative FragmentPos! Seems MIDI driver is buggy!"));
727     }
728     else if (pEngine) {
729     Event event = pEngine->pEventGenerator->CreateEvent(FragmentPos);
730     event.Type = Event::type_control_change;
731     event.Param.CC.Controller = Controller;
732     event.Param.CC.Value = Value;
733     event.pEngineChannel = this;
734     if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
735     else dmsg(1,("EngineChannel: Input event queue full!"));
736     }
737     }
738    
739 persson 1924 /**
740     * Will be called by the MIDIIn Thread to signal that a program
741     * change should be performed. As a program change isn't
742     * real-time safe, the actual change is performed by the disk
743     * thread.
744     *
745     * @param Program - MIDI program change number
746     */
747     void EngineChannel::SendProgramChange(uint8_t Program) {
748     if (pEngine) {
749     pEngine->pDiskThread->OrderProgramChange(Program, this);
750     }
751     }
752    
753 schoenebeck 460 void EngineChannel::ClearEventLists() {
754     pEvents->clear();
755     // empty MIDI key specific event lists
756     {
757     RTList<uint>::Iterator iuiKey = pActiveKeys->first();
758     RTList<uint>::Iterator end = pActiveKeys->end();
759     for(; iuiKey != end; ++iuiKey) {
760     pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key
761     }
762     }
763     }
764    
765 schoenebeck 473 void EngineChannel::ResetControllers() {
766 schoenebeck 670 Pitch = 0;
767     SustainPedal = false;
768 iliev 776 SostenutoPedal = false;
769 schoenebeck 1005 GlobalVolume = 1.0f;
770 schoenebeck 947 MidiVolume = 1.0;
771 schoenebeck 670 GlobalPanLeft = 1.0f;
772     GlobalPanRight = 1.0f;
773 schoenebeck 1723 iLastPanRequest = 64;
774 schoenebeck 1041 GlobalTranspose = 0;
775 schoenebeck 473 // set all MIDI controller values to zero
776 persson 903 memset(ControllerTable, 0x00, 129);
777 schoenebeck 1040 // reset all FX Send levels
778     for (
779     std::vector<FxSend*>::iterator iter = fxSends.begin();
780     iter != fxSends.end(); iter++
781     ) {
782     (*iter)->Reset();
783     }
784 schoenebeck 473 }
785    
786 schoenebeck 460 /**
787     * Copy all events from the engine channel's input event queue buffer to
788     * the internal event list. This will be done at the beginning of each
789     * audio cycle (that is each RenderAudio() call) to distinguish all
790     * events which have to be processed in the current audio cycle. Each
791     * EngineChannel has it's own input event queue for the common channel
792     * specific events (like NoteOn, NoteOff and ControlChange events).
793     * Beside that, the engine also has a input event queue for global
794     * events (usually SysEx messages).
795     *
796     * @param Samples - number of sample points to be processed in the
797     * current audio cycle
798     */
799     void EngineChannel::ImportEvents(uint Samples) {
800 schoenebeck 1659 // import events from pure software MIDI "devices"
801     // (e.g. virtual keyboard in instrument editor)
802     {
803     const int FragmentPos = 0; // randomly chosen, we don't care about jitter for virtual MIDI devices
804     Event event = pEngine->pEventGenerator->CreateEvent(FragmentPos);
805     VirtualMidiDevice::event_t devEvent; // the event format we get from the virtual MIDI device
806     // as we're going to (carefully) write some status to the
807     // synchronized struct, we cast away the const
808     ArrayList<VirtualMidiDevice*>& devices =
809 schoenebeck 1662 const_cast<ArrayList<VirtualMidiDevice*>&>(virtualMidiDevicesReader_AudioThread.Lock());
810 schoenebeck 1659 // iterate through all virtual MIDI devices
811     for (int i = 0; i < devices.size(); i++) {
812     VirtualMidiDevice* pDev = devices[i];
813     // I think we can simply flush the whole FIFO(s), the user shouldn't be so fast ;-)
814     while (pDev->GetMidiEventFromDevice(devEvent)) {
815     event.Type =
816     (devEvent.Type == VirtualMidiDevice::EVENT_TYPE_NOTEON) ?
817     Event::type_note_on : Event::type_note_off;
818     event.Param.Note.Key = devEvent.Key;
819     event.Param.Note.Velocity = devEvent.Velocity;
820     event.pEngineChannel = this;
821     // copy event to internal event list
822     if (pEvents->poolIsEmpty()) {
823     dmsg(1,("Event pool emtpy!\n"));
824     goto exitVirtualDevicesLoop;
825     }
826     *pEvents->allocAppend() = event;
827     }
828     }
829     }
830     exitVirtualDevicesLoop:
831 schoenebeck 1662 virtualMidiDevicesReader_AudioThread.Unlock();
832 schoenebeck 1659
833     // import events from the regular MIDI devices
834 schoenebeck 970 RingBuffer<Event,false>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
835 schoenebeck 460 Event* pEvent;
836     while (true) {
837     // get next event from input event queue
838     if (!(pEvent = eventQueueReader.pop())) break;
839     // if younger event reached, ignore that and all subsequent ones for now
840     if (pEvent->FragmentPos() >= Samples) {
841     eventQueueReader--;
842     dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
843     pEvent->ResetFragmentPos();
844     break;
845     }
846     // copy event to internal event list
847     if (pEvents->poolIsEmpty()) {
848     dmsg(1,("Event pool emtpy!\n"));
849     break;
850     }
851     *pEvents->allocAppend() = *pEvent;
852     }
853     eventQueueReader.free(); // free all copied events from input queue
854     }
855    
856 schoenebeck 1001 void EngineChannel::RemoveAllFxSends() {
857     if (pEngine) pEngine->DisableAndLock();
858     if (!fxSends.empty()) { // free local render buffers
859     if (pChannelLeft) {
860     delete pChannelLeft;
861     if (pEngine && pEngine->pAudioOutputDevice) {
862     // fallback to render directly to the AudioOutputDevice's buffer
863     pChannelLeft = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannelLeft);
864     } else pChannelLeft = NULL;
865     }
866     if (pChannelRight) {
867     delete pChannelRight;
868     if (pEngine && pEngine->pAudioOutputDevice) {
869     // fallback to render directly to the AudioOutputDevice's buffer
870     pChannelRight = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannelRight);
871 persson 1646 } else pChannelRight = NULL;
872 schoenebeck 1001 }
873     }
874     for (int i = 0; i < fxSends.size(); i++) delete fxSends[i];
875     fxSends.clear();
876     if (pEngine) pEngine->Enable();
877     }
878    
879 schoenebeck 1659 void EngineChannel::Connect(VirtualMidiDevice* pDevice) {
880     // double buffer ... double work ...
881     {
882     ArrayList<VirtualMidiDevice*>& devices = virtualMidiDevices.GetConfigForUpdate();
883     devices.add(pDevice);
884     }
885     {
886     ArrayList<VirtualMidiDevice*>& devices = virtualMidiDevices.SwitchConfig();
887     devices.add(pDevice);
888     }
889     }
890    
891     void EngineChannel::Disconnect(VirtualMidiDevice* pDevice) {
892     // double buffer ... double work ...
893     {
894     ArrayList<VirtualMidiDevice*>& devices = virtualMidiDevices.GetConfigForUpdate();
895     devices.remove(pDevice);
896     }
897     {
898     ArrayList<VirtualMidiDevice*>& devices = virtualMidiDevices.SwitchConfig();
899     devices.remove(pDevice);
900     }
901     }
902    
903 schoenebeck 411 float EngineChannel::Volume() {
904     return GlobalVolume;
905     }
906    
907     void EngineChannel::Volume(float f) {
908     GlobalVolume = f;
909 schoenebeck 660 bStatusChanged = true; // status of engine channel has changed, so set notify flag
910 schoenebeck 411 }
911    
912 schoenebeck 1723 float EngineChannel::Pan() {
913     return float(iLastPanRequest - 64) / 64.0f;
914     }
915    
916     void EngineChannel::Pan(float f) {
917     int iMidiPan = int(f * 64.0f) + 64;
918     if (iMidiPan > 127) iMidiPan = 127;
919     else if (iMidiPan < 0) iMidiPan = 0;
920     GlobalPanLeft = Engine::PanCurve[128 - iMidiPan];
921     GlobalPanRight = Engine::PanCurve[iMidiPan];
922     iLastPanRequest = iMidiPan;
923     }
924    
925 schoenebeck 411 uint EngineChannel::Channels() {
926     return 2;
927     }
928    
929     String EngineChannel::InstrumentFileName() {
930     return InstrumentFile;
931     }
932    
933     String EngineChannel::InstrumentName() {
934     return InstrumentIdxName;
935     }
936    
937     int EngineChannel::InstrumentIndex() {
938     return InstrumentIdx;
939     }
940    
941     int EngineChannel::InstrumentStatus() {
942     return InstrumentStat;
943 persson 438 }
944 schoenebeck 411
945 schoenebeck 475 String EngineChannel::EngineName() {
946     return LS_GIG_ENGINE_NAME;
947     }
948 schoenebeck 660
949 iliev 1843 void EngineChannel::ClearDimRegionsInUse() {
950     {
951     instrument_change_command_t& cmd = InstrumentChangeCommand.GetConfigForUpdate();
952     if(cmd.pDimRegionsInUse != NULL) cmd.pDimRegionsInUse->clear();
953     }
954     {
955     instrument_change_command_t& cmd = InstrumentChangeCommand.SwitchConfig();
956     if(cmd.pDimRegionsInUse != NULL) cmd.pDimRegionsInUse->clear();
957     }
958     }
959    
960     void EngineChannel::ResetDimRegionsInUse() {
961     {
962     instrument_change_command_t& cmd = InstrumentChangeCommand.GetConfigForUpdate();
963     if(cmd.pDimRegionsInUse != NULL) {
964     delete cmd.pDimRegionsInUse;
965     cmd.pDimRegionsInUse = new RTList< ::gig::DimensionRegion*>(pEngine->pDimRegionPool[0]);
966     }
967     }
968     {
969     instrument_change_command_t& cmd = InstrumentChangeCommand.SwitchConfig();
970     if(cmd.pDimRegionsInUse != NULL) {
971     delete cmd.pDimRegionsInUse;
972     cmd.pDimRegionsInUse = new RTList< ::gig::DimensionRegion*>(pEngine->pDimRegionPool[1]);
973     }
974     }
975     }
976    
977 schoenebeck 411 }} // namespace LinuxSampler::gig

  ViewVC Help
Powered by ViewVC