/[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 517 - (hide annotations) (download)
Sun May 8 00:26:21 2005 UTC (18 years, 11 months ago) by schoenebeck
File size: 19413 byte(s)
* implemented progress indicator for loading instruments
  (can be polled with "GET CHANNEL INFO", field "INSTRUMENT_STATUS")

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 persson 438 pEventQueue = new RingBuffer<Event>(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     }
53    
54     EngineChannel::~EngineChannel() {
55 schoenebeck 460 DisconnectAudioOutputDevice();
56 schoenebeck 411 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 schoenebeck 424 GlobalPanLeft = 1.0f;
70     GlobalPanRight = 1.0f;
71 schoenebeck 411 CurrentKeyDimension = 0;
72    
73 schoenebeck 473 ResetControllers();
74 schoenebeck 411
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 schoenebeck 473 pMIDIKeyInfo[i].VoiceTheftsQueued = 0;
86 schoenebeck 411 }
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 persson 438
134 schoenebeck 411 ResetInternal();
135 persson 438
136 schoenebeck 411 // 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 schoenebeck 517 * we are currently using on this EngineChannel is going to be updated,
195     * so we can stop playback before that happens.
196 schoenebeck 411 */
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 schoenebeck 517 /**
214     * Will be called by the InstrumentResourceManager on progress changes
215     * while loading or realoading an instrument for this EngineChannel.
216     *
217     * @param fProgress - current progress as value between 0.0 and 1.0
218     */
219     void EngineChannel::OnResourceProgress(float fProgress) {
220     this->InstrumentStat = int(fProgress * 100.0f);
221     dmsg(7,("gig::EngineChannel: progress %d%", InstrumentStat));
222     }
223    
224 schoenebeck 412 void EngineChannel::Connect(AudioOutputDevice* pAudioOut) {
225 schoenebeck 460 if (pEngine) {
226     if (pEngine->pAudioOutputDevice == pAudioOut) return;
227 schoenebeck 412 DisconnectAudioOutputDevice();
228     }
229 schoenebeck 411 pEngine = Engine::AcquireEngine(this, pAudioOut);
230 persson 438 ResetInternal();
231 schoenebeck 460 pEvents = new RTList<Event>(pEngine->pEventPool);
232     pCCEvents = new RTList<Event>(pEngine->pEventPool);
233     for (uint i = 0; i < Event::destination_count; i++) {
234     pSynthesisEvents[i] = new RTList<Event>(pEngine->pEventPool);
235     }
236 schoenebeck 411 for (uint i = 0; i < 128; i++) {
237     pMIDIKeyInfo[i].pActiveVoices = new RTList<Voice>(pEngine->pVoicePool);
238     pMIDIKeyInfo[i].pEvents = new RTList<Event>(pEngine->pEventPool);
239     }
240     AudioDeviceChannelLeft = 0;
241     AudioDeviceChannelRight = 1;
242     pOutputLeft = pAudioOut->Channel(0)->Buffer();
243     pOutputRight = pAudioOut->Channel(1)->Buffer();
244     }
245    
246     void EngineChannel::DisconnectAudioOutputDevice() {
247     if (pEngine) { // if clause to prevent disconnect loops
248     ResetInternal();
249 schoenebeck 460 if (pEvents) {
250     delete pEvents;
251     pEvents = NULL;
252     }
253     if (pCCEvents) {
254     delete pCCEvents;
255     pCCEvents = NULL;
256     }
257 schoenebeck 411 for (uint i = 0; i < 128; i++) {
258 schoenebeck 420 if (pMIDIKeyInfo[i].pActiveVoices) {
259     delete pMIDIKeyInfo[i].pActiveVoices;
260     pMIDIKeyInfo[i].pActiveVoices = NULL;
261     }
262     if (pMIDIKeyInfo[i].pEvents) {
263     delete pMIDIKeyInfo[i].pEvents;
264     pMIDIKeyInfo[i].pEvents = NULL;
265     }
266 schoenebeck 411 }
267 schoenebeck 460 for (uint i = 0; i < Event::destination_count; i++) {
268     if (pSynthesisEvents[i]) {
269     delete pSynthesisEvents[i];
270     pSynthesisEvents[i] = NULL;
271     }
272     }
273 schoenebeck 411 Engine* oldEngine = pEngine;
274     AudioOutputDevice* oldAudioDevice = pEngine->pAudioOutputDevice;
275     pEngine = NULL;
276     Engine::FreeEngine(this, oldAudioDevice);
277     AudioDeviceChannelLeft = -1;
278 persson 438 AudioDeviceChannelRight = -1;
279 schoenebeck 411 }
280     }
281    
282     void EngineChannel::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) {
283     if (!pEngine || !pEngine->pAudioOutputDevice) throw AudioOutputException("No audio output device connected yet.");
284 persson 438
285 schoenebeck 411 AudioChannel* pChannel = pEngine->pAudioOutputDevice->Channel(AudioDeviceChannel);
286     if (!pChannel) throw AudioOutputException("Invalid audio output device channel " + ToString(AudioDeviceChannel));
287     switch (EngineAudioChannel) {
288     case 0: // left output channel
289     pOutputLeft = pChannel->Buffer();
290     AudioDeviceChannelLeft = AudioDeviceChannel;
291     break;
292     case 1: // right output channel
293     pOutputRight = pChannel->Buffer();
294     AudioDeviceChannelRight = AudioDeviceChannel;
295     break;
296     default:
297     throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));
298     }
299     }
300    
301     int EngineChannel::OutputChannel(uint EngineAudioChannel) {
302     switch (EngineAudioChannel) {
303     case 0: // left channel
304     return AudioDeviceChannelLeft;
305     case 1: // right channel
306     return AudioDeviceChannelRight;
307     default:
308     throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel));
309     }
310     }
311    
312     /**
313     * Will be called by the MIDIIn Thread to let the audio thread trigger a new
314     * voice for the given key.
315     *
316     * @param Key - MIDI key number of the triggered key
317     * @param Velocity - MIDI velocity value of the triggered key
318     */
319     void EngineChannel::SendNoteOn(uint8_t Key, uint8_t Velocity) {
320     if (pEngine) {
321     Event event = pEngine->pEventGenerator->CreateEvent();
322     event.Type = Event::type_note_on;
323     event.Param.Note.Key = Key;
324     event.Param.Note.Velocity = Velocity;
325 persson 438 event.pEngineChannel = this;
326 schoenebeck 411 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
327 schoenebeck 412 else dmsg(1,("EngineChannel: Input event queue full!"));
328 schoenebeck 411 }
329     }
330    
331     /**
332     * Will be called by the MIDIIn Thread to signal the audio thread to release
333     * voice(s) on the given key.
334     *
335     * @param Key - MIDI key number of the released key
336     * @param Velocity - MIDI release velocity value of the released key
337     */
338     void EngineChannel::SendNoteOff(uint8_t Key, uint8_t Velocity) {
339     if (pEngine) {
340     Event event = pEngine->pEventGenerator->CreateEvent();
341     event.Type = Event::type_note_off;
342     event.Param.Note.Key = Key;
343     event.Param.Note.Velocity = Velocity;
344 schoenebeck 412 event.pEngineChannel = this;
345 schoenebeck 411 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
346 schoenebeck 412 else dmsg(1,("EngineChannel: Input event queue full!"));
347 schoenebeck 411 }
348     }
349    
350     /**
351     * Will be called by the MIDIIn Thread to signal the audio thread to change
352     * the pitch value for all voices.
353     *
354     * @param Pitch - MIDI pitch value (-8192 ... +8191)
355     */
356     void EngineChannel::SendPitchbend(int Pitch) {
357 persson 438 if (pEngine) {
358 schoenebeck 411 Event event = pEngine->pEventGenerator->CreateEvent();
359     event.Type = Event::type_pitchbend;
360     event.Param.Pitch.Pitch = Pitch;
361 schoenebeck 412 event.pEngineChannel = this;
362 schoenebeck 411 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
363 schoenebeck 412 else dmsg(1,("EngineChannel: Input event queue full!"));
364 schoenebeck 411 }
365     }
366    
367     /**
368     * Will be called by the MIDIIn Thread to signal the audio thread that a
369     * continuous controller value has changed.
370     *
371     * @param Controller - MIDI controller number of the occured control change
372     * @param Value - value of the control change
373     */
374     void EngineChannel::SendControlChange(uint8_t Controller, uint8_t Value) {
375     if (pEngine) {
376     Event event = pEngine->pEventGenerator->CreateEvent();
377     event.Type = Event::type_control_change;
378     event.Param.CC.Controller = Controller;
379     event.Param.CC.Value = Value;
380 schoenebeck 412 event.pEngineChannel = this;
381 schoenebeck 411 if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event);
382 schoenebeck 412 else dmsg(1,("EngineChannel: Input event queue full!"));
383 schoenebeck 411 }
384     }
385    
386 schoenebeck 460 void EngineChannel::ClearEventLists() {
387     pEvents->clear();
388     pCCEvents->clear();
389     for (uint i = 0; i < Event::destination_count; i++) {
390     pSynthesisEvents[i]->clear();
391     }
392     // empty MIDI key specific event lists
393     {
394     RTList<uint>::Iterator iuiKey = pActiveKeys->first();
395     RTList<uint>::Iterator end = pActiveKeys->end();
396     for(; iuiKey != end; ++iuiKey) {
397     pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key
398     }
399     }
400     }
401    
402 schoenebeck 473 void EngineChannel::ResetControllers() {
403     // set all MIDI controller values to zero
404     memset(ControllerTable, 0x00, 128);
405     }
406    
407 schoenebeck 460 /**
408     * Copy all events from the engine channel's input event queue buffer to
409     * the internal event list. This will be done at the beginning of each
410     * audio cycle (that is each RenderAudio() call) to distinguish all
411     * events which have to be processed in the current audio cycle. Each
412     * EngineChannel has it's own input event queue for the common channel
413     * specific events (like NoteOn, NoteOff and ControlChange events).
414     * Beside that, the engine also has a input event queue for global
415     * events (usually SysEx messages).
416     *
417     * @param Samples - number of sample points to be processed in the
418     * current audio cycle
419     */
420     void EngineChannel::ImportEvents(uint Samples) {
421     RingBuffer<Event>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
422     Event* pEvent;
423     while (true) {
424     // get next event from input event queue
425     if (!(pEvent = eventQueueReader.pop())) break;
426     // if younger event reached, ignore that and all subsequent ones for now
427     if (pEvent->FragmentPos() >= Samples) {
428     eventQueueReader--;
429     dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
430     pEvent->ResetFragmentPos();
431     break;
432     }
433     // copy event to internal event list
434     if (pEvents->poolIsEmpty()) {
435     dmsg(1,("Event pool emtpy!\n"));
436     break;
437     }
438     *pEvents->allocAppend() = *pEvent;
439     }
440     eventQueueReader.free(); // free all copied events from input queue
441     }
442    
443 schoenebeck 411 float EngineChannel::Volume() {
444     return GlobalVolume;
445     }
446    
447     void EngineChannel::Volume(float f) {
448     GlobalVolume = f;
449     }
450    
451     uint EngineChannel::Channels() {
452     return 2;
453     }
454    
455     String EngineChannel::InstrumentFileName() {
456     return InstrumentFile;
457     }
458    
459     String EngineChannel::InstrumentName() {
460     return InstrumentIdxName;
461     }
462    
463     int EngineChannel::InstrumentIndex() {
464     return InstrumentIdx;
465     }
466    
467     int EngineChannel::InstrumentStatus() {
468     return InstrumentStat;
469 persson 438 }
470 schoenebeck 411
471 schoenebeck 475 String EngineChannel::EngineName() {
472     return LS_GIG_ENGINE_NAME;
473     }
474    
475 schoenebeck 411 }} // namespace LinuxSampler::gig

  ViewVC Help
Powered by ViewVC