--- linuxsampler/trunk/src/engines/gig/EngineChannel.cpp 2005/09/21 19:05:41 776 +++ linuxsampler/trunk/src/engines/gig/EngineChannel.cpp 2014/06/10 13:32:16 2612 @@ -2,8 +2,9 @@ * * * LinuxSampler - modular, streaming capable sampler * * * - * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck * - * Copyright (C) 2005 Christian Schoenebeck * + * Copyright (C) 2003,2004 by Benno Senoner and Christian Schoenebeck * + * Copyright (C) 2005-2008 Christian Schoenebeck * + * Copyright (C) 2009-2012 Christian Schoenebeck and Grigor Iliev * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * @@ -22,127 +23,51 @@ ***************************************************************************/ #include "EngineChannel.h" +#include "Engine.h" namespace LinuxSampler { namespace gig { - EngineChannel::EngineChannel() { - pMIDIKeyInfo = new midi_key_info_t[128]; - pEngine = NULL; - pInstrument = NULL; - pEvents = NULL; // we allocate when we retrieve the right Engine object - pEventQueue = new RingBuffer(CONFIG_MAX_EVENTS_PER_FRAGMENT, 0); - pActiveKeys = new Pool(128); - for (uint i = 0; i < 128; i++) { - pMIDIKeyInfo[i].pActiveVoices = NULL; // we allocate when we retrieve the right Engine object - pMIDIKeyInfo[i].KeyPressed = false; - pMIDIKeyInfo[i].Active = false; - pMIDIKeyInfo[i].ReleaseTrigger = false; - pMIDIKeyInfo[i].pEvents = NULL; // we allocate when we retrieve the right Engine object - pMIDIKeyInfo[i].VoiceTheftsQueued = 0; - pMIDIKeyInfo[i].RoundRobinIndex = 0; - } - InstrumentIdx = -1; - InstrumentStat = -1; - AudioDeviceChannelLeft = -1; - AudioDeviceChannelRight = -1; - pMidiInputPort = NULL; - midiChannel = midi_chan_all; - ResetControllers(); + } EngineChannel::~EngineChannel() { DisconnectAudioOutputDevice(); - if (pInstrument) Engine::instruments.HandBack(pInstrument, this); - if (pEventQueue) delete pEventQueue; - if (pActiveKeys) delete pActiveKeys; - if (pMIDIKeyInfo) delete[] pMIDIKeyInfo; - } - - /** - * Implementation of virtual method from abstract EngineChannel interface. - * This method will periodically be polled (e.g. by the LSCP server) to - * check if some engine channel parameter has changed since the last - * StatusChanged() call. - * - * This method can also be used to mark the engine channel as changed - * from outside, e.g. by a MIDI input device. The optional argument - * \a nNewStatus can be used for this. - * - * TODO: This "poll method" is just a lazy solution and might be - * replaced in future. - * @param bNewStatus - (optional, default: false) sets the new status flag - * @returns true if engine channel status has changed since last - * StatusChanged() call - */ - bool EngineChannel::StatusChanged(bool bNewStatus) { - bool b = bStatusChanged; - bStatusChanged = bNewStatus; - return b; - } - - void EngineChannel::Reset() { - if (pEngine) pEngine->DisableAndLock(); - ResetInternal(); - ResetControllers(); - if (pEngine) { - pEngine->Enable(); - pEngine->Reset(); + // In case the channel was removed before the instrument was + // fully loaded, try to give back instrument again (see bug #113) + InstrumentChangeCmd< ::gig::DimensionRegion, ::gig::Instrument>& cmd = ChangeInstrument(NULL); + if (cmd.pInstrument) { + Engine::instruments.HandBack(cmd.pInstrument, this); } + /////// } - /** - * This method is not thread safe! - */ + AbstractEngine::Format EngineChannel::GetEngineFormat() { return AbstractEngine::GIG; } + + /** This method is not thread safe! */ void EngineChannel::ResetInternal() { CurrentKeyDimension = 0; - - // reset key info - for (uint i = 0; i < 128; i++) { - if (pMIDIKeyInfo[i].pActiveVoices) - pMIDIKeyInfo[i].pActiveVoices->clear(); - if (pMIDIKeyInfo[i].pEvents) - pMIDIKeyInfo[i].pEvents->clear(); - pMIDIKeyInfo[i].KeyPressed = false; - pMIDIKeyInfo[i].Active = false; - pMIDIKeyInfo[i].ReleaseTrigger = false; - pMIDIKeyInfo[i].itSelf = Pool::Iterator(); - pMIDIKeyInfo[i].VoiceTheftsQueued = 0; - } - - // reset all key groups - std::map::iterator iter = ActiveKeyGroups.begin(); - for (; iter != ActiveKeyGroups.end(); iter++) iter->second = NULL; - - // free all active keys - pActiveKeys->clear(); - - // delete all input events - pEventQueue->init(); - - if (pEngine) pEngine->ResetInternal(); - - // status of engine channel has changed, so set notify flag - bStatusChanged = true; - } - - LinuxSampler::Engine* EngineChannel::GetEngine() { - return pEngine; + EngineChannelBase::ResetInternal(); } /** - * More or less a workaround to set the instrument name, index and load - * status variable to zero percent immediately, that is without blocking - * the calling thread. It might be used in future for other preparations - * as well though. + * Will be called by the MIDIIn Thread to signal that a program + * change should be performed. As a program change isn't + * real-time safe, the actual change is performed by the disk + * thread. * - * @param FileName - file name of the Gigasampler instrument file - * @param Instrument - index of the instrument in the .gig file - * @see LoadInstrument() + * @param Program - MIDI program change number */ - void EngineChannel::PrepareLoadInstrument(const char* FileName, uint Instrument) { - InstrumentFile = FileName; - InstrumentIdx = Instrument; - InstrumentStat = 0; + void EngineChannel::SendProgramChange(uint8_t Program) { + SetMidiProgram(Program); + Engine* engine = dynamic_cast(pEngine); + if(engine == NULL) return; + + if(engine->GetDiskThread()) { + uint32_t merged = (GetMidiBankMsb() << 16) | (GetMidiBankLsb() << 8) | Program; + engine->GetDiskThread()->OrderProgramChange(merged, this); + } else { + // TODO: + } } /** @@ -151,365 +76,116 @@ * This method will then actually start to load the instrument and block * the calling thread until loading was completed. * - * @returns detailed description of the method call result * @see PrepareLoadInstrument() */ void EngineChannel::LoadInstrument() { + InstrumentResourceManager* pInstrumentManager = dynamic_cast(pEngine->GetInstrumentManager()); - if (pEngine) pEngine->DisableAndLock(); - - ResetInternal(); - - // free old instrument - if (pInstrument) { - // give old instrument back to instrument manager - Engine::instruments.HandBack(pInstrument, this); + // make sure we don't trigger any new notes with an old + // instrument + InstrumentChangeCmd< ::gig::DimensionRegion, ::gig::Instrument>& cmd = ChangeInstrument(0); + if (cmd.pInstrument) { + // give old instrument back to instrument manager, but + // keep the dimension regions and samples that are in use + pInstrumentManager->HandBackInstrument(cmd.pInstrument, this, cmd.pRegionsInUse); + } + if (cmd.pScript) { + // give old instrument script back to instrument resource manager + cmd.pScript->resetAll(); } + cmd.pRegionsInUse->clear(); // delete all key groups - ActiveKeyGroups.clear(); + DeleteGroupEventLists(); // request gig instrument from instrument manager + ::gig::Instrument* newInstrument; try { - instrument_id_t instrid; - instrid.FileName = InstrumentFile; - instrid.iInstrument = InstrumentIdx; - pInstrument = Engine::instruments.Borrow(instrid, this); - if (!pInstrument) { - InstrumentStat = -1; - dmsg(1,("no instrument loaded!!!\n")); - exit(EXIT_FAILURE); + InstrumentManager::instrument_id_t instrid; + instrid.FileName = InstrumentFile; + instrid.Index = InstrumentIdx; + + newInstrument = pInstrumentManager->Borrow(instrid, this); + if (!newInstrument) { + throw InstrumentManagerException("resource was not created"); + } + + if (newInstrument->ScriptSlotCount() > 1) { + std::cerr << "WARNING: Executing more than one real-time instrument script slot is not implemented yet!\n"; + } + ::gig::Script* script = newInstrument->GetScriptOfSlot(0); + if (script) { + String sourceCode = script->GetScriptAsText(); + LoadInstrumentScript(sourceCode); } } catch (RIFF::Exception e) { InstrumentStat = -2; + StatusChanged(true); String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message; - throw LinuxSamplerException(msg); + throw Exception(msg); } - catch (InstrumentResourceManagerException e) { + catch (InstrumentManagerException e) { InstrumentStat = -3; + StatusChanged(true); String msg = "gig::Engine error: Failed to load instrument, cause: " + e.Message(); - throw LinuxSamplerException(msg); + throw Exception(msg); } catch (...) { InstrumentStat = -4; - throw LinuxSamplerException("gig::Engine error: Failed to load instrument, cause: Unknown exception while trying to parse gig file."); + StatusChanged(true); + throw Exception("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; - - InstrumentIdxName = pInstrument->pInfo->Name; - InstrumentStat = 100; + RoundRobinIndex = 0; + for (int i = 0 ; i < 128 ; i++) pMIDIKeyInfo[i].pRoundRobinIndex = NULL; - // inform audio driver for the need of two channels - try { - if (pEngine && pEngine->pAudioOutputDevice) - pEngine->pAudioOutputDevice->AcquireChannels(2); // gig Engine only stereo - } - catch (AudioOutputException e) { - String msg = "Audio output device unable to provide 2 audio channels, cause: " + e.Message(); - throw LinuxSamplerException(msg); - } + // rebuild ActiveKeyGroups map with key groups of current + // instrument and set the round robin pointers to use one + // counter for each region + int region = 0; + for (::gig::Region* pRegion = newInstrument->GetFirstRegion(); pRegion; pRegion = newInstrument->GetNextRegion()) { + AddGroup(pRegion->KeyGroup); - if (pEngine) pEngine->Enable(); - } - - /** - * Will be called by the InstrumentResourceManager when the instrument - * we are currently using on this EngineChannel is going to be updated, - * so we can stop playback before that happens. - */ - void EngineChannel::ResourceToBeUpdated(::gig::Instrument* pResource, void*& pUpdateArg) { - dmsg(3,("gig::Engine: Received instrument update message.\n")); - if (pEngine) pEngine->DisableAndLock(); - ResetInternal(); - this->pInstrument = NULL; - } - - /** - * Will be called by the InstrumentResourceManager when the instrument - * update process was completed, so we can continue with playback. - */ - void EngineChannel::ResourceUpdated(::gig::Instrument* pOldResource, ::gig::Instrument* pNewResource, void* pUpdateArg) { - this->pInstrument = pNewResource; //TODO: there are couple of engine parameters we should update here as well if the instrument was updated (see LoadInstrument()) - if (pEngine) pEngine->Enable(); - bStatusChanged = true; // status of engine has changed, so set notify flag - } - - /** - * Will be called by the InstrumentResourceManager on progress changes - * while loading or realoading an instrument for this EngineChannel. - * - * @param fProgress - current progress as value between 0.0 and 1.0 - */ - void EngineChannel::OnResourceProgress(float fProgress) { - this->InstrumentStat = int(fProgress * 100.0f); - dmsg(7,("gig::EngineChannel: progress %d%", InstrumentStat)); - bStatusChanged = true; // status of engine has changed, so set notify flag - } - - void EngineChannel::Connect(AudioOutputDevice* pAudioOut) { - if (pEngine) { - if (pEngine->pAudioOutputDevice == pAudioOut) return; - DisconnectAudioOutputDevice(); - } - pEngine = Engine::AcquireEngine(this, pAudioOut); - ResetInternal(); - pEvents = new RTList(pEngine->pEventPool); - for (uint i = 0; i < 128; i++) { - pMIDIKeyInfo[i].pActiveVoices = new RTList(pEngine->pVoicePool); - pMIDIKeyInfo[i].pEvents = new RTList(pEngine->pEventPool); - } - AudioDeviceChannelLeft = 0; - AudioDeviceChannelRight = 1; - pOutputLeft = pAudioOut->Channel(0)->Buffer(); - pOutputRight = pAudioOut->Channel(1)->Buffer(); - } - - void EngineChannel::DisconnectAudioOutputDevice() { - if (pEngine) { // if clause to prevent disconnect loops - ResetInternal(); - if (pEvents) { - delete pEvents; - pEvents = NULL; + RoundRobinIndexes[region] = 0; + for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) { + pMIDIKeyInfo[iKey].pRoundRobinIndex = &RoundRobinIndexes[region]; } - for (uint i = 0; i < 128; i++) { - if (pMIDIKeyInfo[i].pActiveVoices) { - delete pMIDIKeyInfo[i].pActiveVoices; - pMIDIKeyInfo[i].pActiveVoices = NULL; - } - if (pMIDIKeyInfo[i].pEvents) { - delete pMIDIKeyInfo[i].pEvents; - pMIDIKeyInfo[i].pEvents = NULL; - } - } - Engine* oldEngine = pEngine; - AudioOutputDevice* oldAudioDevice = pEngine->pAudioOutputDevice; - pEngine = NULL; - Engine::FreeEngine(this, oldAudioDevice); - AudioDeviceChannelLeft = -1; - AudioDeviceChannelRight = -1; - } - } - - void EngineChannel::SetOutputChannel(uint EngineAudioChannel, uint AudioDeviceChannel) { - if (!pEngine || !pEngine->pAudioOutputDevice) throw AudioOutputException("No audio output device connected yet."); - - AudioChannel* pChannel = pEngine->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 EngineChannel::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)); - } - } - - void EngineChannel::Connect(MidiInputPort* pMidiPort, midi_chan_t MidiChannel) { - if (!pMidiPort || pMidiPort == this->pMidiInputPort) return; - DisconnectMidiInputPort(); - this->pMidiInputPort = pMidiPort; - this->midiChannel = MidiChannel; - pMidiPort->Connect(this, MidiChannel); - } - - void EngineChannel::DisconnectMidiInputPort() { - MidiInputPort* pOldPort = this->pMidiInputPort; - this->pMidiInputPort = NULL; - if (pOldPort) pOldPort->Disconnect(this); - } - - MidiInputPort* EngineChannel::GetMidiInputPort() { - return pMidiInputPort; - } - - midi_chan_t EngineChannel::MidiChannel() { - return midiChannel; - } - - /** - * Will be called by the MIDIIn Thread to let the audio thread trigger a new - * voice for the given key. - * - * @param Key - MIDI key number of the triggered key - * @param Velocity - MIDI velocity value of the triggered key - */ - void EngineChannel::SendNoteOn(uint8_t Key, uint8_t Velocity) { - if (pEngine) { - Event event = pEngine->pEventGenerator->CreateEvent(); - event.Type = Event::type_note_on; - event.Param.Note.Key = Key; - event.Param.Note.Velocity = Velocity; - event.pEngineChannel = this; - if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event); - else dmsg(1,("EngineChannel: Input event queue full!")); + region++; } - } - /** - * Will be called by the MIDIIn Thread to signal the audio thread to release - * voice(s) on the given key. - * - * @param Key - MIDI key number of the released key - * @param Velocity - MIDI release velocity value of the released key - */ - void EngineChannel::SendNoteOff(uint8_t Key, uint8_t Velocity) { - if (pEngine) { - Event event = pEngine->pEventGenerator->CreateEvent(); - event.Type = Event::type_note_off; - event.Param.Note.Key = Key; - event.Param.Note.Velocity = Velocity; - event.pEngineChannel = this; - if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event); - else dmsg(1,("EngineChannel: Input event queue full!")); - } - } + InstrumentIdxName = newInstrument->pInfo->Name; + InstrumentStat = 100; - /** - * Will be called by the MIDIIn Thread to signal the audio thread to change - * the pitch value for all voices. - * - * @param Pitch - MIDI pitch value (-8192 ... +8191) - */ - void EngineChannel::SendPitchbend(int Pitch) { - if (pEngine) { - Event event = pEngine->pEventGenerator->CreateEvent(); - event.Type = Event::type_pitchbend; - event.Param.Pitch.Pitch = Pitch; - event.pEngineChannel = this; - if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event); - else dmsg(1,("EngineChannel: Input event queue full!")); + cmd = ChangeInstrument(newInstrument); + if (cmd.pScript) { + // give old instrument script back to instrument resource manager + cmd.pScript->resetAll(); } - } - /** - * Will be called by the MIDIIn Thread to signal the audio thread that a - * continuous controller value has changed. - * - * @param Controller - MIDI controller number of the occured control change - * @param Value - value of the control change - */ - void EngineChannel::SendControlChange(uint8_t Controller, uint8_t Value) { - if (pEngine) { - Event event = pEngine->pEventGenerator->CreateEvent(); - event.Type = Event::type_control_change; - event.Param.CC.Controller = Controller; - event.Param.CC.Value = Value; - event.pEngineChannel = this; - if (this->pEventQueue->write_space() > 0) this->pEventQueue->push(&event); - else dmsg(1,("EngineChannel: Input event queue full!")); - } + StatusChanged(true); } - void EngineChannel::ClearEventLists() { - pEvents->clear(); - // empty MIDI key specific event lists + void EngineChannel::ProcessKeySwitchChange(int key) { + // Change key dimension value if key is in keyswitching area { - RTList::Iterator iuiKey = pActiveKeys->first(); - RTList::Iterator end = pActiveKeys->end(); - for(; iuiKey != end; ++iuiKey) { - pMIDIKeyInfo[*iuiKey].pEvents->clear(); // free all events on the key - } + if (key >= pInstrument->DimensionKeyRange.low && key <= pInstrument->DimensionKeyRange.high) + CurrentKeyDimension = float(key - pInstrument->DimensionKeyRange.low) / + (pInstrument->DimensionKeyRange.high - pInstrument->DimensionKeyRange.low + 1); } } - - void EngineChannel::ResetControllers() { - Pitch = 0; - SustainPedal = false; - SostenutoPedal = false; - GlobalVolume = 1.0; - GlobalPanLeft = 1.0f; - GlobalPanRight = 1.0f; - // set all MIDI controller values to zero - memset(ControllerTable, 0x00, 128); - } - - /** - * Copy all events from the engine channel's input event queue buffer to - * the internal event list. This will be done at the beginning of each - * audio cycle (that is each RenderAudio() call) to distinguish all - * events which have to be processed in the current audio cycle. Each - * EngineChannel has it's own input event queue for the common channel - * specific events (like NoteOn, NoteOff and ControlChange events). - * Beside that, the engine also has a input event queue for global - * events (usually SysEx messages). - * - * @param Samples - number of sample points to be processed in the - * current audio cycle - */ - void EngineChannel::ImportEvents(uint Samples) { - RingBuffer::NonVolatileReader eventQueueReader = pEventQueue->get_non_volatile_reader(); - Event* pEvent; - while (true) { - // get next event from input event queue - if (!(pEvent = eventQueueReader.pop())) break; - // if younger event reached, ignore that and all subsequent ones for now - if (pEvent->FragmentPos() >= Samples) { - eventQueueReader--; - dmsg(2,("Younger Event, pos=%d ,Samples=%d!\n",pEvent->FragmentPos(),Samples)); - pEvent->ResetFragmentPos(); - break; - } - // copy event to internal event list - if (pEvents->poolIsEmpty()) { - dmsg(1,("Event pool emtpy!\n")); - break; - } - *pEvents->allocAppend() = *pEvent; - } - eventQueueReader.free(); // free all copied events from input queue - } - - float EngineChannel::Volume() { - return GlobalVolume; - } - - void EngineChannel::Volume(float f) { - GlobalVolume = f; - bStatusChanged = true; // status of engine channel has changed, so set notify flag - } - - uint EngineChannel::Channels() { - return 2; - } - + String EngineChannel::InstrumentFileName() { - return InstrumentFile; + return EngineChannelBase::InstrumentFileName(); } - - String EngineChannel::InstrumentName() { - return InstrumentIdxName; - } - - int EngineChannel::InstrumentIndex() { - return InstrumentIdx; - } - - int EngineChannel::InstrumentStatus() { - return InstrumentStat; - } - - String EngineChannel::EngineName() { - return LS_GIG_ENGINE_NAME; + + String EngineChannel::InstrumentFileName(int index) { + if (index == 0) return InstrumentFileName(); + if (!pInstrument || !pInstrument->GetParent()) return ""; + DLS::File* pMainFile = dynamic_cast(pInstrument->GetParent()); + if (!pMainFile) return ""; + RIFF::File* pExtensionFile = pMainFile->GetExtensionFile(index); + return (pExtensionFile) ? pExtensionFile->GetFileName() : ""; } }} // namespace LinuxSampler::gig