/[svn]/linuxsampler/trunk/src/engines/AbstractEngine.cpp
ViewVC logotype

Contents of /linuxsampler/trunk/src/engines/AbstractEngine.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2296 - (show annotations) (download)
Thu Dec 8 20:03:47 2011 UTC (12 years, 3 months ago) by iliev
File size: 30315 byte(s)
* fixed crash when trying to create an effect instance with controls
  which min and/or max values depend on the sample rate
* experimental support for per voice equalization (work in progress)
* sfz engine: implemented opcodes eq1_freq, eq2_freq, eq3_freq,
  eq1_freqccN, eq2_freqccN, eq3_freqccN, eq1_bw, eq2_bw, eq3_bw,
  eq1_bwccN, eq2_bwccN, eq3_bwccN, eq1_gain, eq2_gain, eq3_gain,
  eq1_gainccN, eq2_gainccN, eq3_gainccN

1 /***************************************************************************
2 * *
3 * LinuxSampler - modular, streaming capable sampler *
4 * *
5 * Copyright (C) 2003,2004 by Benno Senoner and Christian Schoenebeck *
6 * Copyright (C) 2005-2008 Christian Schoenebeck *
7 * Copyright (C) 2009-2010 Christian Schoenebeck and Grigor Iliev *
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 * This program is distributed in the hope that it will be useful, *
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
17 * GNU General Public License for more details. *
18 * *
19 * You should have received a copy of the GNU General Public License *
20 * along with this program; if not, write to the Free Software *
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
22 * MA 02111-1307 USA *
23 ***************************************************************************/
24
25 #include "AbstractEngine.h"
26 #include "AbstractEngineChannel.h"
27 #include "EngineFactory.h"
28 #include "../common/global_private.h"
29 #include "../effects/EffectFactory.h"
30
31 namespace LinuxSampler {
32
33 //InstrumentResourceManager Engine::instruments;
34
35 std::map<AbstractEngine::Format, std::map<AudioOutputDevice*,AbstractEngine*> > AbstractEngine::engines;
36
37 /**
38 * Get an AbstractEngine object for the given AbstractEngineChannel and the
39 * given AudioOutputDevice. All engine channels which are connected to
40 * the same audio output device will use the same engine instance. This
41 * method will be called by an EngineChannel whenever it's
42 * connecting to an audio output device.
43 *
44 * @param pChannel - engine channel which acquires an engine object
45 * @param pDevice - the audio output device \a pChannel is connected to
46 */
47 AbstractEngine* AbstractEngine::AcquireEngine(AbstractEngineChannel* pChannel, AudioOutputDevice* pDevice) {
48 AbstractEngine* pEngine = NULL;
49 // check if there's already an engine for the given audio output device
50 std::map<AbstractEngine::Format, std::map<AudioOutputDevice*,AbstractEngine*> >::iterator it;
51 it = engines.find(pChannel->GetEngineFormat());
52 if (it != engines.end() && (*it).second.count(pDevice)) {
53 dmsg(4,("Using existing Engine.\n"));
54 pEngine = (*it).second[pDevice];
55
56 // Disable the engine while the new engine channel is
57 // added and initialized. The engine will be enabled again
58 // in EngineChannel::Connect.
59 pEngine->DisableAndLock();
60 } else { // create a new engine (and disk thread) instance for the given audio output device
61 dmsg(4,("Creating new Engine.\n"));
62 pEngine = (AbstractEngine*) EngineFactory::Create(pChannel->EngineName());
63 pEngine->Connect(pDevice);
64 engines[pChannel->GetEngineFormat()][pDevice] = pEngine;
65 }
66 // register engine channel to the engine instance
67 pEngine->engineChannels.add(pChannel);
68 // remember index in the ArrayList
69 pChannel->iEngineIndexSelf = pEngine->engineChannels.size() - 1;
70 dmsg(4,("This Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));
71 return pEngine;
72 }
73
74 AbstractEngine::AbstractEngine() {
75 pAudioOutputDevice = NULL;
76 pEventGenerator = NULL;
77 pSysexBuffer = new RingBuffer<uint8_t,false>(CONFIG_SYSEX_BUFFER_SIZE, 0);
78 pEventQueue = new RingBuffer<Event,false>(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0);
79 pEventPool = new Pool<Event>(CONFIG_MAX_EVENTS_PER_FRAGMENT);
80 pGlobalEvents = new RTList<Event>(pEventPool);
81 FrameTime = 0;
82 RandomSeed = 0;
83 pDedicatedVoiceChannelLeft = pDedicatedVoiceChannelRight = NULL;
84 pEq = NULL;
85 }
86
87 AbstractEngine::~AbstractEngine() {
88 if (pEventQueue) delete pEventQueue;
89 if (pEventPool) delete pEventPool;
90 if (pEventGenerator) delete pEventGenerator;
91 if (pGlobalEvents) delete pGlobalEvents;
92 if (pSysexBuffer) delete pSysexBuffer;
93 if (pDedicatedVoiceChannelLeft) delete pDedicatedVoiceChannelLeft;
94 if (pDedicatedVoiceChannelRight) delete pDedicatedVoiceChannelRight;
95 if (pEq) delete pEq;
96 Unregister();
97 }
98
99 /**
100 * Once an engine channel is disconnected from an audio output device,
101 * it will immediately call this method to unregister itself from the
102 * engine instance and if that engine instance is not used by any other
103 * engine channel anymore, then that engine instance will be destroyed.
104 *
105 * @param pChannel - engine channel which wants to disconnect from it's
106 * engine instance
107 * @param pDevice - audio output device \a pChannel was connected to
108 */
109 void AbstractEngine::FreeEngine(AbstractEngineChannel* pChannel, AudioOutputDevice* pDevice) {
110 dmsg(4,("Disconnecting EngineChannel from Engine.\n"));
111 AbstractEngine* pEngine = engines[pChannel->GetEngineFormat()][pDevice];
112 // unregister EngineChannel from the Engine instance
113 pEngine->engineChannels.remove(pChannel);
114 // if the used Engine instance is not used anymore, then destroy it
115 if (pEngine->engineChannels.empty()) {
116 pDevice->Disconnect(pEngine);
117 engines[pChannel->GetEngineFormat()].erase(pDevice);
118 delete pEngine;
119 dmsg(4,("Destroying Engine.\n"));
120 }
121 else dmsg(4,("This Engine has now %d EngineChannels.\n",pEngine->engineChannels.size()));
122 }
123
124 void AbstractEngine::Enable() {
125 dmsg(3,("AbstractEngine: enabling\n"));
126 EngineDisabled.PushAndUnlock(false, 2, 0, true); // set condition object 'EngineDisabled' to false (wait max. 2s)
127 dmsg(3,("AbstractEngine: enabled (val=%d)\n", EngineDisabled.GetUnsafe()));
128 }
129
130 /**
131 * Temporarily stop the engine to not do anything. The engine will just be
132 * frozen during that time, that means after enabling it again it will
133 * continue where it was, with all its voices and playback state it had at
134 * the point of disabling. Notice that the engine's (audio) thread will
135 * continue to run, it just remains in an inactive loop during that time.
136 *
137 * If you need to be sure that all voices and disk streams are killed as
138 * well, use @c SuspendAll() instead.
139 *
140 * @see Enable(), SuspendAll()
141 */
142 void AbstractEngine::Disable() {
143 dmsg(3,("AbstractEngine: disabling\n"));
144 bool* pWasDisabled = EngineDisabled.PushAndUnlock(true, 2); // wait max. 2s
145 if (!pWasDisabled) dmsg(3,("AbstractEngine warning: Timeout waiting to disable engine.\n"));
146 }
147
148 void AbstractEngine::DisableAndLock() {
149 dmsg(3,("AbstractEngine: disabling\n"));
150 bool* pWasDisabled = EngineDisabled.Push(true, 2); // wait max. 2s
151 if (!pWasDisabled) dmsg(3,("AbstractEngine warning: Timeout waiting to disable engine.\n"));
152 }
153
154 /**
155 * Reset all voices and disk thread and clear input event queue and all
156 * control and status variables.
157 */
158 void AbstractEngine::Reset() {
159 DisableAndLock();
160 ResetInternal();
161 ResetScaleTuning();
162 Enable();
163 }
164
165 /**
166 * Reset to normal, chromatic scale (means equal tempered).
167 */
168 void AbstractEngine::ResetScaleTuning() {
169 memset(&ScaleTuning[0], 0x00, 12);
170 }
171
172 /**
173 * Copy all events from the engine's global input queue buffer to the
174 * engine's internal event list. This will be done at the beginning of
175 * each audio cycle (that is each RenderAudio() call) to distinguish
176 * all global events which have to be processed in the current audio
177 * cycle. These events are usually just SysEx messages. Every
178 * EngineChannel has it's own input event queue buffer and event list
179 * to handle common events like NoteOn, NoteOff and ControlChange
180 * events.
181 *
182 * @param Samples - number of sample points to be processed in the
183 * current audio cycle
184 */
185 void AbstractEngine::ImportEvents(uint Samples) {
186 RingBuffer<Event,false>::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader();
187 Event* pEvent;
188 while (true) {
189 // get next event from input event queue
190 if (!(pEvent = eventQueueReader.pop())) break;
191 // if younger event reached, ignore that and all subsequent ones for now
192 if (pEvent->FragmentPos() >= Samples) {
193 eventQueueReader--;
194 dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples));
195 pEvent->ResetFragmentPos();
196 break;
197 }
198 // copy event to internal event list
199 if (pGlobalEvents->poolIsEmpty()) {
200 dmsg(1,("Event pool emtpy!\n"));
201 break;
202 }
203 *pGlobalEvents->allocAppend() = *pEvent;
204 }
205 eventQueueReader.free(); // free all copied events from input queue
206 }
207
208 /**
209 * Clear all engine global event lists.
210 */
211 void AbstractEngine::ClearEventLists() {
212 pGlobalEvents->clear();
213 }
214
215 /**
216 * Will be called in case the respective engine channel sports FX send
217 * channels. In this particular case, engine channel local buffers are
218 * used to render and mix all voices to. This method is responsible for
219 * copying the audio data from those local buffers to the master audio
220 * output channels as well as to the FX send audio output channels with
221 * their respective FX send levels.
222 *
223 * @param pEngineChannel - engine channel from which audio should be
224 * routed
225 * @param Samples - amount of sample points to be routed in
226 * this audio fragment cycle
227 */
228 void AbstractEngine::RouteAudio(EngineChannel* pEngineChannel, uint Samples) {
229 AbstractEngineChannel* pChannel = static_cast<AbstractEngineChannel*>(pEngineChannel);
230 AudioChannel* ppSource[2] = {
231 pChannel->pChannelLeft,
232 pChannel->pChannelRight
233 };
234 // route dry signal
235 {
236 AudioChannel* pDstL = pAudioOutputDevice->Channel(pChannel->AudioDeviceChannelLeft);
237 AudioChannel* pDstR = pAudioOutputDevice->Channel(pChannel->AudioDeviceChannelRight);
238 ppSource[0]->MixTo(pDstL, Samples);
239 ppSource[1]->MixTo(pDstR, Samples);
240 }
241 // route FX send signal (wet)
242 {
243 for (int iFxSend = 0; iFxSend < pChannel->GetFxSendCount(); iFxSend++) {
244 FxSend* pFxSend = pChannel->GetFxSend(iFxSend);
245 const bool success = RouteFxSend(pFxSend, ppSource, pFxSend->Level(), Samples);
246 if (!success) goto channel_cleanup;
247 }
248 }
249 channel_cleanup:
250 // reset buffers with silence (zero out) for the next audio cycle
251 ppSource[0]->Clear();
252 ppSource[1]->Clear();
253 }
254
255 /**
256 * Similar to RouteAudio(), but this method is even more special. It is
257 * only called by voices which have dedicated effect send(s) level(s). So
258 * such voices have to be routed separately apart from the other voices
259 * which can just be mixed together and routed afterwards in one turn.
260 */
261 void AbstractEngine::RouteDedicatedVoiceChannels(EngineChannel* pEngineChannel, optional<float> FxSendLevels[2], uint Samples) {
262 AbstractEngineChannel* pChannel = static_cast<AbstractEngineChannel*>(pEngineChannel);
263 AudioChannel* ppSource[2] = {
264 pDedicatedVoiceChannelLeft,
265 pDedicatedVoiceChannelRight
266 };
267 // route dry signal
268 {
269 AudioChannel* pDstL = pAudioOutputDevice->Channel(pChannel->AudioDeviceChannelLeft);
270 AudioChannel* pDstR = pAudioOutputDevice->Channel(pChannel->AudioDeviceChannelRight);
271 ppSource[0]->MixTo(pDstL, Samples);
272 ppSource[1]->MixTo(pDstR, Samples);
273 }
274 // route FX send signals (wet)
275 // (we simply hard code the voices 'reverb send' to the 1st effect
276 // send bus, and the voioces 'chorus send' to the 2nd effect send bus)
277 {
278 for (int iFxSend = 0; iFxSend < 2 && iFxSend < pChannel->GetFxSendCount(); iFxSend++) {
279 // no voice specific FX send level defined for this effect?
280 if (!FxSendLevels[iFxSend]) continue; // ignore this effect then
281
282 FxSend* pFxSend = pChannel->GetFxSend(iFxSend);
283 const bool success = RouteFxSend(pFxSend, ppSource, *FxSendLevels[iFxSend], Samples);
284 if (!success) goto channel_cleanup;
285 }
286 }
287 channel_cleanup:
288 // reset buffers with silence (zero out) for the next dedicated voice rendering/routing process
289 ppSource[0]->Clear();
290 ppSource[1]->Clear();
291 }
292
293 /**
294 * Route the audio signal given by @a ppSource to the effect send bus
295 * defined by @a pFxSend (wet signal only).
296 *
297 * @param pFxSend - definition of effect send bus
298 * @param ppSource - the 2 channels of the audio signal to be routed
299 * @param FxSendLevel - the effect send level to by applied
300 * @param Samples - amount of sample points to be processed
301 * @returns true if signal was routed successfully, false on error
302 */
303 bool AbstractEngine::RouteFxSend(FxSend* pFxSend, AudioChannel* ppSource[2], float FxSendLevel, uint Samples) {
304 for (int iChan = 0; iChan < 2; ++iChan) {
305 const int iDstChan = pFxSend->DestinationChannel(iChan);
306 if (iDstChan < 0) {
307 dmsg(1,("Engine::RouteAudio() Error: invalid FX send (%s) destination channel (%d->%d)", ((iChan) ? "R" : "L"), iChan, iDstChan));
308 return false; // error
309 }
310 AudioChannel* pDstChan = NULL;
311 if (pFxSend->DestinationEffectChain() >= 0) { // fx send routed to an internal send effect
312 EffectChain* pEffectChain =
313 pAudioOutputDevice->SendEffectChainByID(
314 pFxSend->DestinationEffectChain()
315 );
316 if (!pEffectChain) {
317 dmsg(1,("Engine::RouteAudio() Error: invalid FX send (%s) destination effect chain %d", ((iChan) ? "R" : "L"), pFxSend->DestinationEffectChain()));
318 return false; // error
319 }
320 Effect* pEffect =
321 pEffectChain->GetEffect(
322 pFxSend->DestinationEffectChainPosition()
323 );
324 if (!pEffect) {
325 dmsg(1,("Engine::RouteAudio() Error: invalid FX send (%s) destination effect %d of effect chain %d", ((iChan) ? "R" : "L"), pFxSend->DestinationEffectChainPosition(), pFxSend->DestinationEffectChain()));
326 return false; // error
327 }
328 pDstChan = pEffect->InputChannel(iDstChan);
329 } else { // FX send routed directly to an audio output channel
330 pDstChan = pAudioOutputDevice->Channel(iDstChan);
331 }
332 if (!pDstChan) {
333 dmsg(1,("Engine::RouteAudio() Error: invalid FX send (%s) destination channel (%d->%d)", ((iChan) ? "R" : "L"), iChan, iDstChan));
334 return false; // error
335 }
336 ppSource[iChan]->MixTo(pDstChan, Samples, FxSendLevel);
337 }
338 return true; // success
339 }
340
341 /**
342 * Calculates the Roland GS sysex check sum.
343 *
344 * @param AddrReader - reader which currently points to the first GS
345 * command address byte of the GS sysex message in
346 * question
347 * @param DataSize - size of the GS message data (in bytes)
348 */
349 uint8_t AbstractEngine::GSCheckSum(const RingBuffer<uint8_t,false>::NonVolatileReader AddrReader, uint DataSize) {
350 RingBuffer<uint8_t,false>::NonVolatileReader reader = AddrReader;
351 uint bytes = 3 /*addr*/ + DataSize;
352 uint8_t addr_and_data[bytes];
353 reader.read(&addr_and_data[0], bytes);
354 uint8_t sum = 0;
355 for (uint i = 0; i < bytes; i++) sum += addr_and_data[i];
356 return 128 - sum % 128;
357 }
358
359 /**
360 * Allows to tune each of the twelve semitones of an octave.
361 *
362 * @param ScaleTunes - detuning of all twelve semitones (in cents)
363 */
364 void AbstractEngine::AdjustScale(int8_t ScaleTunes[12]) {
365 memcpy(&this->ScaleTuning[0], &ScaleTunes[0], 12); //TODO: currently not sample accurate
366 }
367
368 uint AbstractEngine::VoiceCount() {
369 return atomic_read(&ActiveVoiceCount);
370 }
371
372 void AbstractEngine::SetVoiceCount(uint Count) {
373 atomic_set(&ActiveVoiceCount, Count);
374 }
375
376 uint AbstractEngine::VoiceCountMax() {
377 return ActiveVoiceCountMax;
378 }
379
380 /**
381 * Moves pitchbend event from the general (input) event list to the engine
382 * channel's event list. It will actually processed later by the
383 * respective voice.
384 *
385 * @param pEngineChannel - engine channel on which this event occured on
386 * @param itPitchbendEvent - absolute pitch value and time stamp of the event
387 */
388 void AbstractEngine::ProcessPitchbend(AbstractEngineChannel* pEngineChannel, Pool<Event>::Iterator& itPitchbendEvent) {
389 pEngineChannel->Pitch = itPitchbendEvent->Param.Pitch.Pitch; // store current pitch value
390 }
391
392 void AbstractEngine::ProcessFxSendControllers (
393 AbstractEngineChannel* pEngineChannel,
394 Pool<Event>::Iterator& itControlChangeEvent
395 ) {
396 if (!pEngineChannel->fxSends.empty()) {
397 for (int iFxSend = 0; iFxSend < pEngineChannel->GetFxSendCount(); iFxSend++) {
398 FxSend* pFxSend = pEngineChannel->GetFxSend(iFxSend);
399 if (pFxSend->MidiController() == itControlChangeEvent->Param.CC.Controller) {
400 pFxSend->SetLevel(itControlChangeEvent->Param.CC.Value);
401 pFxSend->SetInfoChanged(true);
402 }
403 }
404 }
405 }
406
407 /**
408 * Will be called by the MIDI input device whenever a MIDI system
409 * exclusive message has arrived.
410 *
411 * @param pData - pointer to sysex data
412 * @param Size - lenght of sysex data (in bytes)
413 * @param pSender - the MIDI input port on which the SysEx message was
414 * received
415 */
416 void AbstractEngine::SendSysex(void* pData, uint Size, MidiInputPort* pSender) {
417 Event event = pEventGenerator->CreateEvent();
418 event.Type = Event::type_sysex;
419 event.Param.Sysex.Size = Size;
420 event.pEngineChannel = NULL; // as Engine global event
421 event.pMidiInputPort = pSender;
422 if (pEventQueue->write_space() > 0) {
423 if (pSysexBuffer->write_space() >= Size) {
424 // copy sysex data to input buffer
425 uint toWrite = Size;
426 uint8_t* pPos = (uint8_t*) pData;
427 while (toWrite) {
428 const uint writeNow = RTMath::Min(toWrite, pSysexBuffer->write_space_to_end());
429 pSysexBuffer->write(pPos, writeNow);
430 toWrite -= writeNow;
431 pPos += writeNow;
432
433 }
434 // finally place sysex event into input event queue
435 pEventQueue->push(&event);
436 }
437 else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,CONFIG_SYSEX_BUFFER_SIZE));
438 }
439 else dmsg(1,("Engine: Input event queue full!"));
440 }
441
442 /**
443 * Reacts on MIDI system exclusive messages.
444 *
445 * @param itSysexEvent - sysex data size and time stamp of the sysex event
446 */
447 void AbstractEngine::ProcessSysex(Pool<Event>::Iterator& itSysexEvent) {
448 RingBuffer<uint8_t,false>::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader();
449
450 uint8_t exclusive_status, id;
451 if (!reader.pop(&exclusive_status)) goto free_sysex_data;
452 if (!reader.pop(&id)) goto free_sysex_data;
453 if (exclusive_status != 0xF0) goto free_sysex_data;
454
455 switch (id) {
456 case 0x7f: { // (Realtime) Universal Sysex (GM Standard)
457 uint8_t sysex_channel, sub_id1, sub_id2, val_msb, val_lsb;;
458 if (!reader.pop(&sysex_channel)) goto free_sysex_data;
459 if (!reader.pop(&sub_id1)) goto free_sysex_data;
460 if (!reader.pop(&sub_id2)) goto free_sysex_data;
461 if (!reader.pop(&val_lsb)) goto free_sysex_data;
462 if (!reader.pop(&val_msb)) goto free_sysex_data;
463 //TODO: for now we simply ignore the sysex channel, seldom used anyway
464 switch (sub_id1) {
465 case 0x04: // Device Control
466 switch (sub_id2) {
467 case 0x01: { // Master Volume
468 const double volume =
469 double((uint(val_msb)<<7) | uint(val_lsb)) / 16383.0;
470 #if CONFIG_MASTER_VOLUME_SYSEX_BY_PORT
471 // apply volume to all sampler channels that
472 // are connected to the same MIDI input port
473 // this sysex message arrived on
474 for (int i = 0; i < engineChannels.size(); ++i) {
475 EngineChannel* pEngineChannel = engineChannels[i];
476 if (pEngineChannel->GetMidiInputPort() ==
477 itSysexEvent->pMidiInputPort)
478 {
479 pEngineChannel->Volume(volume);
480 }
481 }
482 #else
483 // apply volume globally to the whole sampler
484 GLOBAL_VOLUME = volume;
485 #endif // CONFIG_MASTER_VOLUME_SYSEX_BY_PORT
486 break;
487 }
488 }
489 break;
490 }
491 break;
492 }
493 case 0x41: { // Roland
494 dmsg(3,("Roland Sysex\n"));
495 uint8_t device_id, model_id, cmd_id;
496 if (!reader.pop(&device_id)) goto free_sysex_data;
497 if (!reader.pop(&model_id)) goto free_sysex_data;
498 if (!reader.pop(&cmd_id)) goto free_sysex_data;
499 if (model_id != 0x42 /*GS*/) goto free_sysex_data;
500 if (cmd_id != 0x12 /*DT1*/) goto free_sysex_data;
501
502 // command address
503 uint8_t addr[3]; // 2 byte addr MSB, followed by 1 byte addr LSB)
504 const RingBuffer<uint8_t,false>::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later
505 if (reader.read(&addr[0], 3) != 3) goto free_sysex_data;
506 if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters
507 dmsg(3,("\tSystem Parameter\n"));
508 if (addr[2] == 0x7f) { // GS reset
509 for (int i = 0; i < engineChannels.size(); ++i) {
510 AbstractEngineChannel* pEngineChannel
511 = static_cast<AbstractEngineChannel*>(engineChannels[i]);
512 if (pEngineChannel->GetMidiInputPort() == itSysexEvent->pMidiInputPort) {
513 KillAllVoices(pEngineChannel, itSysexEvent);
514 pEngineChannel->ResetControllers();
515 }
516 }
517 }
518 }
519 else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters
520 dmsg(3,("\tCommon Parameter\n"));
521 }
522 else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1)
523 dmsg(3,("\tPart Parameter\n"));
524 switch (addr[2]) {
525 case 0x40: { // scale tuning
526 dmsg(3,("\t\tScale Tuning\n"));
527 uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave
528 if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data;
529 uint8_t checksum;
530 if (!reader.pop(&checksum)) goto free_sysex_data;
531 #if CONFIG_ASSERT_GS_SYSEX_CHECKSUM
532 if (GSCheckSum(checksum_reader, 12)) goto free_sysex_data;
533 #endif // CONFIG_ASSERT_GS_SYSEX_CHECKSUM
534 for (int i = 0; i < 12; i++) scale_tunes[i] -= 64;
535 AdjustScale((int8_t*) scale_tunes);
536 dmsg(3,("\t\t\tNew scale applied.\n"));
537 break;
538 }
539 case 0x15: { // chromatic / drumkit mode
540 dmsg(3,("\t\tMIDI Instrument Map Switch\n"));
541 uint8_t part = addr[1] & 0x0f;
542 uint8_t map;
543 if (!reader.pop(&map)) goto free_sysex_data;
544 for (int i = 0; i < engineChannels.size(); ++i) {
545 AbstractEngineChannel* pEngineChannel
546 = static_cast<AbstractEngineChannel*>(engineChannels[i]);
547 if (
548 (pEngineChannel->midiChannel == part ||
549 pEngineChannel->midiChannel == midi_chan_all) &&
550 pEngineChannel->GetMidiInputPort() == itSysexEvent->pMidiInputPort
551 ) {
552 try {
553 pEngineChannel->SetMidiInstrumentMap(map);
554 } catch (Exception e) {
555 dmsg(2,("\t\t\tCould not apply MIDI instrument map %d to part %d: %s\n", map, part, e.Message().c_str()));
556 goto free_sysex_data;
557 } catch (...) {
558 dmsg(2,("\t\t\tCould not apply MIDI instrument map %d to part %d (unknown exception)\n", map, part));
559 goto free_sysex_data;
560 }
561 }
562 }
563 dmsg(3,("\t\t\tApplied MIDI instrument map %d to part %d.\n", map, part));
564 break;
565 }
566 }
567 }
568 else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x20) { // Part Parameters (2)
569 }
570 else if (addr[0] == 0x41) { // Drum Setup Parameters
571 }
572 break;
573 }
574 }
575
576 free_sysex_data: // finally free sysex data
577 pSysexBuffer->increment_read_ptr(itSysexEvent->Param.Sysex.Size);
578 }
579
580 String AbstractEngine::GetFormatString(Format f) {
581 switch(f) {
582 case GIG: return "GIG";
583 case SF2: return "SF2";
584 case SFZ: return "SFZ";
585 default: return "UNKNOWN";
586 }
587 }
588
589 String AbstractEngine::EngineName() {
590 return GetFormatString(GetEngineFormat());
591 }
592
593 // static constant initializers
594 const AbstractEngine::FloatTable AbstractEngine::VolumeCurve(InitVolumeCurve());
595 const AbstractEngine::FloatTable AbstractEngine::PanCurve(InitPanCurve());
596 const AbstractEngine::FloatTable AbstractEngine::CrossfadeCurve(InitCrossfadeCurve());
597
598 float* AbstractEngine::InitVolumeCurve() {
599 // line-segment approximation
600 const float segments[] = {
601 0, 0, 2, 0.0046, 16, 0.016, 31, 0.051, 45, 0.115, 54.5, 0.2,
602 64.5, 0.39, 74, 0.74, 92, 1.03, 114, 1.94, 119.2, 2.2, 127, 2.2
603 };
604 return InitCurve(segments);
605 }
606
607 float* AbstractEngine::InitPanCurve() {
608 // line-segment approximation
609 const float segments[] = {
610 0, 0, 1, 0,
611 2, 0.05, 31.5, 0.7, 51, 0.851, 74.5, 1.12,
612 127, 1.41, 128, 1.41
613 };
614 return InitCurve(segments, 129);
615 }
616
617 float* AbstractEngine::InitCrossfadeCurve() {
618 // line-segment approximation
619 const float segments[] = {
620 0, 0, 1, 0.03, 10, 0.1, 51, 0.58, 127, 1
621 };
622 return InitCurve(segments);
623 }
624
625 float* AbstractEngine::InitCurve(const float* segments, int size) {
626 float* y = new float[size];
627 for (int x = 0 ; x < size ; x++) {
628 if (x > segments[2]) segments += 2;
629 y[x] = segments[1] + (x - segments[0]) *
630 (segments[3] - segments[1]) / (segments[2] - segments[0]);
631 }
632 return y;
633 }
634
635 } // namespace LinuxSampler

  ViewVC Help
Powered by ViewVC