--- linuxsampler/trunk/src/engines/gig/Engine.cpp 2004/08/22 14:46:47 225 +++ linuxsampler/trunk/src/engines/gig/Engine.cpp 2004/09/19 14:12:55 246 @@ -37,7 +37,8 @@ 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); @@ -47,11 +48,12 @@ 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); @@ -92,6 +94,7 @@ 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; @@ -154,6 +157,9 @@ ActiveVoiceCountMax = 0; GlobalVolume = 1.0; + // reset to normal chromatic scale (means equal temper) + memset(&ScaleTuning[0], 0x00, 12); + // set all MIDI controller values to zero memset(ControllerTable, 0x00, 128); @@ -161,11 +167,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(); @@ -206,6 +217,9 @@ InstrumentIdx = Instrument; InstrumentStat = 0; + // delete all key groups + ActiveKeyGroups.clear(); + // request gig instrument from instrument manager try { instrument_id_t instrid; @@ -233,6 +247,10 @@ throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file."); } + // 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 @@ -264,7 +282,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(); } @@ -395,21 +413,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; } } @@ -433,7 +455,7 @@ 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 @@ -457,10 +479,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!")); } @@ -473,10 +495,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!")); } @@ -488,9 +510,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!")); } @@ -503,45 +525,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); } /** @@ -553,15 +600,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); } /** @@ -571,20 +626,72 @@ * @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) + */ + void Engine::LaunchVoice(Event* pNoteOnEvent, int iLayer, bool ReleaseTriggerVoice) { + 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) + } + } + else std::cerr << "No free voice!" << std::endl << std::flush; + } + + /** * 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]; @@ -593,9 +700,14 @@ // 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; dmsg(3,("Key has no more voices now\n")); } } @@ -609,11 +721,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; @@ -633,7 +745,7 @@ } } } - if (pControlChangeEvent->Value < 64 && SustainPedal) { + if (pControlChangeEvent->Param.CC.Value < 64 && SustainPedal) { dmsg(4,("PEDAL UP\n")); SustainPedal = false; @@ -658,13 +770,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. */ @@ -768,7 +963,7 @@ } String Engine::Version() { - String s = "$Revision: 1.8 $"; + String s = "$Revision: 1.13 $"; return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword }