/[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 460 - (show annotations) (download)
Mon Mar 14 22:35:44 2005 UTC (19 years, 1 month ago) by schoenebeck
File size: 18699 byte(s)
* spawning layered voices now within a loop instead of recursively (fixes
  segmentation fault under heavy voice count load and reduces stress on the
  stack)
* voice stealing operates on all engine channels now
* limit voice stealing to MAX_AUDIO_VOICES thefts per audio fragment cycle
* fixed keygroup handling (layered voices could kill each other)

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

  ViewVC Help
Powered by ViewVC