/[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 1826 - (hide annotations) (download)
Sat Jan 24 14:32:35 2009 UTC (15 years, 2 months ago) by iliev
File size: 39927 byte(s)
* fixed a crash which occurs when removing a sampler channel with
  instrument loading in progress (bug #113)

1 schoenebeck 411 /***************************************************************************
2     * *
3     * LinuxSampler - modular, streaming capable sampler *
4     * *
5     * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck *
6 persson 1646 * Copyright (C) 2005 - 2008 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 schoenebeck 411 }
64    
65     EngineChannel::~EngineChannel() {
66 schoenebeck 460 DisconnectAudioOutputDevice();
67 iliev 1826
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 schoenebeck 411 if (pEventQueue) delete pEventQueue;
77     if (pActiveKeys) delete pActiveKeys;
78     if (pMIDIKeyInfo) delete[] pMIDIKeyInfo;
79 schoenebeck 1001 RemoveAllFxSends();
80 schoenebeck 411 }
81    
82     /**
83 schoenebeck 660 * 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 schoenebeck 670 * 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 schoenebeck 660 * TODO: This "poll method" is just a lazy solution and might be
93     * replaced in future.
94 schoenebeck 670 * @param bNewStatus - (optional, default: false) sets the new status flag
95 schoenebeck 660 * @returns true if engine channel status has changed since last
96     * StatusChanged() call
97     */
98 schoenebeck 670 bool EngineChannel::StatusChanged(bool bNewStatus) {
99 schoenebeck 660 bool b = bStatusChanged;
100 schoenebeck 670 bStatusChanged = bNewStatus;
101 schoenebeck 660 return b;
102     }
103    
104 schoenebeck 670 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 schoenebeck 660 /**
115 schoenebeck 411 * This method is not thread safe!
116     */
117     void EngineChannel::ResetInternal() {
118     CurrentKeyDimension = 0;
119    
120     // reset key info
121     for (uint i = 0; i < 128; i++) {
122     if (pMIDIKeyInfo[i].pActiveVoices)
123     pMIDIKeyInfo[i].pActiveVoices->clear();
124     if (pMIDIKeyInfo[i].pEvents)
125     pMIDIKeyInfo[i].pEvents->clear();
126     pMIDIKeyInfo[i].KeyPressed = false;
127     pMIDIKeyInfo[i].Active = false;
128     pMIDIKeyInfo[i].ReleaseTrigger = false;
129     pMIDIKeyInfo[i].itSelf = Pool<uint>::Iterator();
130 schoenebeck 473 pMIDIKeyInfo[i].VoiceTheftsQueued = 0;
131 schoenebeck 411 }
132 schoenebeck 829 SoloKey = -1; // no solo key active yet
133     PortamentoPos = -1.0f; // no portamento active yet
134 schoenebeck 411
135     // reset all key groups
136     std::map<uint,uint*>::iterator iter = ActiveKeyGroups.begin();
137     for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;
138    
139     // free all active keys
140     pActiveKeys->clear();
141    
142     // delete all input events
143     pEventQueue->init();
144    
145     if (pEngine) pEngine->ResetInternal();
146 schoenebeck 660
147     // status of engine channel has changed, so set notify flag
148     bStatusChanged = true;
149 schoenebeck 411 }
150    
151     LinuxSampler::Engine* EngineChannel::GetEngine() {
152     return pEngine;
153     }
154    
155     /**
156     * More or less a workaround to set the instrument name, index and load
157     * status variable to zero percent immediately, that is without blocking
158     * the calling thread. It might be used in future for other preparations
159     * as well though.
160     *
161     * @param FileName - file name of the Gigasampler instrument file
162     * @param Instrument - index of the instrument in the .gig file
163     * @see LoadInstrument()
164     */
165     void EngineChannel::PrepareLoadInstrument(const char* FileName, uint Instrument) {
166     InstrumentFile = FileName;
167     InstrumentIdx = Instrument;
168     InstrumentStat = 0;
169     }
170    
171     /**
172     * Load an instrument from a .gig file. PrepareLoadInstrument() has to
173     * be called first to provide the information which instrument to load.
174     * This method will then actually start to load the instrument and block
175     * the calling thread until loading was completed.
176     *
177     * @see PrepareLoadInstrument()
178     */
179     void EngineChannel::LoadInstrument() {
180 persson 1646 // make sure we don't trigger any new notes with an old
181     // instrument
182     instrument_change_command_t& cmd = ChangeInstrument(0);
183     if (cmd.pInstrument) {
184     // give old instrument back to instrument manager, but
185     // keep the dimension regions and samples that are in use
186     Engine::instruments.HandBackInstrument(cmd.pInstrument, this, cmd.pDimRegionsInUse);
187 schoenebeck 411 }
188 persson 1646 cmd.pDimRegionsInUse->clear();
189 schoenebeck 411
190     // delete all key groups
191     ActiveKeyGroups.clear();
192    
193     // request gig instrument from instrument manager
194 persson 1038 ::gig::Instrument* newInstrument;
195 schoenebeck 411 try {
196 schoenebeck 947 InstrumentManager::instrument_id_t instrid;
197     instrid.FileName = InstrumentFile;
198     instrid.Index = InstrumentIdx;
199 persson 1038 newInstrument = Engine::instruments.Borrow(instrid, this);
200     if (!newInstrument) {
201 schoenebeck 1212 throw InstrumentManagerException("resource was not created");
202 schoenebeck 411 }
203     }
204     catch (RIFF::Exception e) {
205     InstrumentStat = -2;
206 iliev 1309 StatusChanged(true);
207 schoenebeck 411 String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;
208 schoenebeck 880 throw Exception(msg);
209 schoenebeck 411 }
210 schoenebeck 1212 catch (InstrumentManagerException e) {
211 schoenebeck 411 InstrumentStat = -3;
212 iliev 1309 StatusChanged(true);
213 schoenebeck 411 String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();
214 schoenebeck 880 throw Exception(msg);
215 schoenebeck 411 }
216     catch (...) {
217     InstrumentStat = -4;
218 iliev 1309 StatusChanged(true);
219 schoenebeck 880 throw Exception("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");
220 schoenebeck 411 }
221    
222     // rebuild ActiveKeyGroups map with key groups of current instrument
223 persson 1038 for (::gig::Region* pRegion = newInstrument->GetFirstRegion(); pRegion; pRegion = newInstrument->GetNextRegion())
224 schoenebeck 411 if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL;
225    
226 persson 1038 InstrumentIdxName = newInstrument->pInfo->Name;
227 schoenebeck 411 InstrumentStat = 100;
228    
229 persson 1646 ChangeInstrument(newInstrument);
230    
231 iliev 1298 StatusChanged(true);
232 schoenebeck 411 }
233    
234 persson 1646
235 schoenebeck 411 /**
236 persson 1646 * 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     /**
252 schoenebeck 411 * Will be called by the InstrumentResourceManager when the instrument
253 schoenebeck 517 * we are currently using on this EngineChannel is going to be updated,
254     * so we can stop playback before that happens.
255 schoenebeck 411 */
256     void EngineChannel::ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {
257     dmsg(3,("gig::Engine: Received instrument update message.\n"));
258     if (pEngine) pEngine->DisableAndLock();
259     ResetInternal();
260     this->pInstrument = NULL;
261     }
262    
263     /**
264     * Will be called by the InstrumentResourceManager when the instrument
265     * update process was completed, so we can continue with playback.
266     */
267     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())
269     if (pEngine) pEngine->Enable();
270 schoenebeck 660 bStatusChanged = true; // status of engine has changed, so set notify flag
271 schoenebeck 411 }
272    
273 schoenebeck 517 /**
274     * Will be called by the InstrumentResourceManager on progress changes
275     * while loading or realoading an instrument for this EngineChannel.
276     *
277     * @param fProgress - current progress as value between 0.0 and 1.0
278     */
279     void EngineChannel::OnResourceProgress(float fProgress) {
280     this->InstrumentStat = int(fProgress * 100.0f);
281     dmsg(7,("gig::EngineChannel: progress %d%", InstrumentStat));
282 schoenebeck 660 bStatusChanged = true; // status of engine has changed, so set notify flag
283 schoenebeck 517 }
284    
285 schoenebeck 412 void EngineChannel::Connect(AudioOutputDevice* pAudioOut) {
286 schoenebeck 460 if (pEngine) {
287     if (pEngine->pAudioOutputDevice == pAudioOut) return;
288 schoenebeck 412 DisconnectAudioOutputDevice();
289     }
290 schoenebeck 411 pEngine = Engine::AcquireEngine(this, pAudioOut);
291 persson 438 ResetInternal();
292 schoenebeck 738 pEvents = new RTList<Event>(pEngine->pEventPool);
293 persson 1646
294     // reset the instrument change command struct (need to be done
295     // 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 schoenebeck 411 for (uint i = 0; i < 128; i++) {
310     pMIDIKeyInfo[i].pActiveVoices = new RTList<Voice>(pEngine->pVoicePool);
311     pMIDIKeyInfo[i].pEvents = new RTList<Event>(pEngine->pEventPool);
312     }
313     AudioDeviceChannelLeft = 0;
314     AudioDeviceChannelRight = 1;
315 schoenebeck 1001 if (fxSends.empty()) { // render directly into the AudioDevice's output buffers
316     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 persson 1039 if (pEngine->EngineDisabled.GetUnsafe()) pEngine->Enable();
326 persson 846 MidiInputPort::AddSysexListener(pEngine);
327 schoenebeck 411 }
328    
329     void EngineChannel::DisconnectAudioOutputDevice() {
330     if (pEngine) { // if clause to prevent disconnect loops
331 persson 1646
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 iliev 1761
343 persson 1646 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 schoenebeck 411 ResetInternal();
361 schoenebeck 460 if (pEvents) {
362     delete pEvents;
363     pEvents = NULL;
364     }
365 schoenebeck 411 for (uint i = 0; i < 128; i++) {
366 schoenebeck 420 if (pMIDIKeyInfo[i].pActiveVoices) {
367     delete pMIDIKeyInfo[i].pActiveVoices;
368     pMIDIKeyInfo[i].pActiveVoices = NULL;
369     }
370     if (pMIDIKeyInfo[i].pEvents) {
371     delete pMIDIKeyInfo[i].pEvents;
372     pMIDIKeyInfo[i].pEvents = NULL;
373     }
374 schoenebeck 411 }
375     Engine* oldEngine = pEngine;
376     AudioOutputDevice* oldAudioDevice = pEngine->pAudioOutputDevice;
377     pEngine = NULL;
378     Engine::FreeEngine(this, oldAudioDevice);
379     AudioDeviceChannelLeft = -1;
380 persson 438 AudioDeviceChannelRight = -1;
381 schoenebeck 1001 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 schoenebeck 411 }
388     }
389    
390 schoenebeck 1001 AudioOutputDevice* EngineChannel::GetAudioOutputDevice() {
391     return (pEngine) ? pEngine->pAudioOutputDevice : NULL;
392     }
393    
394 schoenebeck 411 void EngineChannel::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) {
395     if (!pEngine || !pEngine->pAudioOutputDevice) throw AudioOutputException("No audio output device connected yet.");
396 persson 438
397 schoenebeck 411 AudioChannel* pChannel = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannel);
398     if (!pChannel) throw AudioOutputException("Invalid audio output device channel " + ToString(AudioDeviceChannel));
399     switch (EngineAudioChannel) {
400     case 0: // left output channel
401 schoenebeck 1001 if (fxSends.empty()) pChannelLeft = pChannel;
402 schoenebeck 411 AudioDeviceChannelLeft = AudioDeviceChannel;
403     break;
404     case 1: // right output channel
405 schoenebeck 1001 if (fxSends.empty()) pChannelRight = pChannel;
406 schoenebeck 411 AudioDeviceChannelRight = AudioDeviceChannel;
407     break;
408     default:
409     throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));
410     }
411 iliev 1267
412     bStatusChanged = true;
413 schoenebeck 411 }
414    
415     int EngineChannel::OutputChannel(uint EngineAudioChannel) {
416     switch (EngineAudioChannel) {
417     case 0: // left channel
418     return AudioDeviceChannelLeft;
419     case 1: // right channel
420     return AudioDeviceChannelRight;
421     default:
422     throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));
423     }
424     }
425    
426 schoenebeck 675 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 schoenebeck 1001 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 iliev 1761 fireFxSendCountChanged(GetSamplerChannel()->Index(), GetFxSendCount());
466 persson 1646
467 schoenebeck 1001 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 iliev 1761 fireFxSendCountChanged(GetSamplerChannel()->Index(), GetFxSendCount());
505 schoenebeck 1001 }
506    
507 schoenebeck 411 /**
508     * Will be called by the MIDIIn Thread to let the audio thread trigger a new
509 schoenebeck 906 * 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 schoenebeck 411 *
513     * @param Key - MIDI key number of the triggered key
514     * @param Velocity - MIDI velocity value of the triggered key
515     */
516     void EngineChannel::SendNoteOn(uint8_t Key, uint8_t Velocity) {
517     if (pEngine) {
518     Event event = pEngine->pEventGenerator->CreateEvent();
519     event.Type = Event::type_note_on;
520     event.Param.Note.Key = Key;
521     event.Param.Note.Velocity = Velocity;
522 persson 438 event.pEngineChannel = this;
523 schoenebeck 411 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
524 schoenebeck 412 else dmsg(1,("EngineChannel: Input event queue full!"));
525 schoenebeck 1662 // 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 schoenebeck 411 }
536     }
537    
538     /**
539 schoenebeck 906 * 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 schoenebeck 1662 // 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 schoenebeck 906 }
572     }
573    
574     /**
575 schoenebeck 411 * Will be called by the MIDIIn Thread to signal the audio thread to release
576 schoenebeck 906 * 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 schoenebeck 411 *
580     * @param Key - MIDI key number of the released key
581     * @param Velocity - MIDI release velocity value of the released key
582     */
583     void EngineChannel::SendNoteOff(uint8_t Key, uint8_t Velocity) {
584     if (pEngine) {
585     Event event = pEngine->pEventGenerator->CreateEvent();
586     event.Type = Event::type_note_off;
587     event.Param.Note.Key = Key;
588     event.Param.Note.Velocity = Velocity;
589 schoenebeck 412 event.pEngineChannel = this;
590 schoenebeck 411 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
591 schoenebeck 412 else dmsg(1,("EngineChannel: Input event queue full!"));
592 schoenebeck 1662 // 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 schoenebeck 411 }
603     }
604    
605     /**
606 schoenebeck 906 * 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 schoenebeck 1662 // 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 schoenebeck 906 }
639     }
640    
641     /**
642 schoenebeck 411 * Will be called by the MIDIIn Thread to signal the audio thread to change
643 schoenebeck 906 * 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 schoenebeck 411 *
647     * @param Pitch - MIDI pitch value (-8192 ... +8191)
648     */
649     void EngineChannel::SendPitchbend(int Pitch) {
650 persson 438 if (pEngine) {
651 schoenebeck 411 Event event = pEngine->pEventGenerator->CreateEvent();
652     event.Type = Event::type_pitchbend;
653     event.Param.Pitch.Pitch = Pitch;
654 schoenebeck 412 event.pEngineChannel = this;
655 schoenebeck 411 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
656 schoenebeck 412 else dmsg(1,("EngineChannel: Input event queue full!"));
657 schoenebeck 411 }
658     }
659    
660     /**
661 schoenebeck 906 * 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 schoenebeck 411 * Will be called by the MIDIIn Thread to signal the audio thread that a
686 schoenebeck 906 * 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 schoenebeck 411 *
690     * @param Controller - MIDI controller number of the occured control change
691     * @param Value - value of the control change
692     */
693     void EngineChannel::SendControlChange(uint8_t Controller, uint8_t Value) {
694     if (pEngine) {
695     Event event = pEngine->pEventGenerator->CreateEvent();
696     event.Type = Event::type_control_change;
697     event.Param.CC.Controller = Controller;
698     event.Param.CC.Value = Value;
699 schoenebeck 412 event.pEngineChannel = this;
700 schoenebeck 411 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
701 schoenebeck 412 else dmsg(1,("EngineChannel: Input event queue full!"));
702 schoenebeck 411 }
703     }
704    
705 schoenebeck 906 /**
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 schoenebeck 460 void EngineChannel::ClearEventLists() {
732     pEvents->clear();
733     // empty MIDI key specific event lists
734     {
735     RTList<uint>::Iterator iuiKey = pActiveKeys->first();
736     RTList<uint>::Iterator end = pActiveKeys->end();
737     for(; iuiKey != end; ++iuiKey) {
738     pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key
739     }
740     }
741     }
742    
743 schoenebeck 473 void EngineChannel::ResetControllers() {
744 schoenebeck 670 Pitch = 0;
745     SustainPedal = false;
746 iliev 776 SostenutoPedal = false;
747 schoenebeck 1005 GlobalVolume = 1.0f;
748 schoenebeck 947 MidiVolume = 1.0;
749 schoenebeck 670 GlobalPanLeft = 1.0f;
750     GlobalPanRight = 1.0f;
751 schoenebeck 1723 iLastPanRequest = 64;
752 schoenebeck 1041 GlobalTranspose = 0;
753 schoenebeck 473 // set all MIDI controller values to zero
754 persson 903 memset(ControllerTable, 0x00, 129);
755 schoenebeck 1040 // 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 schoenebeck 473 }
763    
764 schoenebeck 460 /**
765     * Copy all events from the engine channel's input event queue buffer to
766     * the internal event list. This will be done at the beginning of each
767     * audio cycle (that is each RenderAudio() call) to distinguish all
768     * events which have to be processed in the current audio cycle. Each
769     * EngineChannel has it's own input event queue for the common channel
770     * specific events (like NoteOn, NoteOff and ControlChange events).
771     * Beside that, the engine also has a input event queue for global
772     * events (usually SysEx messages).
773     *
774     * @param Samples - number of sample points to be processed in the
775     * current audio cycle
776     */
777     void EngineChannel::ImportEvents(uint Samples) {
778 schoenebeck 1659 // 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 schoenebeck 1662 const_cast<ArrayList<VirtualMidiDevice*>&>(virtualMidiDevicesReader_AudioThread.Lock());
788 schoenebeck 1659 // 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 schoenebeck 1662 virtualMidiDevicesReader_AudioThread.Unlock();
810 schoenebeck 1659
811     // import events from the regular MIDI devices
812 schoenebeck 970 RingBuffer<Event,false>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
813 schoenebeck 460 Event* pEvent;
814     while (true) {
815     // get next event from input event queue
816     if (!(pEvent = eventQueueReader.pop())) break;
817     // if younger event reached, ignore that and all subsequent ones for now
818     if (pEvent->FragmentPos() >= Samples) {
819     eventQueueReader--;
820     dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
821     pEvent->ResetFragmentPos();
822     break;
823     }
824     // copy event to internal event list
825     if (pEvents->poolIsEmpty()) {
826     dmsg(1,("Event pool emtpy!\n"));
827     break;
828     }
829     *pEvents->allocAppend() = *pEvent;
830     }
831     eventQueueReader.free(); // free all copied events from input queue
832     }
833    
834 schoenebeck 1001 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 persson 1646 } else pChannelRight = NULL;
850 schoenebeck 1001 }
851     }
852     for (int i = 0; i < fxSends.size(); i++) delete fxSends[i];
853     fxSends.clear();
854     if (pEngine) pEngine->Enable();
855     }
856    
857 schoenebeck 1659 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 schoenebeck 411 float EngineChannel::Volume() {
882     return GlobalVolume;
883     }
884    
885     void EngineChannel::Volume(float f) {
886     GlobalVolume = f;
887 schoenebeck 660 bStatusChanged = true; // status of engine channel has changed, so set notify flag
888 schoenebeck 411 }
889    
890 schoenebeck 1723 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 schoenebeck 411 uint EngineChannel::Channels() {
904     return 2;
905     }
906    
907     String EngineChannel::InstrumentFileName() {
908     return InstrumentFile;
909     }
910    
911     String EngineChannel::InstrumentName() {
912     return InstrumentIdxName;
913     }
914    
915     int EngineChannel::InstrumentIndex() {
916     return InstrumentIdx;
917     }
918    
919     int EngineChannel::InstrumentStatus() {
920     return InstrumentStat;
921 persson 438 }
922 schoenebeck 411
923 schoenebeck 475 String EngineChannel::EngineName() {
924     return LS_GIG_ENGINE_NAME;
925     }
926 schoenebeck 660
927 schoenebeck 411 }} // namespace LinuxSampler::gig

  ViewVC Help
Powered by ViewVC