/[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 1843 - (hide annotations) (download)
Sat Feb 21 17:08:18 2009 UTC (15 years, 1 month ago) by iliev
File size: 41629 byte(s)
* fixed orphaned pointers when setting maximum voices limit (bug #118)

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

  ViewVC Help
Powered by ViewVC