--- linuxsampler/trunk/src/engines/gig/Engine.cpp 2004/06/06 20:57:28 112 +++ linuxsampler/trunk/src/engines/gig/Engine.cpp 2004/09/20 00:31:13 250 @@ -37,21 +37,24 @@ pAudioOutputDevice = NULL; pDiskThread = NULL; pEventGenerator = NULL; - pEventQueue = new RingBuffer(MAX_EVENTS_PER_FRAGMENT); + pSysexBuffer = new RingBuffer(SYSEX_BUFFER_SIZE, 0); + pEventQueue = new RingBuffer(MAX_EVENTS_PER_FRAGMENT, 0); pEventPool = new RTELMemoryPool(MAX_EVENTS_PER_FRAGMENT); pVoicePool = new RTELMemoryPool(MAX_AUDIO_VOICES); pActiveKeys = new RTELMemoryPool(128); + pVoiceStealingQueue = new RTEList(pEventPool); pEvents = new RTEList(pEventPool); pCCEvents = new RTEList(pEventPool); for (uint i = 0; i < Event::destination_count; i++) { pSynthesisEvents[i] = new RTEList(pEventPool); } for (uint i = 0; i < 128; i++) { - pMIDIKeyInfo[i].pActiveVoices = new RTEList(pVoicePool); - pMIDIKeyInfo[i].KeyPressed = false; - pMIDIKeyInfo[i].Active = false; - pMIDIKeyInfo[i].pSelf = NULL; - pMIDIKeyInfo[i].pEvents = new RTEList(pEventPool); + pMIDIKeyInfo[i].pActiveVoices = new RTEList(pVoicePool); + pMIDIKeyInfo[i].KeyPressed = false; + pMIDIKeyInfo[i].Active = false; + pMIDIKeyInfo[i].ReleaseTrigger = false; + pMIDIKeyInfo[i].pSelf = NULL; + pMIDIKeyInfo[i].pEvents = new RTEList(pEventPool); } for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) { pVoice->SetEngine(this); @@ -61,8 +64,12 @@ pSynthesisParameters[0] = NULL; // we allocate when an audio device is connected pBasicFilterParameters = NULL; pMainFilterParameters = NULL; - + InstrumentIdx = -1; + InstrumentStat = -1; + + AudioDeviceChannelLeft = -1; + AudioDeviceChannelRight = -1; ResetInternal(); } @@ -88,10 +95,12 @@ if (pEventPool) delete pEventPool; if (pVoicePool) delete pVoicePool; if (pActiveKeys) delete pActiveKeys; + if (pSysexBuffer) delete pSysexBuffer; if (pEventGenerator) delete pEventGenerator; if (pMainFilterParameters) delete[] pMainFilterParameters; if (pBasicFilterParameters) delete[] pBasicFilterParameters; if (pSynthesisParameters[0]) delete[] pSynthesisParameters[0]; + if (pVoiceStealingQueue) delete pVoiceStealingQueue; } void Engine::Enable() { @@ -148,6 +157,15 @@ SustainPedal = false; ActiveVoiceCount = 0; ActiveVoiceCountMax = 0; + GlobalVolume = 1.0; + + // reset voice stealing parameters + pLastStolenVoice = NULL; + puiLastStolenKey = NULL; + pVoiceStealingQueue->clear(); + + // reset to normal chromatic scale (means equal temper) + memset(&ScaleTuning[0], 0x00, 12); // set all MIDI controller values to zero memset(ControllerTable, 0x00, 128); @@ -156,11 +174,16 @@ for (uint i = 0; i < 128; i++) { pMIDIKeyInfo[i].pActiveVoices->clear(); pMIDIKeyInfo[i].pEvents->clear(); - pMIDIKeyInfo[i].KeyPressed = false; - pMIDIKeyInfo[i].Active = false; - pMIDIKeyInfo[i].pSelf = NULL; + pMIDIKeyInfo[i].KeyPressed = false; + pMIDIKeyInfo[i].Active = false; + pMIDIKeyInfo[i].ReleaseTrigger = false; + pMIDIKeyInfo[i].pSelf = NULL; } + // reset all key groups + map::iterator iter = ActiveKeyGroups.begin(); + for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL; + // reset all voices for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) { pVoice->Reset(); @@ -197,7 +220,12 @@ Instruments.HandBack(pInstrument, this); } - InstrumentIdx = -1; + InstrumentFile = FileName; + InstrumentIdx = Instrument; + InstrumentStat = 0; + + // delete all key groups + ActiveKeyGroups.clear(); // request gig instrument from instrument manager try { @@ -206,24 +234,31 @@ instrid.iInstrument = Instrument; pInstrument = Instruments.Borrow(instrid, this); if (!pInstrument) { + InstrumentStat = -1; dmsg(1,("no instrument loaded!!!\n")); exit(EXIT_FAILURE); } } catch (RIFF::Exception e) { + InstrumentStat = -2; String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message; throw LinuxSamplerException(msg); } catch (InstrumentResourceManagerException e) { + InstrumentStat = -3; String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message(); throw LinuxSamplerException(msg); } catch (...) { + InstrumentStat = -4; throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file."); } - InstrumentFile = FileName; - InstrumentIdx = Instrument; + // rebuild ActiveKeyGroups map with key groups of current instrument + for (::gig::Region* pRegion = pInstrument->GetFirstRegion(); pRegion; pRegion = pInstrument->GetNextRegion()) + if (pRegion->KeyGroup) ActiveKeyGroups[pRegion->KeyGroup] = NULL; + + InstrumentStat = 100; // inform audio driver for the need of two channels try { @@ -254,7 +289,7 @@ * update process was completed, so we can continue with playback. */ void Engine::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) { - this->pInstrument = pNewResource; + this->pInstrument = pNewResource; //TODO: there are couple of engine parameters we should update here as well if the instrument was updated (see LoadInstrument()) Enable(); } @@ -272,6 +307,13 @@ throw LinuxSamplerException(msg); } + this->AudioDeviceChannelLeft = 0; + this->AudioDeviceChannelRight = 1; + this->pOutputLeft = pAudioOutputDevice->Channel(0)->Buffer(); + this->pOutputRight = pAudioOutputDevice->Channel(1)->Buffer(); + this->MaxSamplesPerCycle = pAudioOutputDevice->MaxSamplesPerCycle(); + this->SampleRate = pAudioOutputDevice->SampleRate(); + // (re)create disk thread if (this->pDiskThread) { this->pDiskThread->StopThread(); @@ -285,7 +327,6 @@ for (Voice* pVoice = pVoicePool->alloc(); pVoice; pVoice = pVoicePool->alloc()) { pVoice->pDiskThread = this->pDiskThread; - pVoice->SetOutput(pAudioOut); dmsg(3,("d")); } pVoicePool->clear(); @@ -323,6 +364,8 @@ AudioOutputDevice* olddevice = pAudioOutputDevice; pAudioOutputDevice = NULL; olddevice->Disconnect(this); + AudioDeviceChannelLeft = -1; + AudioDeviceChannelRight = -1; } } @@ -356,6 +399,10 @@ for (uint i = 0; i < Event::destination_count; i++) { pSynthesisEvents[i]->clear(); } + for (uint* puiKey = pActiveKeys->first(); puiKey; puiKey = pActiveKeys->next()) { + midi_key_info_t* pKey = &pMIDIKeyInfo[*puiKey]; + pKey->pEvents->clear(); // free all events on the key + } // read and copy events from input queue Event event = pEventGenerator->CreateEvent(); @@ -377,21 +424,25 @@ pNextEvent = pEvents->next(); switch (pEvent->Type) { case Event::type_note_on: - dmsg(5,("Audio Thread: Note on received\n")); + dmsg(5,("Engine: Note on received\n")); ProcessNoteOn(pEvent); break; case Event::type_note_off: - dmsg(5,("Audio Thread: Note off received\n")); + dmsg(5,("Engine: Note off received\n")); ProcessNoteOff(pEvent); break; case Event::type_control_change: - dmsg(5,("Audio Thread: MIDI CC received\n")); + dmsg(5,("Engine: MIDI CC received\n")); ProcessControlChange(pEvent); break; case Event::type_pitchbend: - dmsg(5,("Audio Thread: Pitchbend received\n")); + dmsg(5,("Engine: Pitchbend received\n")); ProcessPitchbend(pEvent); break; + case Event::type_sysex: + dmsg(5,("Engine: Sysex received\n")); + ProcessSysex(pEvent); + break; } } @@ -415,13 +466,32 @@ pVoice->Render(Samples); if (pVoice->IsActive()) active_voices++; // still active else { // voice reached end, is now inactive - KillVoice(pVoice); // remove voice from the list of active voices + KillVoiceImmediately(pVoice); // remove voice from the list of active voices } } - pKey->pEvents->clear(); // free all events on the key } + // now render all postponed voices from voice stealing + Event* pVoiceStealEvent = pVoiceStealingQueue->first(); + while (pVoiceStealEvent) { + Voice* pNewVoice = LaunchVoice(pVoiceStealEvent, pVoiceStealEvent->Param.Note.Layer, pVoiceStealEvent->Param.Note.ReleaseTrigger, false); + if (pNewVoice) { + pNewVoice->Render(Samples); + if (pNewVoice->IsActive()) active_voices++; // still active + else { // voice reached end, is now inactive + KillVoiceImmediately(pNewVoice); // remove voice from the list of active voices + } + } + else dmsg(1,("Ouch, voice stealing didn't work out!\n")); + pVoiceStealEvent = pVoiceStealingQueue->next(); + } + // reset voice stealing for the new fragment + pVoiceStealingQueue->clear(); + pLastStolenVoice = NULL; + puiLastStolenKey = NULL; + + // write that to the disk thread class so that it can print it // on the console for debugging purposes ActiveVoiceCount = active_voices; @@ -439,10 +509,10 @@ * @param Velocity - MIDI velocity value of the triggered key */ void Engine::SendNoteOn(uint8_t Key, uint8_t Velocity) { - Event event = pEventGenerator->CreateEvent(); - event.Type = Event::type_note_on; - event.Key = Key; - event.Velocity = Velocity; + Event event = pEventGenerator->CreateEvent(); + event.Type = Event::type_note_on; + event.Param.Note.Key = Key; + event.Param.Note.Velocity = Velocity; if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event); else dmsg(1,("Engine: Input event queue full!")); } @@ -455,10 +525,10 @@ * @param Velocity - MIDI release velocity value of the released key */ void Engine::SendNoteOff(uint8_t Key, uint8_t Velocity) { - Event event = pEventGenerator->CreateEvent(); - event.Type = Event::type_note_off; - event.Key = Key; - event.Velocity = Velocity; + Event event = pEventGenerator->CreateEvent(); + event.Type = Event::type_note_off; + event.Param.Note.Key = Key; + event.Param.Note.Velocity = Velocity; if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event); else dmsg(1,("Engine: Input event queue full!")); } @@ -470,9 +540,9 @@ * @param Pitch - MIDI pitch value (-8192 ... +8191) */ void Engine::SendPitchbend(int Pitch) { - Event event = pEventGenerator->CreateEvent(); - event.Type = Event::type_pitchbend; - event.Pitch = Pitch; + Event event = pEventGenerator->CreateEvent(); + event.Type = Event::type_pitchbend; + event.Param.Pitch.Pitch = Pitch; if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event); else dmsg(1,("Engine: Input event queue full!")); } @@ -485,45 +555,70 @@ * @param Value - value of the control change */ void Engine::SendControlChange(uint8_t Controller, uint8_t Value) { - Event event = pEventGenerator->CreateEvent(); - event.Type = Event::type_control_change; - event.Controller = Controller; - event.Value = Value; + Event event = pEventGenerator->CreateEvent(); + event.Type = Event::type_control_change; + event.Param.CC.Controller = Controller; + event.Param.CC.Value = Value; if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event); else dmsg(1,("Engine: Input event queue full!")); } /** + * Will be called by the MIDI input device whenever a MIDI system + * exclusive message has arrived. + * + * @param pData - pointer to sysex data + * @param Size - lenght of sysex data (in bytes) + */ + void Engine::SendSysex(void* pData, uint Size) { + Event event = pEventGenerator->CreateEvent(); + event.Type = Event::type_sysex; + event.Param.Sysex.Size = Size; + if (pEventQueue->write_space() > 0) { + if (pSysexBuffer->write_space() >= Size) { + // copy sysex data to input buffer + uint toWrite = Size; + uint8_t* pPos = (uint8_t*) pData; + while (toWrite) { + const uint writeNow = RTMath::Min(toWrite, pSysexBuffer->write_space_to_end()); + pSysexBuffer->write(pPos, writeNow); + toWrite -= writeNow; + pPos += writeNow; + + } + // finally place sysex event into input event queue + pEventQueue->push(&event); + } + else dmsg(1,("Engine: Sysex message too large (%d byte) for input buffer (%d byte)!",Size,SYSEX_BUFFER_SIZE)); + } + else dmsg(1,("Engine: Input event queue full!")); + } + + /** * Assigns and triggers a new voice for the respective MIDI key. * * @param pNoteOnEvent - key, velocity and time stamp of the event */ void Engine::ProcessNoteOn(Event* pNoteOnEvent) { - midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Key]; + midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Param.Note.Key]; pKey->KeyPressed = true; // the MIDI key was now pressed down // cancel release process of voices on this key if needed if (pKey->Active && !SustainPedal) { - pNoteOnEvent->Type = Event::type_cancel_release; // transform event type - pEvents->move(pNoteOnEvent, pKey->pEvents); // move event to the key's own event list - } - - // allocate a new voice for the key - Voice* pNewVoice = pKey->pActiveVoices->alloc(); - if (pNewVoice) { - // launch the new voice - if (pNewVoice->Trigger(pNoteOnEvent, this->Pitch, this->pInstrument) < 0) { - dmsg(1,("Triggering new voice failed!\n")); - pKey->pActiveVoices->free(pNewVoice); - } - else if (!pKey->Active) { // mark as active key - pKey->Active = true; - pKey->pSelf = pActiveKeys->alloc(); - *pKey->pSelf = pNoteOnEvent->Key; + Event* pCancelReleaseEvent = pKey->pEvents->alloc(); + if (pCancelReleaseEvent) { + *pCancelReleaseEvent = *pNoteOnEvent; + pCancelReleaseEvent->Type = Event::type_cancel_release; // transform event type } + else dmsg(1,("Event pool emtpy!\n")); } - else std::cerr << "No free voice!" << std::endl << std::flush; + + // allocate and trigger a new voice for the key + LaunchVoice(pNoteOnEvent); + + // finally move note on event to the key's own event list + pEvents->move(pNoteOnEvent, pKey->pEvents); } /** @@ -535,15 +630,23 @@ * @param pNoteOffEvent - key, velocity and time stamp of the event */ void Engine::ProcessNoteOff(Event* pNoteOffEvent) { - midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOffEvent->Key]; + midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOffEvent->Param.Note.Key]; pKey->KeyPressed = false; // the MIDI key was now released // release voices on this key if needed if (pKey->Active && !SustainPedal) { pNoteOffEvent->Type = Event::type_release; // transform event type - pEvents->move(pNoteOffEvent, pKey->pEvents); // move event to the key's own event list } + + // spawn release triggered voice(s) if needed + if (pKey->ReleaseTrigger) { + LaunchVoice(pNoteOffEvent, 0, true); + pKey->ReleaseTrigger = false; + } + + // move event to the key's own event list + pEvents->move(pNoteOffEvent, pKey->pEvents); } /** @@ -553,20 +656,169 @@ * @param pPitchbendEvent - absolute pitch value and time stamp of the event */ void Engine::ProcessPitchbend(Event* pPitchbendEvent) { - this->Pitch = pPitchbendEvent->Pitch; // store current pitch value + this->Pitch = pPitchbendEvent->Param.Pitch.Pitch; // store current pitch value pEvents->move(pPitchbendEvent, pSynthesisEvents[Event::destination_vco]); } /** + * Allocates and triggers a new voice. This method will usually be + * called by the ProcessNoteOn() method and by the voices itself + * (e.g. to spawn further voices on the same key for layered sounds). + * + * @param pNoteOnEvent - key, velocity and time stamp of the event + * @param iLayer - layer index for the new voice (optional - only + * in case of layered sounds of course) + * @param ReleaseTriggerVoice - if new voice is a release triggered voice + * (optional, default = false) + * @param VoiceStealing - if voice stealing should be performed + * when there is no free voice + * (optional, default = true) + * @returns pointer to new voice or NULL if there was no free voice or + * if an error occured while trying to trigger the new voice + */ + Voice* Engine::LaunchVoice(Event* pNoteOnEvent, int iLayer, bool ReleaseTriggerVoice, bool VoiceStealing) { + midi_key_info_t* pKey = &pMIDIKeyInfo[pNoteOnEvent->Param.Note.Key]; + + // allocate a new voice for the key + Voice* pNewVoice = pKey->pActiveVoices->alloc(); + if (pNewVoice) { + // launch the new voice + if (pNewVoice->Trigger(pNoteOnEvent, this->Pitch, this->pInstrument, iLayer, ReleaseTriggerVoice) < 0) { + dmsg(1,("Triggering new voice failed!\n")); + pKey->pActiveVoices->free(pNewVoice); + } + else { // on success + uint** ppKeyGroup = NULL; + if (pNewVoice->KeyGroup) { // if this voice / key belongs to a key group + ppKeyGroup = &ActiveKeyGroups[pNewVoice->KeyGroup]; + if (*ppKeyGroup) { // if there's already an active key in that key group + midi_key_info_t* pOtherKey = &pMIDIKeyInfo[**ppKeyGroup]; + // kill all voices on the (other) key + Voice* pVoiceToBeKilled = pOtherKey->pActiveVoices->first(); + while (pVoiceToBeKilled) { + Voice* pVoiceToBeKilledNext = pOtherKey->pActiveVoices->next(); + if (pVoiceToBeKilled->Type != Voice::type_release_trigger) pVoiceToBeKilled->Kill(pNoteOnEvent); + pOtherKey->pActiveVoices->set_current(pVoiceToBeKilled); + pVoiceToBeKilled = pVoiceToBeKilledNext; + } + } + } + if (!pKey->Active) { // mark as active key + pKey->Active = true; + pKey->pSelf = pActiveKeys->alloc(); + *pKey->pSelf = pNoteOnEvent->Param.Note.Key; + } + if (pNewVoice->KeyGroup) { + *ppKeyGroup = pKey->pSelf; // put key as the (new) active key to its key group + } + if (pNewVoice->Type == Voice::type_release_trigger_required) pKey->ReleaseTrigger = true; // mark key for the need of release triggered voice(s) + return pNewVoice; // success + } + } + else if (VoiceStealing) StealVoice(pNoteOnEvent, iLayer, ReleaseTriggerVoice); // no free voice left, so steal one + + return NULL; // no free voice or error + } + + /** + * Will be called by LaunchVoice() method in case there are no free + * voices left. This method will select and kill one old voice for + * voice stealing and postpone the note-on event until the selected + * voice actually died. + * + * @param pNoteOnEvent - key, velocity and time stamp of the event + * @param iLayer - layer index for the new voice + * @param ReleaseTriggerVoice - if new voice is a release triggered voice + */ + void Engine::StealVoice(Event* pNoteOnEvent, int iLayer, bool ReleaseTriggerVoice) { + if (!pEventPool->pool_is_empty()) { + + uint* puiOldestKey; + Voice* pOldestVoice; + + // Select one voice for voice stealing + switch (VOICE_STEAL_ALGORITHM) { + + // try to pick the oldest voice on the key where the new + // voice should be spawned, if there is no voice on that + // key, or no voice left to kill there, then procceed with + // 'oldestkey' algorithm + case voice_steal_algo_keymask: { + midi_key_info_t* pOldestKey = &pMIDIKeyInfo[pNoteOnEvent->Param.Note.Key]; + if (pLastStolenVoice) { + pOldestKey->pActiveVoices->set_current(pLastStolenVoice); + pOldestVoice = pOldestKey->pActiveVoices->next(); + } + else { // no voice stolen in this audio fragment cycle yet + pOldestVoice = pOldestKey->pActiveVoices->first(); + } + if (pOldestVoice) { + puiOldestKey = pOldestKey->pSelf; + break; // selection succeeded + } + } // no break - intentional ! + + // try to pick the oldest voice on the oldest active key + // (caution: must stay after 'keymask' algorithm !) + case voice_steal_algo_oldestkey: { + if (pLastStolenVoice) { + midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*puiLastStolenKey]; + pOldestKey->pActiveVoices->set_current(pLastStolenVoice); + pOldestVoice = pOldestKey->pActiveVoices->next(); + if (!pOldestVoice) { + pActiveKeys->set_current(puiLastStolenKey); + puiOldestKey = pActiveKeys->next(); + if (puiOldestKey) { + midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*puiOldestKey]; + pOldestVoice = pOldestKey->pActiveVoices->first(); + } + else { // too less voices, even for voice stealing + dmsg(1,("Voice overflow! - You might recompile with higher MAX_AUDIO_VOICES!\n")); + return; + } + } + else puiOldestKey = puiLastStolenKey; + } + else { // no voice stolen in this audio fragment cycle yet + puiOldestKey = pActiveKeys->first(); + midi_key_info_t* pOldestKey = &pMIDIKeyInfo[*puiOldestKey]; + pOldestVoice = pOldestKey->pActiveVoices->first(); + } + break; + } + + // don't steal anything + case voice_steal_algo_none: + default: { + dmsg(1,("No free voice (voice stealing disabled)!\n")); + return; + } + } + + // now kill the selected voice + pOldestVoice->Kill(pNoteOnEvent); + // remember which voice on which key we stole, so we can simply proceed for the next voice stealing + this->pLastStolenVoice = pOldestVoice; + this->puiLastStolenKey = puiOldestKey; + // put note-on event into voice-stealing queue, so it will be reprocessed after killed voice died + Event* pStealEvent = pVoiceStealingQueue->alloc(); + *pStealEvent = *pNoteOnEvent; + pStealEvent->Param.Note.Layer = iLayer; + pStealEvent->Param.Note.ReleaseTrigger = ReleaseTriggerVoice; + } + else dmsg(1,("Event pool emtpy!\n")); + } + + /** * Immediately kills the voice given with pVoice (no matter if sustain is * pressed or not) and removes it from the MIDI key's list of active voice. * This method will e.g. be called if a voice went inactive by itself. * * @param pVoice - points to the voice to be killed */ - void Engine::KillVoice(Voice* pVoice) { + void Engine::KillVoiceImmediately(Voice* pVoice) { if (pVoice) { - if (pVoice->IsActive()) pVoice->Kill(); + if (pVoice->IsActive()) pVoice->KillImmediately(); midi_key_info_t* pKey = &pMIDIKeyInfo[pVoice->MIDIKey]; @@ -575,9 +827,15 @@ // check if there are no voices left on the MIDI key and update the key info if so if (pKey->pActiveVoices->is_empty()) { + if (pVoice->KeyGroup) { // if voice / key belongs to a key group + uint** ppKeyGroup = &ActiveKeyGroups[pVoice->KeyGroup]; + if (*ppKeyGroup == pKey->pSelf) *ppKeyGroup = NULL; // remove key from key group + } pKey->Active = false; pActiveKeys->free(pKey->pSelf); // remove key from list of active keys pKey->pSelf = NULL; + pKey->ReleaseTrigger = false; + pKey->pEvents->clear(); dmsg(3,("Key has no more voices now\n")); } } @@ -591,11 +849,11 @@ * @param pControlChangeEvent - controller, value and time stamp of the event */ void Engine::ProcessControlChange(Event* pControlChangeEvent) { - dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", pControlChangeEvent->Controller, pControlChangeEvent->Value)); + dmsg(4,("Engine::ContinuousController cc=%d v=%d\n", pControlChangeEvent->Param.CC.Controller, pControlChangeEvent->Param.CC.Value)); - switch (pControlChangeEvent->Controller) { + switch (pControlChangeEvent->Param.CC.Controller) { case 64: { - if (pControlChangeEvent->Value >= 64 && !SustainPedal) { + if (pControlChangeEvent->Param.CC.Value >= 64 && !SustainPedal) { dmsg(4,("PEDAL DOWN\n")); SustainPedal = true; @@ -615,7 +873,7 @@ } } } - if (pControlChangeEvent->Value < 64 && SustainPedal) { + if (pControlChangeEvent->Param.CC.Value < 64 && SustainPedal) { dmsg(4,("PEDAL UP\n")); SustainPedal = false; @@ -640,13 +898,96 @@ } // update controller value in the engine's controller table - ControllerTable[pControlChangeEvent->Controller] = pControlChangeEvent->Value; + ControllerTable[pControlChangeEvent->Param.CC.Controller] = pControlChangeEvent->Param.CC.Value; // move event from the unsorted event list to the control change event list pEvents->move(pControlChangeEvent, pCCEvents); } /** + * Reacts on MIDI system exclusive messages. + * + * @param pSysexEvent - sysex data size and time stamp of the sysex event + */ + void Engine::ProcessSysex(Event* pSysexEvent) { + RingBuffer::NonVolatileReader reader = pSysexBuffer->get_non_volatile_reader(); + + uint8_t exclusive_status, id; + if (!reader.pop(&exclusive_status)) goto free_sysex_data; + if (!reader.pop(&id)) goto free_sysex_data; + if (exclusive_status != 0xF0) goto free_sysex_data; + + switch (id) { + case 0x41: { // Roland + uint8_t device_id, model_id, cmd_id; + if (!reader.pop(&device_id)) goto free_sysex_data; + if (!reader.pop(&model_id)) goto free_sysex_data; + if (!reader.pop(&cmd_id)) goto free_sysex_data; + if (model_id != 0x42 /*GS*/) goto free_sysex_data; + if (cmd_id != 0x12 /*DT1*/) goto free_sysex_data; + + // command address + uint8_t addr[3]; // 2 byte addr MSB, followed by 1 byte addr LSB) + const RingBuffer::NonVolatileReader checksum_reader = reader; // so we can calculate the check sum later + if (reader.read(&addr[0], 3) != 3) goto free_sysex_data; + if (addr[0] == 0x40 && addr[1] == 0x00) { // System Parameters + } + else if (addr[0] == 0x40 && addr[1] == 0x01) { // Common Parameters + } + else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x10) { // Part Parameters (1) + switch (addr[3]) { + case 0x40: { // scale tuning + uint8_t scale_tunes[12]; // detuning of all 12 semitones of an octave + if (reader.read(&scale_tunes[0], 12) != 12) goto free_sysex_data; + uint8_t checksum; + if (!reader.pop(&checksum)) goto free_sysex_data; + if (GSCheckSum(checksum_reader, 12) != checksum) goto free_sysex_data; + for (int i = 0; i < 12; i++) scale_tunes[i] -= 64; + AdjustScale((int8_t*) scale_tunes); + break; + } + } + } + else if (addr[0] == 0x40 && (addr[1] & 0xf0) == 0x20) { // Part Parameters (2) + } + else if (addr[0] == 0x41) { // Drum Setup Parameters + } + break; + } + } + + free_sysex_data: // finally free sysex data + pSysexBuffer->increment_read_ptr(pSysexEvent->Param.Sysex.Size); + } + + /** + * Calculates the Roland GS sysex check sum. + * + * @param AddrReader - reader which currently points to the first GS + * command address byte of the GS sysex message in + * question + * @param DataSize - size of the GS message data (in bytes) + */ + uint8_t Engine::GSCheckSum(const RingBuffer::NonVolatileReader AddrReader, uint DataSize) { + RingBuffer::NonVolatileReader reader = AddrReader; + uint bytes = 3 /*addr*/ + DataSize; + uint8_t addr_and_data[bytes]; + reader.read(&addr_and_data[0], bytes); + uint8_t sum = 0; + for (uint i = 0; i < bytes; i++) sum += addr_and_data[i]; + return 128 - sum % 128; + } + + /** + * Allows to tune each of the twelve semitones of an octave. + * + * @param ScaleTunes - detuning of all twelve semitones (in cents) + */ + void Engine::AdjustScale(int8_t ScaleTunes[12]) { + memcpy(&this->ScaleTuning[0], &ScaleTunes[0], 12); //TODO: currently not sample accurate + } + + /** * Initialize the parameter sequence for the modulation destination given by * by 'dst' with the constant value given by val. */ @@ -669,6 +1010,38 @@ GlobalVolume = f; } + uint Engine::Channels() { + return 2; + } + + void Engine::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) { + AudioChannel* pChannel = pAudioOutputDevice->Channel(AudioDeviceChannel); + if (!pChannel) throw AudioOutputException("Invalid audio output device channel " + ToString(AudioDeviceChannel)); + switch (EngineAudioChannel) { + case 0: // left output channel + pOutputLeft = pChannel->Buffer(); + AudioDeviceChannelLeft = AudioDeviceChannel; + break; + case 1: // right output channel + pOutputRight = pChannel->Buffer(); + AudioDeviceChannelRight = AudioDeviceChannel; + break; + default: + throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel)); + } + } + + int Engine::OutputChannel(uint EngineAudioChannel) { + switch (EngineAudioChannel) { + case 0: // left channel + return AudioDeviceChannelLeft; + case 1: // right channel + return AudioDeviceChannelRight; + default: + throw AudioOutputException("Invalid engine audio channel " + ToString(EngineAudioChannel)); + } + } + uint Engine::VoiceCount() { return ActiveVoiceCount; } @@ -709,12 +1082,17 @@ return InstrumentIdx; } + int Engine::InstrumentStatus() { + return InstrumentStat; + } + String Engine::Description() { return "Gigasampler Engine"; } String Engine::Version() { - return "0.0.1-0cvs20040423"; + String s = "$Revision: 1.14 $"; + return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword } }} // namespace LinuxSampler::gig