/[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 473 - (show annotations) (download)
Thu Mar 17 20:13:08 2005 UTC (19 years, 1 month ago) by schoenebeck
File size: 18881 byte(s)
* fixed event leak (events sent to inactive keys were not freed)
* implemented MIDI channel mode messages "All Sound Off", "Reset All
  Controller", "All Notes Off" (fixes bug #5)

1 /***************************************************************************
2 * *
3 * LinuxSampler - modular, streaming capable sampler *
4 * *
5 * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck *
6 * Copyright (C) 2005 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 namespace LinuxSampler { namespace gig {
27
28 EngineChannel::EngineChannel() {
29 pMIDIKeyInfo = new midi_key_info_t[128];
30 pEngine = NULL;
31 pInstrument = NULL;
32 pEvents = NULL; // we allocate when we retrieve the right Engine object
33 pCCEvents = NULL; // we allocate when we retrieve the right Engine object
34 pEventQueue = new RingBuffer<Event>(MAX_EVENTS_PER_FRAGMENT, 0);
35 pActiveKeys = new Pool<uint>(128);
36 for (uint i = 0; i < 128; i++) {
37 pMIDIKeyInfo[i].pActiveVoices = NULL; // we allocate when we retrieve the right Engine object
38 pMIDIKeyInfo[i].KeyPressed = false;
39 pMIDIKeyInfo[i].Active = false;
40 pMIDIKeyInfo[i].ReleaseTrigger = false;
41 pMIDIKeyInfo[i].pEvents = NULL; // we allocate when we retrieve the right Engine object
42 pMIDIKeyInfo[i].VoiceTheftsQueued = 0;
43 pMIDIKeyInfo[i].RoundRobinIndex = 0;
44 }
45 for (uint i = 0; i < Event::destination_count; i++) {
46 pSynthesisEvents[i] = NULL; // we allocate when we retrieve the right Engine object
47 }
48 InstrumentIdx = -1;
49 InstrumentStat = -1;
50 AudioDeviceChannelLeft = -1;
51 AudioDeviceChannelRight = -1;
52 }
53
54 EngineChannel::~EngineChannel() {
55 DisconnectAudioOutputDevice();
56 if (pInstrument) Engine::instruments.HandBack(pInstrument, this);
57 if (pEventQueue) delete pEventQueue;
58 if (pActiveKeys) delete pActiveKeys;
59 if (pMIDIKeyInfo) delete[] pMIDIKeyInfo;
60 }
61
62 /**
63 * This method is not thread safe!
64 */
65 void EngineChannel::ResetInternal() {
66 Pitch = 0;
67 SustainPedal = false;
68 GlobalVolume = 1.0;
69 GlobalPanLeft = 1.0f;
70 GlobalPanRight = 1.0f;
71 CurrentKeyDimension = 0;
72
73 ResetControllers();
74
75 // reset key info
76 for (uint i = 0; i < 128; i++) {
77 if (pMIDIKeyInfo[i].pActiveVoices)
78 pMIDIKeyInfo[i].pActiveVoices->clear();
79 if (pMIDIKeyInfo[i].pEvents)
80 pMIDIKeyInfo[i].pEvents->clear();
81 pMIDIKeyInfo[i].KeyPressed = false;
82 pMIDIKeyInfo[i].Active = false;
83 pMIDIKeyInfo[i].ReleaseTrigger = false;
84 pMIDIKeyInfo[i].itSelf = Pool<uint>::Iterator();
85 pMIDIKeyInfo[i].VoiceTheftsQueued = 0;
86 }
87
88 // reset all key groups
89 std::map<uint,uint*>::iterator iter = ActiveKeyGroups.begin();
90 for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL;
91
92 // free all active keys
93 pActiveKeys->clear();
94
95 // delete all input events
96 pEventQueue->init();
97
98 if (pEngine) pEngine->ResetInternal();
99 }
100
101 LinuxSampler::Engine* EngineChannel::GetEngine() {
102 return pEngine;
103 }
104
105 /**
106 * More or less a workaround to set the instrument name, index and load
107 * status variable to zero percent immediately, that is without blocking
108 * the calling thread. It might be used in future for other preparations
109 * as well though.
110 *
111 * @param FileName - file name of the Gigasampler instrument file
112 * @param Instrument - index of the instrument in the .gig file
113 * @see LoadInstrument()
114 */
115 void EngineChannel::PrepareLoadInstrument(const char* FileName, uint Instrument) {
116 InstrumentFile = FileName;
117 InstrumentIdx = Instrument;
118 InstrumentStat = 0;
119 }
120
121 /**
122 * Load an instrument from a .gig file. PrepareLoadInstrument() has to
123 * be called first to provide the information which instrument to load.
124 * This method will then actually start to load the instrument and block
125 * the calling thread until loading was completed.
126 *
127 * @returns detailed description of the method call result
128 * @see PrepareLoadInstrument()
129 */
130 void EngineChannel::LoadInstrument() {
131
132 if (pEngine) pEngine->DisableAndLock();
133
134 ResetInternal();
135
136 // free old instrument
137 if (pInstrument) {
138 // give old instrument back to instrument manager
139 Engine::instruments.HandBack(pInstrument, this);
140 }
141
142 // delete all key groups
143 ActiveKeyGroups.clear();
144
145 // request gig instrument from instrument manager
146 try {
147 instrument_id_t instrid;
148 instrid.FileName = InstrumentFile;
149 instrid.iInstrument = InstrumentIdx;
150 pInstrument = Engine::instruments.Borrow(instrid, this);
151 if (!pInstrument) {
152 InstrumentStat = -1;
153 dmsg(1,("no instrument loaded!!!\n"));
154 exit(EXIT_FAILURE);
155 }
156 }
157 catch (RIFF::Exception e) {
158 InstrumentStat = -2;
159 String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message;
160 throw LinuxSamplerException(msg);
161 }
162 catch (InstrumentResourceManagerException e) {
163 InstrumentStat = -3;
164 String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message();
165 throw LinuxSamplerException(msg);
166 }
167 catch (...) {
168 InstrumentStat = -4;
169 throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file.");
170 }
171
172 // rebuild ActiveKeyGroups map with key groups of current instrument
173 for (::gig::Region* pRegion = pInstrument->GetFirstRegion(); pRegion; pRegion = pInstrument->GetNextRegion())
174 if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL;
175
176 InstrumentIdxName = pInstrument->pInfo->Name;
177 InstrumentStat = 100;
178
179 // inform audio driver for the need of two channels
180 try {
181 if (pEngine && pEngine->pAudioOutputDevice)
182 pEngine->pAudioOutputDevice->AcquireChannels(2); // gig Engine only stereo
183 }
184 catch (AudioOutputException e) {
185 String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message();
186 throw LinuxSamplerException(msg);
187 }
188
189 if (pEngine) pEngine->Enable();
190 }
191
192 /**
193 * Will be called by the InstrumentResourceManager when the instrument
194 * we are currently using in this engine is going to be updated, so we
195 * can stop playback before that happens.
196 */
197 void EngineChannel::ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) {
198 dmsg(3,("gig::Engine: Received instrument update message.\n"));
199 if (pEngine) pEngine->DisableAndLock();
200 ResetInternal();
201 this->pInstrument = NULL;
202 }
203
204 /**
205 * Will be called by the InstrumentResourceManager when the instrument
206 * update process was completed, so we can continue with playback.
207 */
208 void EngineChannel::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) {
209 this->pInstrument = pNewResource; //TODO: there are couple of engine parameters we should update here as well if the instrument was updated (see LoadInstrument())
210 if (pEngine) pEngine->Enable();
211 }
212
213 void EngineChannel::Connect(AudioOutputDevice* pAudioOut) {
214 if (pEngine) {
215 if (pEngine->pAudioOutputDevice == pAudioOut) return;
216 DisconnectAudioOutputDevice();
217 }
218 pEngine = Engine::AcquireEngine(this, pAudioOut);
219 ResetInternal();
220 pEvents = new RTList<Event>(pEngine->pEventPool);
221 pCCEvents = new RTList<Event>(pEngine->pEventPool);
222 for (uint i = 0; i < Event::destination_count; i++) {
223 pSynthesisEvents[i] = new RTList<Event>(pEngine->pEventPool);
224 }
225 for (uint i = 0; i < 128; i++) {
226 pMIDIKeyInfo[i].pActiveVoices = new RTList<Voice>(pEngine->pVoicePool);
227 pMIDIKeyInfo[i].pEvents = new RTList<Event>(pEngine->pEventPool);
228 }
229 AudioDeviceChannelLeft = 0;
230 AudioDeviceChannelRight = 1;
231 pOutputLeft = pAudioOut->Channel(0)->Buffer();
232 pOutputRight = pAudioOut->Channel(1)->Buffer();
233 }
234
235 void EngineChannel::DisconnectAudioOutputDevice() {
236 if (pEngine) { // if clause to prevent disconnect loops
237 ResetInternal();
238 if (pEvents) {
239 delete pEvents;
240 pEvents = NULL;
241 }
242 if (pCCEvents) {
243 delete pCCEvents;
244 pCCEvents = NULL;
245 }
246 for (uint i = 0; i < 128; i++) {
247 if (pMIDIKeyInfo[i].pActiveVoices) {
248 delete pMIDIKeyInfo[i].pActiveVoices;
249 pMIDIKeyInfo[i].pActiveVoices = NULL;
250 }
251 if (pMIDIKeyInfo[i].pEvents) {
252 delete pMIDIKeyInfo[i].pEvents;
253 pMIDIKeyInfo[i].pEvents = NULL;
254 }
255 }
256 for (uint i = 0; i < Event::destination_count; i++) {
257 if (pSynthesisEvents[i]) {
258 delete pSynthesisEvents[i];
259 pSynthesisEvents[i] = NULL;
260 }
261 }
262 Engine* oldEngine = pEngine;
263 AudioOutputDevice* oldAudioDevice = pEngine->pAudioOutputDevice;
264 pEngine = NULL;
265 Engine::FreeEngine(this, oldAudioDevice);
266 AudioDeviceChannelLeft = -1;
267 AudioDeviceChannelRight = -1;
268 }
269 }
270
271 void EngineChannel::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) {
272 if (!pEngine || !pEngine->pAudioOutputDevice) throw AudioOutputException("No audio output device connected yet.");
273
274 AudioChannel* pChannel = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannel);
275 if (!pChannel) throw AudioOutputException("Invalid audio output device channel " + ToString(AudioDeviceChannel));
276 switch (EngineAudioChannel) {
277 case 0: // left output channel
278 pOutputLeft = pChannel->Buffer();
279 AudioDeviceChannelLeft = AudioDeviceChannel;
280 break;
281 case 1: // right output channel
282 pOutputRight = pChannel->Buffer();
283 AudioDeviceChannelRight = AudioDeviceChannel;
284 break;
285 default:
286 throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));
287 }
288 }
289
290 int EngineChannel::OutputChannel(uint EngineAudioChannel) {
291 switch (EngineAudioChannel) {
292 case 0: // left channel
293 return AudioDeviceChannelLeft;
294 case 1: // right channel
295 return AudioDeviceChannelRight;
296 default:
297 throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));
298 }
299 }
300
301 /**
302 * Will be called by the MIDIIn Thread to let the audio thread trigger a new
303 * voice for the given key.
304 *
305 * @param Key - MIDI key number of the triggered key
306 * @param Velocity - MIDI velocity value of the triggered key
307 */
308 void EngineChannel::SendNoteOn(uint8_t Key, uint8_t Velocity) {
309 if (pEngine) {
310 Event event = pEngine->pEventGenerator->CreateEvent();
311 event.Type = Event::type_note_on;
312 event.Param.Note.Key = Key;
313 event.Param.Note.Velocity = Velocity;
314 event.pEngineChannel = this;
315 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
316 else dmsg(1,("EngineChannel: Input event queue full!"));
317 }
318 }
319
320 /**
321 * Will be called by the MIDIIn Thread to signal the audio thread to release
322 * voice(s) on the given key.
323 *
324 * @param Key - MIDI key number of the released key
325 * @param Velocity - MIDI release velocity value of the released key
326 */
327 void EngineChannel::SendNoteOff(uint8_t Key, uint8_t Velocity) {
328 if (pEngine) {
329 Event event = pEngine->pEventGenerator->CreateEvent();
330 event.Type = Event::type_note_off;
331 event.Param.Note.Key = Key;
332 event.Param.Note.Velocity = Velocity;
333 event.pEngineChannel = this;
334 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
335 else dmsg(1,("EngineChannel: Input event queue full!"));
336 }
337 }
338
339 /**
340 * Will be called by the MIDIIn Thread to signal the audio thread to change
341 * the pitch value for all voices.
342 *
343 * @param Pitch - MIDI pitch value (-8192 ... +8191)
344 */
345 void EngineChannel::SendPitchbend(int Pitch) {
346 if (pEngine) {
347 Event event = pEngine->pEventGenerator->CreateEvent();
348 event.Type = Event::type_pitchbend;
349 event.Param.Pitch.Pitch = Pitch;
350 event.pEngineChannel = this;
351 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
352 else dmsg(1,("EngineChannel: Input event queue full!"));
353 }
354 }
355
356 /**
357 * Will be called by the MIDIIn Thread to signal the audio thread that a
358 * continuous controller value has changed.
359 *
360 * @param Controller - MIDI controller number of the occured control change
361 * @param Value - value of the control change
362 */
363 void EngineChannel::SendControlChange(uint8_t Controller, uint8_t Value) {
364 if (pEngine) {
365 Event event = pEngine->pEventGenerator->CreateEvent();
366 event.Type = Event::type_control_change;
367 event.Param.CC.Controller = Controller;
368 event.Param.CC.Value = Value;
369 event.pEngineChannel = this;
370 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
371 else dmsg(1,("EngineChannel: Input event queue full!"));
372 }
373 }
374
375 void EngineChannel::ClearEventLists() {
376 pEvents->clear();
377 pCCEvents->clear();
378 for (uint i = 0; i < Event::destination_count; i++) {
379 pSynthesisEvents[i]->clear();
380 }
381 // empty MIDI key specific event lists
382 {
383 RTList<uint>::Iterator iuiKey = pActiveKeys->first();
384 RTList<uint>::Iterator end = pActiveKeys->end();
385 for(; iuiKey != end; ++iuiKey) {
386 pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key
387 }
388 }
389 }
390
391 void EngineChannel::ResetControllers() {
392 // set all MIDI controller values to zero
393 memset(ControllerTable, 0x00, 128);
394 }
395
396 /**
397 * Copy all events from the engine channel's input event queue buffer to
398 * the internal event list. This will be done at the beginning of each
399 * audio cycle (that is each RenderAudio() call) to distinguish all
400 * events which have to be processed in the current audio cycle. Each
401 * EngineChannel has it's own input event queue for the common channel
402 * specific events (like NoteOn, NoteOff and ControlChange events).
403 * Beside that, the engine also has a input event queue for global
404 * events (usually SysEx messages).
405 *
406 * @param Samples - number of sample points to be processed in the
407 * current audio cycle
408 */
409 void EngineChannel::ImportEvents(uint Samples) {
410 RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
411 Event* pEvent;
412 while (true) {
413 // get next event from input event queue
414 if (!(pEvent = eventQueueReader.pop())) break;
415 // if younger event reached, ignore that and all subsequent ones for now
416 if (pEvent->FragmentPos() >= Samples) {
417 eventQueueReader--;
418 dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
419 pEvent->ResetFragmentPos();
420 break;
421 }
422 // copy event to internal event list
423 if (pEvents->poolIsEmpty()) {
424 dmsg(1,("Event pool emtpy!\n"));
425 break;
426 }
427 *pEvents->allocAppend() = *pEvent;
428 }
429 eventQueueReader.free(); // free all copied events from input queue
430 }
431
432 float EngineChannel::Volume() {
433 return GlobalVolume;
434 }
435
436 void EngineChannel::Volume(float f) {
437 GlobalVolume = f;
438 }
439
440 uint EngineChannel::Channels() {
441 return 2;
442 }
443
444 String EngineChannel::InstrumentFileName() {
445 return InstrumentFile;
446 }
447
448 String EngineChannel::InstrumentName() {
449 return InstrumentIdxName;
450 }
451
452 int EngineChannel::InstrumentIndex() {
453 return InstrumentIdx;
454 }
455
456 int EngineChannel::InstrumentStatus() {
457 return InstrumentStat;
458 }
459
460 }} // namespace LinuxSampler::gig

  ViewVC Help
Powered by ViewVC