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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1844 - (show annotations) (download)
Mon Feb 23 18:29:50 2009 UTC (15 years, 1 month ago) by persson
File size: 40821 byte(s)
* fixed crash when removing channel with active voices (#116)

1 /***************************************************************************
2 * *
3 * LinuxSampler - modular, streaming capable sampler *
4 * *
5 * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck *
6 * Copyright (C) 2005 - 2009 Christian Schoenebeck *
7 * *
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 #include "../../common/global_private.h"
27 #include "../../Sampler.h"
28
29 namespace LinuxSampler { namespace gig {
30
31 EngineChannel::EngineChannel() :
32 InstrumentChangeCommandReader(InstrumentChangeCommand),
33 virtualMidiDevicesReader_AudioThread(virtualMidiDevices),
34 virtualMidiDevicesReader_MidiThread(virtualMidiDevices)
35 {
36 pMIDIKeyInfo = new midi_key_info_t[128];
37 pEngine = NULL;
38 pInstrument = NULL;
39 pEvents = NULL; // we allocate when we retrieve the right Engine object
40 pEventQueue = new RingBuffer<Event,false>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);
41 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 pMIDIKeyInfo[i].VoiceTheftsQueued = 0;
49 pMIDIKeyInfo[i].RoundRobinIndex = 0;
50 }
51 InstrumentIdx = -1;
52 InstrumentStat = -1;
53 pChannelLeft = NULL;
54 pChannelRight = NULL;
55 AudioDeviceChannelLeft = -1;
56 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 // 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 }
79
80 EngineChannel::~EngineChannel() {
81 DisconnectAudioOutputDevice();
82
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 if (pEventQueue) delete pEventQueue;
92 if (pActiveKeys) delete pActiveKeys;
93 if (pMIDIKeyInfo) delete[] pMIDIKeyInfo;
94 RemoveAllFxSends();
95 }
96
97 /**
98 * 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 * 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 * TODO: This "poll method" is just a lazy solution and might be
108 * replaced in future.
109 * @param bNewStatus - (optional, default: false) sets the new status flag
110 * @returns true if engine channel status has changed since last
111 * StatusChanged() call
112 */
113 bool EngineChannel::StatusChanged(bool bNewStatus) {
114 bool b = bStatusChanged;
115 bStatusChanged = bNewStatus;
116 return b;
117 }
118
119 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 /**
130 * 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 pMIDIKeyInfo[i].VoiceTheftsQueued = 0;
146 }
147 SoloKey = -1; // no solo key active yet
148 PortamentoPos = -1.0f; // no portamento active yet
149
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
162 // status of engine channel has changed, so set notify flag
163 bStatusChanged = true;
164 }
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 // 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 }
203 cmd.pDimRegionsInUse->clear();
204
205 // delete all key groups
206 ActiveKeyGroups.clear();
207
208 // request gig instrument from instrument manager
209 ::gig::Instrument* newInstrument;
210 try {
211 InstrumentManager::instrument_id_t instrid;
212 instrid.FileName = InstrumentFile;
213 instrid.Index = InstrumentIdx;
214 newInstrument = Engine::instruments.Borrow(instrid, this);
215 if (!newInstrument) {
216 throw InstrumentManagerException("resource was not created");
217 }
218 }
219 catch (RIFF::Exception e) {
220 InstrumentStat = -2;
221 StatusChanged(true);
222 String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;
223 throw Exception(msg);
224 }
225 catch (InstrumentManagerException e) {
226 InstrumentStat = -3;
227 StatusChanged(true);
228 String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();
229 throw Exception(msg);
230 }
231 catch (...) {
232 InstrumentStat = -4;
233 StatusChanged(true);
234 throw Exception("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");
235 }
236
237 // rebuild ActiveKeyGroups map with key groups of current instrument
238 for (::gig::Region* pRegion = newInstrument->GetFirstRegion(); pRegion; pRegion = newInstrument->GetNextRegion())
239 if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL;
240
241 InstrumentIdxName = newInstrument->pInfo->Name;
242 InstrumentStat = 100;
243
244 ChangeInstrument(newInstrument);
245
246 StatusChanged(true);
247 }
248
249
250 /**
251 * 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 * Will be called by the InstrumentResourceManager when the instrument
268 * we are currently using on this EngineChannel is going to be updated,
269 * so we can stop playback before that happens.
270 */
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 bStatusChanged = true; // status of engine has changed, so set notify flag
286 }
287
288 /**
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 bStatusChanged = true; // status of engine has changed, so set notify flag
298 }
299
300 void EngineChannel::Connect(AudioOutputDevice* pAudioOut) {
301 if (pEngine) {
302 if (pEngine->pAudioOutputDevice == pAudioOut) return;
303 DisconnectAudioOutputDevice();
304 }
305 pEngine = Engine::AcquireEngine(this, pAudioOut);
306 ResetInternal();
307 pEvents = new RTList<Event>(pEngine->pEventPool);
308
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 for (uint i = 0; i < 128; i++) {
325 pMIDIKeyInfo[i].pActiveVoices = new RTList<Voice>(pEngine->pVoicePool);
326 pMIDIKeyInfo[i].pEvents = new RTList<Event>(pEngine->pEventPool);
327 }
328 AudioDeviceChannelLeft = 0;
329 AudioDeviceChannelRight = 1;
330 if (fxSends.empty()) { // render directly into the AudioDevice's output buffers
331 pChannelLeft = pAudioOut->Channel(AudioDeviceChannelLeft);
332 pChannelRight = pAudioOut->Channel(AudioDeviceChannelRight);
333 } else { // use local buffers for rendering and copy later
334 // ensure the local buffers have the correct size
335 if (pChannelLeft) delete pChannelLeft;
336 if (pChannelRight) delete pChannelRight;
337 pChannelLeft = new AudioChannel(0, pAudioOut->MaxSamplesPerCycle());
338 pChannelRight = new AudioChannel(1, pAudioOut->MaxSamplesPerCycle());
339 }
340 if (pEngine->EngineDisabled.GetUnsafe()) pEngine->Enable();
341 MidiInputPort::AddSysexListener(pEngine);
342 }
343
344 void EngineChannel::DisconnectAudioOutputDevice() {
345 if (pEngine) { // if clause to prevent disconnect loops
346
347 ResetInternal();
348
349 // delete the structures used for instrument change
350 RTList< ::gig::DimensionRegion*>* d = InstrumentChangeCommand.GetConfigForUpdate().pDimRegionsInUse;
351 if (d) delete d;
352 EngineChannel::instrument_change_command_t& cmd = InstrumentChangeCommand.SwitchConfig();
353 d = cmd.pDimRegionsInUse;
354 if (d) delete d;
355
356 if (cmd.pInstrument) {
357 // release the currently loaded instrument
358 Engine::instruments.HandBack(cmd.pInstrument, this);
359 }
360
361 if (pEvents) {
362 delete pEvents;
363 pEvents = NULL;
364 }
365 for (uint i = 0; i < 128; i++) {
366 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 }
375 AudioOutputDevice* oldAudioDevice = pEngine->pAudioOutputDevice;
376 pEngine = NULL;
377 Engine::FreeEngine(this, oldAudioDevice);
378 AudioDeviceChannelLeft = -1;
379 AudioDeviceChannelRight = -1;
380 if (!fxSends.empty()) { // free the local rendering buffers
381 if (pChannelLeft) delete pChannelLeft;
382 if (pChannelRight) delete pChannelRight;
383 }
384 pChannelLeft = NULL;
385 pChannelRight = NULL;
386 }
387 }
388
389 AudioOutputDevice* EngineChannel::GetAudioOutputDevice() {
390 return (pEngine) ? pEngine->pAudioOutputDevice : NULL;
391 }
392
393 void EngineChannel::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) {
394 if (!pEngine || !pEngine->pAudioOutputDevice) throw AudioOutputException("No audio output device connected yet.");
395
396 AudioChannel* pChannel = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannel);
397 if (!pChannel) throw AudioOutputException("Invalid audio output device channel " + ToString(AudioDeviceChannel));
398 switch (EngineAudioChannel) {
399 case 0: // left output channel
400 if (fxSends.empty()) pChannelLeft = pChannel;
401 AudioDeviceChannelLeft = AudioDeviceChannel;
402 break;
403 case 1: // right output channel
404 if (fxSends.empty()) pChannelRight = pChannel;
405 AudioDeviceChannelRight = AudioDeviceChannel;
406 break;
407 default:
408 throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));
409 }
410
411 bStatusChanged = true;
412 }
413
414 int EngineChannel::OutputChannel(uint EngineAudioChannel) {
415 switch (EngineAudioChannel) {
416 case 0: // left channel
417 return AudioDeviceChannelLeft;
418 case 1: // right channel
419 return AudioDeviceChannelRight;
420 default:
421 throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));
422 }
423 }
424
425 void EngineChannel::Connect(MidiInputPort* pMidiPort, midi_chan_t MidiChannel) {
426 if (!pMidiPort || pMidiPort == this->pMidiInputPort) return;
427 DisconnectMidiInputPort();
428 this->pMidiInputPort = pMidiPort;
429 this->midiChannel = MidiChannel;
430 pMidiPort->Connect(this, MidiChannel);
431 }
432
433 void EngineChannel::DisconnectMidiInputPort() {
434 MidiInputPort* pOldPort = this->pMidiInputPort;
435 this->pMidiInputPort = NULL;
436 if (pOldPort) pOldPort->Disconnect(this);
437 }
438
439 MidiInputPort* EngineChannel::GetMidiInputPort() {
440 return pMidiInputPort;
441 }
442
443 midi_chan_t EngineChannel::MidiChannel() {
444 return midiChannel;
445 }
446
447 FxSend* EngineChannel::AddFxSend(uint8_t MidiCtrl, String Name) throw (Exception) {
448 if (pEngine) pEngine->DisableAndLock();
449 FxSend* pFxSend = new FxSend(this, MidiCtrl, Name);
450 if (fxSends.empty()) {
451 if (pEngine && pEngine->pAudioOutputDevice) {
452 AudioOutputDevice* pDevice = pEngine->pAudioOutputDevice;
453 // create local render buffers
454 pChannelLeft = new AudioChannel(0, pDevice->MaxSamplesPerCycle());
455 pChannelRight = new AudioChannel(1, pDevice->MaxSamplesPerCycle());
456 } else {
457 // postpone local render buffer creation until audio device is assigned
458 pChannelLeft = NULL;
459 pChannelRight = NULL;
460 }
461 }
462 fxSends.push_back(pFxSend);
463 if (pEngine) pEngine->Enable();
464 fireFxSendCountChanged(GetSamplerChannel()->Index(), GetFxSendCount());
465
466 return pFxSend;
467 }
468
469 FxSend* EngineChannel::GetFxSend(uint FxSendIndex) {
470 return (FxSendIndex < fxSends.size()) ? fxSends[FxSendIndex] : NULL;
471 }
472
473 uint EngineChannel::GetFxSendCount() {
474 return fxSends.size();
475 }
476
477 void EngineChannel::RemoveFxSend(FxSend* pFxSend) {
478 if (pEngine) pEngine->DisableAndLock();
479 for (
480 std::vector<FxSend*>::iterator iter = fxSends.begin();
481 iter != fxSends.end(); iter++
482 ) {
483 if (*iter == pFxSend) {
484 delete pFxSend;
485 fxSends.erase(iter);
486 if (fxSends.empty()) {
487 // destroy local render buffers
488 if (pChannelLeft) delete pChannelLeft;
489 if (pChannelRight) delete pChannelRight;
490 // fallback to render directly into AudioOutputDevice's buffers
491 if (pEngine && pEngine->pAudioOutputDevice) {
492 pChannelLeft = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannelLeft);
493 pChannelRight = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannelRight);
494 } else { // we update the pointers later
495 pChannelLeft = NULL;
496 pChannelRight = NULL;
497 }
498 }
499 break;
500 }
501 }
502 if (pEngine) pEngine->Enable();
503 fireFxSendCountChanged(GetSamplerChannel()->Index(), GetFxSendCount());
504 }
505
506 /**
507 * Will be called by the MIDIIn Thread to let the audio thread trigger a new
508 * voice for the given key. This method is meant for real time rendering,
509 * that is an event will immediately be created with the current system
510 * time as time stamp.
511 *
512 * @param Key - MIDI key number of the triggered key
513 * @param Velocity - MIDI velocity value of the triggered key
514 */
515 void EngineChannel::SendNoteOn(uint8_t Key, uint8_t Velocity) {
516 if (pEngine) {
517 Event event = pEngine->pEventGenerator->CreateEvent();
518 event.Type = Event::type_note_on;
519 event.Param.Note.Key = Key;
520 event.Param.Note.Velocity = Velocity;
521 event.pEngineChannel = this;
522 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
523 else dmsg(1,("EngineChannel: Input event queue full!"));
524 // inform connected virtual MIDI devices if any ...
525 // (e.g. virtual MIDI keyboard in instrument editor(s))
526 ArrayList<VirtualMidiDevice*>& devices =
527 const_cast<ArrayList<VirtualMidiDevice*>&>(
528 virtualMidiDevicesReader_MidiThread.Lock()
529 );
530 for (int i = 0; i < devices.size(); i++) {
531 devices[i]->SendNoteOnToDevice(Key, Velocity);
532 }
533 virtualMidiDevicesReader_MidiThread.Unlock();
534 }
535 }
536
537 /**
538 * Will be called by the MIDIIn Thread to let the audio thread trigger a new
539 * voice for the given key. This method is meant for offline rendering
540 * and / or for cases where the exact position of the event in the current
541 * audio fragment is already known.
542 *
543 * @param Key - MIDI key number of the triggered key
544 * @param Velocity - MIDI velocity value of the triggered key
545 * @param FragmentPos - sample point position in the current audio
546 * fragment to which this event belongs to
547 */
548 void EngineChannel::SendNoteOn(uint8_t Key, uint8_t Velocity, int32_t FragmentPos) {
549 if (FragmentPos < 0) {
550 dmsg(1,("EngineChannel::SendNoteOn(): negative FragmentPos! Seems MIDI driver is buggy!"));
551 }
552 else if (pEngine) {
553 Event event = pEngine->pEventGenerator->CreateEvent(FragmentPos);
554 event.Type = Event::type_note_on;
555 event.Param.Note.Key = Key;
556 event.Param.Note.Velocity = Velocity;
557 event.pEngineChannel = this;
558 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
559 else dmsg(1,("EngineChannel: Input event queue full!"));
560 // inform connected virtual MIDI devices if any ...
561 // (e.g. virtual MIDI keyboard in instrument editor(s))
562 ArrayList<VirtualMidiDevice*>& devices =
563 const_cast<ArrayList<VirtualMidiDevice*>&>(
564 virtualMidiDevicesReader_MidiThread.Lock()
565 );
566 for (int i = 0; i < devices.size(); i++) {
567 devices[i]->SendNoteOnToDevice(Key, Velocity);
568 }
569 virtualMidiDevicesReader_MidiThread.Unlock();
570 }
571 }
572
573 /**
574 * Will be called by the MIDIIn Thread to signal the audio thread to release
575 * voice(s) on the given key. This method is meant for real time rendering,
576 * that is an event will immediately be created with the current system
577 * time as time stamp.
578 *
579 * @param Key - MIDI key number of the released key
580 * @param Velocity - MIDI release velocity value of the released key
581 */
582 void EngineChannel::SendNoteOff(uint8_t Key, uint8_t Velocity) {
583 if (pEngine) {
584 Event event = pEngine->pEventGenerator->CreateEvent();
585 event.Type = Event::type_note_off;
586 event.Param.Note.Key = Key;
587 event.Param.Note.Velocity = Velocity;
588 event.pEngineChannel = this;
589 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
590 else dmsg(1,("EngineChannel: Input event queue full!"));
591 // inform connected virtual MIDI devices if any ...
592 // (e.g. virtual MIDI keyboard in instrument editor(s))
593 ArrayList<VirtualMidiDevice*>& devices =
594 const_cast<ArrayList<VirtualMidiDevice*>&>(
595 virtualMidiDevicesReader_MidiThread.Lock()
596 );
597 for (int i = 0; i < devices.size(); i++) {
598 devices[i]->SendNoteOffToDevice(Key, Velocity);
599 }
600 virtualMidiDevicesReader_MidiThread.Unlock();
601 }
602 }
603
604 /**
605 * Will be called by the MIDIIn Thread to signal the audio thread to release
606 * voice(s) on the given key. This method is meant for offline rendering
607 * and / or for cases where the exact position of the event in the current
608 * audio fragment is already known.
609 *
610 * @param Key - MIDI key number of the released key
611 * @param Velocity - MIDI release velocity value of the released key
612 * @param FragmentPos - sample point position in the current audio
613 * fragment to which this event belongs to
614 */
615 void EngineChannel::SendNoteOff(uint8_t Key, uint8_t Velocity, int32_t FragmentPos) {
616 if (FragmentPos < 0) {
617 dmsg(1,("EngineChannel::SendNoteOff(): negative FragmentPos! Seems MIDI driver is buggy!"));
618 }
619 else if (pEngine) {
620 Event event = pEngine->pEventGenerator->CreateEvent(FragmentPos);
621 event.Type = Event::type_note_off;
622 event.Param.Note.Key = Key;
623 event.Param.Note.Velocity = Velocity;
624 event.pEngineChannel = this;
625 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
626 else dmsg(1,("EngineChannel: Input event queue full!"));
627 // inform connected virtual MIDI devices if any ...
628 // (e.g. virtual MIDI keyboard in instrument editor(s))
629 ArrayList<VirtualMidiDevice*>& devices =
630 const_cast<ArrayList<VirtualMidiDevice*>&>(
631 virtualMidiDevicesReader_MidiThread.Lock()
632 );
633 for (int i = 0; i < devices.size(); i++) {
634 devices[i]->SendNoteOffToDevice(Key, Velocity);
635 }
636 virtualMidiDevicesReader_MidiThread.Unlock();
637 }
638 }
639
640 /**
641 * Will be called by the MIDIIn Thread to signal the audio thread to change
642 * the pitch value for all voices. This method is meant for real time
643 * rendering, that is an event will immediately be created with the
644 * current system time as time stamp.
645 *
646 * @param Pitch - MIDI pitch value (-8192 ... +8191)
647 */
648 void EngineChannel::SendPitchbend(int Pitch) {
649 if (pEngine) {
650 Event event = pEngine->pEventGenerator->CreateEvent();
651 event.Type = Event::type_pitchbend;
652 event.Param.Pitch.Pitch = Pitch;
653 event.pEngineChannel = this;
654 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
655 else dmsg(1,("EngineChannel: Input event queue full!"));
656 }
657 }
658
659 /**
660 * Will be called by the MIDIIn Thread to signal the audio thread to change
661 * the pitch value for all voices. This method is meant for offline
662 * rendering and / or for cases where the exact position of the event in
663 * the current audio fragment is already known.
664 *
665 * @param Pitch - MIDI pitch value (-8192 ... +8191)
666 * @param FragmentPos - sample point position in the current audio
667 * fragment to which this event belongs to
668 */
669 void EngineChannel::SendPitchbend(int Pitch, int32_t FragmentPos) {
670 if (FragmentPos < 0) {
671 dmsg(1,("EngineChannel::SendPitchBend(): negative FragmentPos! Seems MIDI driver is buggy!"));
672 }
673 else if (pEngine) {
674 Event event = pEngine->pEventGenerator->CreateEvent(FragmentPos);
675 event.Type = Event::type_pitchbend;
676 event.Param.Pitch.Pitch = Pitch;
677 event.pEngineChannel = this;
678 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
679 else dmsg(1,("EngineChannel: Input event queue full!"));
680 }
681 }
682
683 /**
684 * Will be called by the MIDIIn Thread to signal the audio thread that a
685 * continuous controller value has changed. This method is meant for real
686 * time rendering, that is an event will immediately be created with the
687 * current system time as time stamp.
688 *
689 * @param Controller - MIDI controller number of the occured control change
690 * @param Value - value of the control change
691 */
692 void EngineChannel::SendControlChange(uint8_t Controller, uint8_t Value) {
693 if (pEngine) {
694 Event event = pEngine->pEventGenerator->CreateEvent();
695 event.Type = Event::type_control_change;
696 event.Param.CC.Controller = Controller;
697 event.Param.CC.Value = Value;
698 event.pEngineChannel = this;
699 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
700 else dmsg(1,("EngineChannel: Input event queue full!"));
701 }
702 }
703
704 /**
705 * Will be called by the MIDIIn Thread to signal the audio thread that a
706 * continuous controller value has changed. This method is meant for
707 * offline rendering and / or for cases where the exact position of the
708 * event in the current audio fragment is already known.
709 *
710 * @param Controller - MIDI controller number of the occured control change
711 * @param Value - value of the control change
712 * @param FragmentPos - sample point position in the current audio
713 * fragment to which this event belongs to
714 */
715 void EngineChannel::SendControlChange(uint8_t Controller, uint8_t Value, int32_t FragmentPos) {
716 if (FragmentPos < 0) {
717 dmsg(1,("EngineChannel::SendControlChange(): negative FragmentPos! Seems MIDI driver is buggy!"));
718 }
719 else if (pEngine) {
720 Event event = pEngine->pEventGenerator->CreateEvent(FragmentPos);
721 event.Type = Event::type_control_change;
722 event.Param.CC.Controller = Controller;
723 event.Param.CC.Value = Value;
724 event.pEngineChannel = this;
725 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
726 else dmsg(1,("EngineChannel: Input event queue full!"));
727 }
728 }
729
730 void EngineChannel::ClearEventLists() {
731 pEvents->clear();
732 // empty MIDI key specific event lists
733 {
734 RTList<uint>::Iterator iuiKey = pActiveKeys->first();
735 RTList<uint>::Iterator end = pActiveKeys->end();
736 for(; iuiKey != end; ++iuiKey) {
737 pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key
738 }
739 }
740 }
741
742 void EngineChannel::ResetControllers() {
743 Pitch = 0;
744 SustainPedal = false;
745 SostenutoPedal = false;
746 GlobalVolume = 1.0f;
747 MidiVolume = 1.0;
748 GlobalPanLeft = 1.0f;
749 GlobalPanRight = 1.0f;
750 iLastPanRequest = 64;
751 GlobalTranspose = 0;
752 // set all MIDI controller values to zero
753 memset(ControllerTable, 0x00, 129);
754 // reset all FX Send levels
755 for (
756 std::vector<FxSend*>::iterator iter = fxSends.begin();
757 iter != fxSends.end(); iter++
758 ) {
759 (*iter)->Reset();
760 }
761 }
762
763 /**
764 * Copy all events from the engine channel's input event queue buffer to
765 * the internal event list. This will be done at the beginning of each
766 * audio cycle (that is each RenderAudio() call) to distinguish all
767 * events which have to be processed in the current audio cycle. Each
768 * EngineChannel has it's own input event queue for the common channel
769 * specific events (like NoteOn, NoteOff and ControlChange events).
770 * Beside that, the engine also has a input event queue for global
771 * events (usually SysEx messages).
772 *
773 * @param Samples - number of sample points to be processed in the
774 * current audio cycle
775 */
776 void EngineChannel::ImportEvents(uint Samples) {
777 // import events from pure software MIDI "devices"
778 // (e.g. virtual keyboard in instrument editor)
779 {
780 const int FragmentPos = 0; // randomly chosen, we don't care about jitter for virtual MIDI devices
781 Event event = pEngine->pEventGenerator->CreateEvent(FragmentPos);
782 VirtualMidiDevice::event_t devEvent; // the event format we get from the virtual MIDI device
783 // as we're going to (carefully) write some status to the
784 // synchronized struct, we cast away the const
785 ArrayList<VirtualMidiDevice*>& devices =
786 const_cast<ArrayList<VirtualMidiDevice*>&>(virtualMidiDevicesReader_AudioThread.Lock());
787 // iterate through all virtual MIDI devices
788 for (int i = 0; i < devices.size(); i++) {
789 VirtualMidiDevice* pDev = devices[i];
790 // I think we can simply flush the whole FIFO(s), the user shouldn't be so fast ;-)
791 while (pDev->GetMidiEventFromDevice(devEvent)) {
792 event.Type =
793 (devEvent.Type == VirtualMidiDevice::EVENT_TYPE_NOTEON) ?
794 Event::type_note_on : Event::type_note_off;
795 event.Param.Note.Key = devEvent.Key;
796 event.Param.Note.Velocity = devEvent.Velocity;
797 event.pEngineChannel = this;
798 // copy event to internal event list
799 if (pEvents->poolIsEmpty()) {
800 dmsg(1,("Event pool emtpy!\n"));
801 goto exitVirtualDevicesLoop;
802 }
803 *pEvents->allocAppend() = event;
804 }
805 }
806 }
807 exitVirtualDevicesLoop:
808 virtualMidiDevicesReader_AudioThread.Unlock();
809
810 // import events from the regular MIDI devices
811 RingBuffer<Event,false>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
812 Event* pEvent;
813 while (true) {
814 // get next event from input event queue
815 if (!(pEvent = eventQueueReader.pop())) break;
816 // if younger event reached, ignore that and all subsequent ones for now
817 if (pEvent->FragmentPos() >= Samples) {
818 eventQueueReader--;
819 dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
820 pEvent->ResetFragmentPos();
821 break;
822 }
823 // copy event to internal event list
824 if (pEvents->poolIsEmpty()) {
825 dmsg(1,("Event pool emtpy!\n"));
826 break;
827 }
828 *pEvents->allocAppend() = *pEvent;
829 }
830 eventQueueReader.free(); // free all copied events from input queue
831 }
832
833 void EngineChannel::RemoveAllFxSends() {
834 if (pEngine) pEngine->DisableAndLock();
835 if (!fxSends.empty()) { // free local render buffers
836 if (pChannelLeft) {
837 delete pChannelLeft;
838 if (pEngine && pEngine->pAudioOutputDevice) {
839 // fallback to render directly to the AudioOutputDevice's buffer
840 pChannelLeft = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannelLeft);
841 } else pChannelLeft = NULL;
842 }
843 if (pChannelRight) {
844 delete pChannelRight;
845 if (pEngine && pEngine->pAudioOutputDevice) {
846 // fallback to render directly to the AudioOutputDevice's buffer
847 pChannelRight = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannelRight);
848 } else pChannelRight = NULL;
849 }
850 }
851 for (int i = 0; i < fxSends.size(); i++) delete fxSends[i];
852 fxSends.clear();
853 if (pEngine) pEngine->Enable();
854 }
855
856 void EngineChannel::Connect(VirtualMidiDevice* pDevice) {
857 // double buffer ... double work ...
858 {
859 ArrayList<VirtualMidiDevice*>& devices = virtualMidiDevices.GetConfigForUpdate();
860 devices.add(pDevice);
861 }
862 {
863 ArrayList<VirtualMidiDevice*>& devices = virtualMidiDevices.SwitchConfig();
864 devices.add(pDevice);
865 }
866 }
867
868 void EngineChannel::Disconnect(VirtualMidiDevice* pDevice) {
869 // double buffer ... double work ...
870 {
871 ArrayList<VirtualMidiDevice*>& devices = virtualMidiDevices.GetConfigForUpdate();
872 devices.remove(pDevice);
873 }
874 {
875 ArrayList<VirtualMidiDevice*>& devices = virtualMidiDevices.SwitchConfig();
876 devices.remove(pDevice);
877 }
878 }
879
880 float EngineChannel::Volume() {
881 return GlobalVolume;
882 }
883
884 void EngineChannel::Volume(float f) {
885 GlobalVolume = f;
886 bStatusChanged = true; // status of engine channel has changed, so set notify flag
887 }
888
889 float EngineChannel::Pan() {
890 return float(iLastPanRequest - 64) / 64.0f;
891 }
892
893 void EngineChannel::Pan(float f) {
894 int iMidiPan = int(f * 64.0f) + 64;
895 if (iMidiPan > 127) iMidiPan = 127;
896 else if (iMidiPan < 0) iMidiPan = 0;
897 GlobalPanLeft = Engine::PanCurve[128 - iMidiPan];
898 GlobalPanRight = Engine::PanCurve[iMidiPan];
899 iLastPanRequest = iMidiPan;
900 }
901
902 uint EngineChannel::Channels() {
903 return 2;
904 }
905
906 String EngineChannel::InstrumentFileName() {
907 return InstrumentFile;
908 }
909
910 String EngineChannel::InstrumentName() {
911 return InstrumentIdxName;
912 }
913
914 int EngineChannel::InstrumentIndex() {
915 return InstrumentIdx;
916 }
917
918 int EngineChannel::InstrumentStatus() {
919 return InstrumentStat;
920 }
921
922 String EngineChannel::EngineName() {
923 return LS_GIG_ENGINE_NAME;
924 }
925
926 void EngineChannel::ClearDimRegionsInUse() {
927 {
928 instrument_change_command_t& cmd = InstrumentChangeCommand.GetConfigForUpdate();
929 if(cmd.pDimRegionsInUse != NULL) cmd.pDimRegionsInUse->clear();
930 }
931 {
932 instrument_change_command_t& cmd = InstrumentChangeCommand.SwitchConfig();
933 if(cmd.pDimRegionsInUse != NULL) cmd.pDimRegionsInUse->clear();
934 }
935 }
936
937 void EngineChannel::ResetDimRegionsInUse() {
938 {
939 instrument_change_command_t& cmd = InstrumentChangeCommand.GetConfigForUpdate();
940 if(cmd.pDimRegionsInUse != NULL) {
941 delete cmd.pDimRegionsInUse;
942 cmd.pDimRegionsInUse = new RTList< ::gig::DimensionRegion*>(pEngine->pDimRegionPool[0]);
943 }
944 }
945 {
946 instrument_change_command_t& cmd = InstrumentChangeCommand.SwitchConfig();
947 if(cmd.pDimRegionsInUse != NULL) {
948 delete cmd.pDimRegionsInUse;
949 cmd.pDimRegionsInUse = new RTList< ::gig::DimensionRegion*>(pEngine->pDimRegionPool[1]);
950 }
951 }
952 }
953
954 }} // namespace LinuxSampler::gig

  ViewVC Help
Powered by ViewVC