/[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 670 - (hide annotations) (download)
Tue Jun 21 18:00:52 2005 UTC (18 years, 9 months ago) by schoenebeck
File size: 20898 byte(s)
* don't reset volume, pan, pitch and MIDI controller values on instrument
  or audio output device change
* send 'CHANNEL_INFO' LSCP event on MIDI program change messages

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

  ViewVC Help
Powered by ViewVC