/[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 1662 - (show annotations) (download)
Sun Feb 3 16:21:38 2008 UTC (16 years, 2 months ago) by schoenebeck
File size: 39096 byte(s)
* the promised "cleanup": rewrote virtual MIDI device's notification a bit
  (using now a safe double buffer approach using "SynchronizedConfig"
  instead of the Trylock() approach previously to synchronize the list of
  virtual MIDI devices)
* bumped version to 0.5.1.2cvs

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

  ViewVC Help
Powered by ViewVC