--- linuxsampler/trunk/src/network/lscpserver.cpp 2007/12/03 16:41:17 1536 +++ linuxsampler/trunk/src/network/lscpserver.cpp 2014/03/03 12:02:40 2528 @@ -3,7 +3,7 @@ * LinuxSampler - modular, streaming capable sampler * * * * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck * - * Copyright (C) 2005 - 2007 Christian Schoenebeck * + * Copyright (C) 2005 - 2014 Christian Schoenebeck * * * * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * @@ -21,11 +21,16 @@ * MA 02111-1307 USA * ***************************************************************************/ +#include +#include + +#include "../common/File.h" #include "lscpserver.h" #include "lscpresultset.h" #include "lscpevent.h" #if defined(WIN32) +#include #else #include #endif @@ -38,7 +43,11 @@ #include "../engines/EngineChannelFactory.h" #include "../drivers/audio/AudioOutputDeviceFactory.h" #include "../drivers/midi/MidiInputDeviceFactory.h" +#include "../effects/EffectFactory.h" + +namespace LinuxSampler { +String lscpParserProcessShellInteraction(String& line, yyparse_param_t* param, bool possibilities); /** * Returns a copy of the given string where all special characters are @@ -90,17 +99,17 @@ */ fd_set LSCPServer::fdSet; int LSCPServer::currentSocket = -1; -std::vector LSCPServer::Sessions = std::vector(); -std::vector::iterator itCurrentSession = std::vector::iterator(); -std::map LSCPServer::bufferedNotifies = std::map(); -std::map LSCPServer::bufferedCommands = std::map(); -std::map< LSCPEvent::event_t, std::list > LSCPServer::eventSubscriptions = std::map< LSCPEvent::event_t, std::list >(); -Mutex LSCPServer::NotifyMutex = Mutex(); -Mutex LSCPServer::NotifyBufferMutex = Mutex(); -Mutex LSCPServer::SubscriptionMutex = Mutex(); -Mutex LSCPServer::RTNotifyMutex = Mutex(); +std::vector LSCPServer::Sessions; +std::vector::iterator itCurrentSession; +std::map LSCPServer::bufferedNotifies; +std::map LSCPServer::bufferedCommands; +std::map< LSCPEvent::event_t, std::list > LSCPServer::eventSubscriptions; +Mutex LSCPServer::NotifyMutex; +Mutex LSCPServer::NotifyBufferMutex; +Mutex LSCPServer::SubscriptionMutex; +Mutex LSCPServer::RTNotifyMutex; -LSCPServer::LSCPServer(Sampler* pSampler, long int addr, short int port) : Thread(true, false, 0, -4) { +LSCPServer::LSCPServer(Sampler* pSampler, long int addr, short int port) : Thread(true, false, 0, -4), eventHandler(this) { SocketAddress.sin_family = AF_INET; SocketAddress.sin_addr.s_addr = addr; SocketAddress.sin_port = port; @@ -126,12 +135,21 @@ LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO"); LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO"); LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS"); + LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT"); LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT"); LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO"); + LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI"); + LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI"); + LSCPEvent::RegisterEvent(LSCPEvent::event_fx_instance_count, "EFFECT_INSTANCE_COUNT"); + LSCPEvent::RegisterEvent(LSCPEvent::event_fx_instance_info, "EFFECT_INSTANCE_INFO"); + LSCPEvent::RegisterEvent(LSCPEvent::event_send_fx_chain_count, "SEND_EFFECT_CHAIN_COUNT"); + LSCPEvent::RegisterEvent(LSCPEvent::event_send_fx_chain_info, "SEND_EFFECT_CHAIN_INFO"); hSocket = -1; } LSCPServer::~LSCPServer() { + CloseAllConnections(); + InstrumentManager::StopBackgroundThread(); #if defined(WIN32) if (hSocket >= 0) closesocket(hSocket); #else @@ -139,10 +157,63 @@ #endif } +LSCPServer::EventHandler::EventHandler(LSCPServer* pParent) { + this->pParent = pParent; +} + +LSCPServer::EventHandler::~EventHandler() { + std::vector l = channelMidiListeners; + channelMidiListeners.clear(); + for (int i = 0; i < l.size(); i++) + delete l[i].pMidiListener; +} + void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) { LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount)); } +void LSCPServer::EventHandler::ChannelAdded(SamplerChannel* pChannel) { + pChannel->AddEngineChangeListener(this); +} + +void LSCPServer::EventHandler::ChannelToBeRemoved(SamplerChannel* pChannel) { + if (!pChannel->GetEngineChannel()) return; + EngineToBeChanged(pChannel->Index()); +} + +void LSCPServer::EventHandler::EngineToBeChanged(int ChannelId) { + SamplerChannel* pSamplerChannel = + pParent->pSampler->GetSamplerChannel(ChannelId); + if (!pSamplerChannel) return; + EngineChannel* pEngineChannel = + pSamplerChannel->GetEngineChannel(); + if (!pEngineChannel) return; + for (std::vector::iterator iter = channelMidiListeners.begin(); iter != channelMidiListeners.end(); ++iter) { + if ((*iter).pEngineChannel == pEngineChannel) { + VirtualMidiDevice* pMidiListener = (*iter).pMidiListener; + pEngineChannel->Disconnect(pMidiListener); + channelMidiListeners.erase(iter); + delete pMidiListener; + return; + } + } +} + +void LSCPServer::EventHandler::EngineChanged(int ChannelId) { + SamplerChannel* pSamplerChannel = + pParent->pSampler->GetSamplerChannel(ChannelId); + if (!pSamplerChannel) return; + EngineChannel* pEngineChannel = + pSamplerChannel->GetEngineChannel(); + if (!pEngineChannel) return; + VirtualMidiDevice* pMidiListener = new VirtualMidiDevice; + pEngineChannel->Connect(pMidiListener); + midi_listener_entry entry = { + pSamplerChannel, pEngineChannel, pMidiListener + }; + channelMidiListeners.push_back(entry); +} + void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) { LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount)); } @@ -151,6 +222,54 @@ LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount)); } +void LSCPServer::EventHandler::MidiDeviceToBeDestroyed(MidiInputDevice* pDevice) { + pDevice->RemoveMidiPortCountListener(this); + for (int i = 0; i < pDevice->PortCount(); ++i) + MidiPortToBeRemoved(pDevice->GetPort(i)); +} + +void LSCPServer::EventHandler::MidiDeviceCreated(MidiInputDevice* pDevice) { + pDevice->AddMidiPortCountListener(this); + for (int i = 0; i < pDevice->PortCount(); ++i) + MidiPortAdded(pDevice->GetPort(i)); +} + +void LSCPServer::EventHandler::MidiPortCountChanged(int NewCount) { + // yet unused +} + +void LSCPServer::EventHandler::MidiPortToBeRemoved(MidiInputPort* pPort) { + for (std::vector::iterator iter = deviceMidiListeners.begin(); iter != deviceMidiListeners.end(); ++iter) { + if ((*iter).pPort == pPort) { + VirtualMidiDevice* pMidiListener = (*iter).pMidiListener; + pPort->Disconnect(pMidiListener); + deviceMidiListeners.erase(iter); + delete pMidiListener; + return; + } + } +} + +void LSCPServer::EventHandler::MidiPortAdded(MidiInputPort* pPort) { + // find out the device ID + std::map devices = + pParent->pSampler->GetMidiInputDevices(); + for ( + std::map::iterator iter = devices.begin(); + iter != devices.end(); ++iter + ) { + if (iter->second == pPort->GetDevice()) { // found + VirtualMidiDevice* pMidiListener = new VirtualMidiDevice; + pPort->Connect(pMidiListener); + device_midi_listener_entry entry = { + pPort, pMidiListener, iter->first + }; + deviceMidiListeners.push_back(entry); + return; + } + } +} + void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) { LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount)); } @@ -187,6 +306,10 @@ LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount)); } +void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) { + LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount)); +} + #if HAVE_SQLITE3 void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) { LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir))); @@ -221,6 +344,24 @@ } #endif // HAVE_SQLITE3 +void LSCPServer::RemoveListeners() { + pSampler->RemoveChannelCountListener(&eventHandler); + pSampler->RemoveAudioDeviceCountListener(&eventHandler); + pSampler->RemoveMidiDeviceCountListener(&eventHandler); + pSampler->RemoveVoiceCountListener(&eventHandler); + pSampler->RemoveStreamCountListener(&eventHandler); + pSampler->RemoveBufferFillListener(&eventHandler); + pSampler->RemoveTotalStreamCountListener(&eventHandler); + pSampler->RemoveTotalVoiceCountListener(&eventHandler); + pSampler->RemoveFxSendCountListener(&eventHandler); + MidiInstrumentMapper::RemoveMidiInstrumentCountListener(&eventHandler); + MidiInstrumentMapper::RemoveMidiInstrumentInfoListener(&eventHandler); + MidiInstrumentMapper::RemoveMidiInstrumentMapCountListener(&eventHandler); + MidiInstrumentMapper::RemoveMidiInstrumentMapInfoListener(&eventHandler); +#if HAVE_SQLITE3 + InstrumentsDb::GetInstrumentsDb()->RemoveInstrumentsDbListener(&dbInstrumentsEventHandler); +#endif +} /** * Blocks the calling thread until the LSCP Server is initialized and @@ -283,6 +424,7 @@ pSampler->AddVoiceCountListener(&eventHandler); pSampler->AddStreamCountListener(&eventHandler); pSampler->AddBufferFillListener(&eventHandler); + pSampler->AddTotalStreamCountListener(&eventHandler); pSampler->AddTotalVoiceCountListener(&eventHandler); pSampler->AddFxSendCountListener(&eventHandler); MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler); @@ -302,20 +444,24 @@ timeval timeout; while (true) { + #if CONFIG_PTHREAD_TESTCANCEL + TestCancel(); + #endif // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers { + LockGuard lock(EngineChannelFactory::EngineChannelsMutex); std::set engineChannels = EngineChannelFactory::EngineChannelInstances(); std::set::iterator itEngineChannel = engineChannels.begin(); std::set::iterator itEnd = engineChannels.end(); for (; itEngineChannel != itEnd; ++itEngineChannel) { if ((*itEngineChannel)->StatusChanged()) { - SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex)); + SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->GetSamplerChannel()->Index())); } for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) { FxSend* fxs = (*itEngineChannel)->GetFxSend(i); if(fxs != NULL && fxs->IsInfoChanged()) { - int chn = (*itEngineChannel)->iSamplerChannelIndex; + int chn = (*itEngineChannel)->GetSamplerChannel()->Index(); LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id())); fxs->SetInfoChanged(false); } @@ -323,17 +469,67 @@ } } - //Now let's deliver late notifies (if any) - NotifyBufferMutex.Lock(); - for (std::map::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) { + // check if MIDI data arrived on some engine channel + for (int i = 0; i < eventHandler.channelMidiListeners.size(); ++i) { + const EventHandler::midi_listener_entry entry = + eventHandler.channelMidiListeners[i]; + VirtualMidiDevice* pMidiListener = entry.pMidiListener; + if (pMidiListener->NotesChanged()) { + for (int iNote = 0; iNote < 128; iNote++) { + if (pMidiListener->NoteChanged(iNote)) { + const bool bActive = pMidiListener->NoteIsActive(iNote); + LSCPServer::SendLSCPNotify( + LSCPEvent( + LSCPEvent::event_channel_midi, + entry.pSamplerChannel->Index(), + std::string(bActive ? "NOTE_ON" : "NOTE_OFF"), + iNote, + bActive ? pMidiListener->NoteOnVelocity(iNote) + : pMidiListener->NoteOffVelocity(iNote) + ) + ); + } + } + } + } + + // check if MIDI data arrived on some MIDI device + for (int i = 0; i < eventHandler.deviceMidiListeners.size(); ++i) { + const EventHandler::device_midi_listener_entry entry = + eventHandler.deviceMidiListeners[i]; + VirtualMidiDevice* pMidiListener = entry.pMidiListener; + if (pMidiListener->NotesChanged()) { + for (int iNote = 0; iNote < 128; iNote++) { + if (pMidiListener->NoteChanged(iNote)) { + const bool bActive = pMidiListener->NoteIsActive(iNote); + LSCPServer::SendLSCPNotify( + LSCPEvent( + LSCPEvent::event_device_midi, + entry.uiDeviceID, + entry.pPort->GetPortNumber(), + std::string(bActive ? "NOTE_ON" : "NOTE_OFF"), + iNote, + bActive ? pMidiListener->NoteOnVelocity(iNote) + : pMidiListener->NoteOffVelocity(iNote) + ) + ); + } + } + } + } + + //Now let's deliver late notifies (if any) + { + LockGuard lock(NotifyBufferMutex); + for (std::map::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) { #ifdef MSG_NOSIGNAL - send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), MSG_NOSIGNAL); + send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), MSG_NOSIGNAL); #else - send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0); + send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0); #endif - } - bufferedNotifies.clear(); - NotifyBufferMutex.Unlock(); + } + bufferedNotifies.clear(); + } fd_set selectSet = fdSet; timeout.tv_sec = 0; @@ -341,7 +537,7 @@ int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout); - if (retval == 0) + if (retval == 0 || (retval == -1 && errno == EINTR)) continue; //Nothing try again if (retval == -1) { std::cerr << "LSCPServer: Socket select error." << std::endl; @@ -368,6 +564,13 @@ exit(EXIT_FAILURE); } #else + struct linger linger; + linger.l_onoff = 1; + linger.l_linger = 0; + if(setsockopt(socket, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger))) { + std::cerr << "LSCPServer: Failed to set SO_LINGER\n"; + } + if (fcntl(socket, F_SETFL, O_NONBLOCK)) { std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl; exit(EXIT_FAILURE); @@ -391,11 +594,11 @@ //Something was selected and it was not the hSocket, so it must be some command(s) coming. for (std::vector::iterator iter = Sessions.begin(); iter != Sessions.end(); iter++) { if (FD_ISSET((*iter).hSession, &selectSet)) { //Was it this socket? + currentSocket = (*iter).hSession; //a hack if (GetLSCPCommand(iter)) { //Have we read the entire command? dmsg(3,("LSCPServer: Got command on socket %d, calling parser.\n", currentSocket)); int dummy; // just a temporary hack to fulfill the restart() function prototype restart(NULL, dummy); // restart the 'scanner' - currentSocket = (*iter).hSession; //a hack itCurrentSession = iter; // another hack dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str())); if ((*iter).bVerbose) { // if echo mode enabled @@ -409,6 +612,7 @@ CloseConnection(iter); } } + currentSocket = -1; //continuation of a hack //socket may have been closed, iter may be invalid, get out of the loop for now. //we'll be back if there is data. break; @@ -423,12 +627,14 @@ LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection terminated on socket", socket)); Sessions.erase(iter); FD_CLR(socket, &fdSet); - SubscriptionMutex.Lock(); //Must unsubscribe this socket from all events (if any) - for (std::map< LSCPEvent::event_t, std::list >::iterator iter = eventSubscriptions.begin(); iter != eventSubscriptions.end(); iter++) { - iter->second.remove(socket); - } - SubscriptionMutex.Unlock(); - NotifyMutex.Lock(); + { + LockGuard lock(SubscriptionMutex); + // Must unsubscribe this socket from all events (if any) + for (std::map< LSCPEvent::event_t, std::list >::iterator iter = eventSubscriptions.begin(); iter != eventSubscriptions.end(); iter++) { + iter->second.remove(socket); + } + } + LockGuard lock(NotifyMutex); bufferedCommands.erase(socket); bufferedNotifies.erase(socket); #if defined(WIN32) @@ -436,25 +642,31 @@ #else close(socket); #endif - NotifyMutex.Unlock(); +} + +void LSCPServer::CloseAllConnections() { + std::vector::iterator iter = Sessions.begin(); + while(iter != Sessions.end()) { + CloseConnection(iter); + iter = Sessions.begin(); + } } int LSCPServer::EventSubscribers( std::list events ) { int subs = 0; - SubscriptionMutex.Lock(); + LockGuard lock(SubscriptionMutex); for( std::list::iterator iter = events.begin(); iter != events.end(); iter++) { subs += eventSubscriptions.count(*iter); } - SubscriptionMutex.Unlock(); return subs; } void LSCPServer::SendLSCPNotify( LSCPEvent event ) { - SubscriptionMutex.Lock(); + LockGuard lock(SubscriptionMutex); if (eventSubscriptions.count(event.GetType()) == 0) { - SubscriptionMutex.Unlock(); //Nobody is subscribed to this event + // Nobody is subscribed to this event return; } std::list::iterator iter = eventSubscriptions[event.GetType()].begin(); @@ -480,7 +692,6 @@ } } } - SubscriptionMutex.Unlock(); } extern int GetLSCPCommand( void *buf, int max_size ) { @@ -511,78 +722,112 @@ */ bool LSCPServer::GetLSCPCommand( std::vector::iterator iter ) { int socket = (*iter).hSession; + int result; char c; - int i = 0; + std::vector input; + + // first get as many character as possible and add it to the 'input' buffer while (true) { #if defined(WIN32) - int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now + result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now #else - int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now + result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now #endif - if (result == 0) { //socket was selected, so 0 here means client has closed the connection - CloseConnection(iter); - break; + if (result == 1) input.push_back(c); + else break; // end of input or some error + if (c == '\n') break; // process line by line + } + + // process input buffer + for (int i = 0; i < input.size(); ++i) { + c = input[i]; + if (c == '\r') continue; //Ignore CR + if (c == '\n') { + // only if the other side is the LSCP shell application: + // check the current (incomplete) command line for syntax errors, + // possible completions and report everything back to the shell + if ((*iter).bShellInteract || (*iter).bShellAutoCorrect) { + String s = lscpParserProcessShellInteraction(bufferedCommands[socket], &(*iter), false); + if (!s.empty() && (*iter).bShellInteract) AnswerClient(s + "\n"); + } + + LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Received \'" + bufferedCommands[socket] + "\' on socket", socket)); + bufferedCommands[socket] += "\r\n"; + return true; //Complete command was read } - if (result == 1) { - if (c == '\r') - continue; //Ignore CR - if (c == '\n') { - LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Received \'" + bufferedCommands[socket] + "\' on socket", socket)); - bufferedCommands[socket] += "\r\n"; - return true; //Complete command was read + // backspace character - should only happen with shell + if (c == '\b') { + if (!bufferedCommands[socket].empty()) { + bufferedCommands[socket] = bufferedCommands[socket].substr( + 0, bufferedCommands[socket].length() - 1 + ); } - bufferedCommands[socket] += c; + } else bufferedCommands[socket] += c; + // only if the other side is the LSCP shell application: + // check the current (incomplete) command line for syntax errors, + // possible completions and report everything back to the shell + if ((*iter).bShellInteract || (*iter).bShellAutoCorrect) { + String s = lscpParserProcessShellInteraction(bufferedCommands[socket], &(*iter), true); + if (!s.empty() && (*iter).bShellInteract && i == input.size() - 1) + AnswerClient(s + "\n"); } - #if defined(WIN32) - if (result == SOCKET_ERROR) { - int wsa_lasterror = WSAGetLastError(); - if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later. + } + + // handle network errors ... + if (result == 0) { //socket was selected, so 0 here means client has closed the connection + CloseConnection(iter); + return false; + } + #if defined(WIN32) + if (result == SOCKET_ERROR) { + int wsa_lasterror = WSAGetLastError(); + if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later. + return false; + dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror)); + CloseConnection(iter); + return false; + } + #else + if (result == -1) { + if (errno == EAGAIN) //Would block, try again later. + return false; + switch(errno) { + case EBADF: + dmsg(2,("LSCPScanner: The argument s is an invalid descriptor.\n")); return false; - dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror)); - CloseConnection(iter); - break; - } - #else - if (result == -1) { - if (errno == EAGAIN) //Would block, try again later. + case ECONNREFUSED: + dmsg(2,("LSCPScanner: A remote host refused to allow the network connection (typically because it is not running the requested service).\n")); + return false; + case ENOTCONN: + dmsg(2,("LSCPScanner: The socket is associated with a connection-oriented protocol and has not been connected (see connect(2) and accept(2)).\n")); + return false; + case ENOTSOCK: + dmsg(2,("LSCPScanner: The argument s does not refer to a socket.\n")); + return false; + case EAGAIN: + dmsg(2,("LSCPScanner: The socket is marked non-blocking and the receive operation would block, or a receive timeout had been set and the timeout expired before data was received.\n")); + return false; + case EINTR: + dmsg(2,("LSCPScanner: The receive was interrupted by delivery of a signal before any data were available.\n")); + return false; + case EFAULT: + dmsg(2,("LSCPScanner: The receive buffer pointer(s) point outside the process's address space.\n")); + return false; + case EINVAL: + dmsg(2,("LSCPScanner: Invalid argument passed.\n")); + return false; + case ENOMEM: + dmsg(2,("LSCPScanner: Could not allocate memory for recvmsg.\n")); + return false; + default: + dmsg(2,("LSCPScanner: Unknown recv() error.\n")); return false; - switch(errno) { - case EBADF: - dmsg(2,("LSCPScanner: The argument s is an invalid descriptor.\n")); - break; - case ECONNREFUSED: - dmsg(2,("LSCPScanner: A remote host refused to allow the network connection (typically because it is not running the requested service).\n")); - break; - case ENOTCONN: - dmsg(2,("LSCPScanner: The socket is associated with a connection-oriented protocol and has not been connected (see connect(2) and accept(2)).\n")); - break; - case ENOTSOCK: - dmsg(2,("LSCPScanner: The argument s does not refer to a socket.\n")); - break; - case EAGAIN: - dmsg(2,("LSCPScanner: The socket is marked non-blocking and the receive operation would block, or a receive timeout had been set and the timeout expired before data was received.\n")); - break; - case EINTR: - dmsg(2,("LSCPScanner: The receive was interrupted by delivery of a signal before any data were available.\n")); - break; - case EFAULT: - dmsg(2,("LSCPScanner: The receive buffer pointer(s) point outside the process's address space.\n")); - break; - case EINVAL: - dmsg(2,("LSCPScanner: Invalid argument passed.\n")); - break; - case ENOMEM: - dmsg(2,("LSCPScanner: Could not allocate memory for recvmsg.\n")); - break; - default: - dmsg(2,("LSCPScanner: Unknown recv() error.\n")); - break; - } - CloseConnection(iter); - break; } - #endif + CloseConnection(iter); + return false; } + #endif + return false; } @@ -593,15 +838,34 @@ * @param ReturnMessage - message that will be send to the client */ void LSCPServer::AnswerClient(String ReturnMessage) { - dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str())); + dmsg(2,("LSCPServer::AnswerClient(ReturnMessage='%s')", ReturnMessage.c_str())); if (currentSocket != -1) { - NotifyMutex.Lock(); + LockGuard lock(NotifyMutex); + + // just if other side is LSCP shell: in case respose is a multi-line + // one, then inform client about it before sending the actual mult-line + // response + if (GetCurrentYaccSession()->bShellInteract) { + // check if this is a multi-line response + int n = 0; + for (int i = 0; i < ReturnMessage.size(); ++i) + if (ReturnMessage[i] == '\n') ++n; + if (n >= 2) { + dmsg(2,("LSCP Shell <- expect mult-line response\n")); + String s = LSCP_SHK_EXPECT_MULTI_LINE "\r\n"; +#ifdef MSG_NOSIGNAL + send(currentSocket, s.c_str(), s.size(), MSG_NOSIGNAL); +#else + send(currentSocket, s.c_str(), s.size(), 0); +#endif + } + } + #ifdef MSG_NOSIGNAL send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), MSG_NOSIGNAL); #else send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0); #endif - NotifyMutex.Unlock(); } } @@ -751,10 +1015,9 @@ try { SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); - LockRTNotify(); + LockGuard lock(RTNotifyMutex); pSamplerChannel->SetEngineType(EngineName); if(HasSoloChannel()) pSamplerChannel->GetEngineChannel()->SetMute(-1); - UnlockRTNotify(); } catch (Exception e) { result.Error(e); @@ -794,9 +1057,11 @@ */ String LSCPServer::AddChannel() { dmsg(2,("LSCPServer: AddChannel()\n")); - LockRTNotify(); - SamplerChannel* pSamplerChannel = pSampler->AddSamplerChannel(); - UnlockRTNotify(); + SamplerChannel* pSamplerChannel; + { + LockGuard lock(RTNotifyMutex); + pSamplerChannel = pSampler->AddSamplerChannel(); + } LSCPResultSet result(pSamplerChannel->Index()); return result.Produce(); } @@ -807,9 +1072,10 @@ String LSCPServer::RemoveChannel(uint uiSamplerChannel) { dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel)); LSCPResultSet result; - LockRTNotify(); - pSampler->RemoveSamplerChannel(uiSamplerChannel); - UnlockRTNotify(); + { + LockGuard lock(RTNotifyMutex); + pSampler->RemoveSamplerChannel(uiSamplerChannel); + } return result.Produce(); } @@ -852,17 +1118,18 @@ String LSCPServer::GetEngineInfo(String EngineName) { dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str())); LSCPResultSet result; - LockRTNotify(); - try { - Engine* pEngine = EngineFactory::Create(EngineName); - result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description())); - result.Add("VERSION", pEngine->Version()); - EngineFactory::Destroy(pEngine); - } - catch (Exception e) { - result.Error(e); + { + LockGuard lock(RTNotifyMutex); + try { + Engine* pEngine = EngineFactory::Create(EngineName); + result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description())); + result.Add("VERSION", pEngine->Version()); + EngineFactory::Destroy(pEngine); + } + catch (Exception e) { + result.Error(e); + } } - UnlockRTNotify(); return result.Produce(); } @@ -961,10 +1228,7 @@ dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); - if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); - EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel(); - if (!pEngineChannel) throw Exception("No engine loaded on sampler channel"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel"); result.Add(pEngineChannel->GetEngine()->VoiceCount()); } @@ -982,10 +1246,7 @@ dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); - if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); - EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel(); - if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel"); result.Add(pEngineChannel->GetEngine()->DiskStreamCount()); } @@ -1003,10 +1264,7 @@ dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); - if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); - EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel(); - if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel"); if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA"); else { @@ -1094,6 +1352,7 @@ for (;iter != parameters.end(); iter++) { if (s != "") s += ","; s += iter->first; + delete iter->second; } result.Add("PARAMETERS", s); } @@ -1118,6 +1377,7 @@ for (;iter != parameters.end(); iter++) { if (s != "") s += ","; s += iter->first; + delete iter->second; } result.Add("PARAMETERS", s); } @@ -1148,6 +1408,7 @@ if (oRangeMin) result.Add("RANGE_MIN", *oRangeMin); if (oRangeMax) result.Add("RANGE_MAX", *oRangeMax); if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities); + delete pParameter; } catch (Exception e) { result.Error(e); @@ -1175,6 +1436,7 @@ if (oRangeMin) result.Add("RANGE_MIN", *oRangeMin); if (oRangeMax) result.Add("RANGE_MAX", *oRangeMax); if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities); + delete pParameter; } catch (Exception e) { result.Error(e); @@ -1516,58 +1778,160 @@ String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) { dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel)); LSCPResultSet result; - LockRTNotify(); + { + LockGuard lock(RTNotifyMutex); + try { + SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); + if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); + std::map devices = pSampler->GetAudioOutputDevices(); + if (!devices.count(AudioDeviceId)) throw Exception("There is no audio output device with index " + ToString(AudioDeviceId)); + AudioOutputDevice* pDevice = devices[AudioDeviceId]; + pSamplerChannel->SetAudioOutputDevice(pDevice); + } + catch (Exception e) { + result.Error(e); + } + } + return result.Produce(); +} + +String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) { + dmsg(2,("LSCPServer: SetAudioOutputType(String AudioOutputDriver=%s, SamplerChannel=%d)\n",AudioOutputDriver.c_str(),uiSamplerChannel)); + LSCPResultSet result; + { + LockGuard lock(RTNotifyMutex); + try { + SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); + if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); + // Driver type name aliasing... + if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA"; + if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK"; + // Check if there's one audio output device already created + // for the intended audio driver type (AudioOutputDriver)... + AudioOutputDevice *pDevice = NULL; + std::map devices = pSampler->GetAudioOutputDevices(); + std::map::iterator iter = devices.begin(); + for (; iter != devices.end(); iter++) { + if ((iter->second)->Driver() == AudioOutputDriver) { + pDevice = iter->second; + break; + } + } + // If it doesn't exist, create a new one with default parameters... + if (pDevice == NULL) { + std::map params; + pDevice = pSampler->CreateAudioOutputDevice(AudioOutputDriver, params); + } + // Must have a device... + if (pDevice == NULL) + throw Exception("Internal error: could not create audio output device."); + // Set it as the current channel device... + pSamplerChannel->SetAudioOutputDevice(pDevice); + } + catch (Exception e) { + result.Error(e); + } + } + return result.Produce(); +} + +String LSCPServer::AddChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId, uint MIDIPort) { + dmsg(2,("LSCPServer: AddChannelMidiInput(uiSamplerChannel=%d, MIDIDeviceId=%d, MIDIPort=%d)\n",uiSamplerChannel,MIDIDeviceId,MIDIPort)); + LSCPResultSet result; try { SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); - std::map devices = pSampler->GetAudioOutputDevices(); - if (!devices.count(AudioDeviceId)) throw Exception("There is no audio output device with index " + ToString(AudioDeviceId)); - AudioOutputDevice* pDevice = devices[AudioDeviceId]; - pSamplerChannel->SetAudioOutputDevice(pDevice); + + std::map devices = pSampler->GetMidiInputDevices(); + if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId)); + MidiInputDevice* pDevice = devices[MIDIDeviceId]; + + MidiInputPort* pPort = pDevice->GetPort(MIDIPort); + if (!pPort) throw Exception("There is no MIDI input port with index " + ToString(MIDIPort) + " on MIDI input device with index " + ToString(MIDIDeviceId)); + + pSamplerChannel->Connect(pPort); + } catch (Exception e) { + result.Error(e); } - catch (Exception e) { - result.Error(e); + return result.Produce(); +} + +String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel) { + dmsg(2,("LSCPServer: RemoveChannelMidiInput(uiSamplerChannel=%d)\n",uiSamplerChannel)); + LSCPResultSet result; + try { + SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); + if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); + pSamplerChannel->DisconnectAllMidiInputPorts(); + } catch (Exception e) { + result.Error(e); } - UnlockRTNotify(); return result.Produce(); } -String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) { - dmsg(2,("LSCPServer: SetAudioOutputType(String AudioOutputDriver=%s, SamplerChannel=%d)\n",AudioOutputDriver.c_str(),uiSamplerChannel)); +String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId) { + dmsg(2,("LSCPServer: RemoveChannelMidiInput(uiSamplerChannel=%d, MIDIDeviceId=%d)\n",uiSamplerChannel,MIDIDeviceId)); LSCPResultSet result; - LockRTNotify(); try { SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); - // Driver type name aliasing... - if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA"; - if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK"; - // Check if there's one audio output device already created - // for the intended audio driver type (AudioOutputDriver)... - AudioOutputDevice *pDevice = NULL; - std::map devices = pSampler->GetAudioOutputDevices(); - std::map::iterator iter = devices.begin(); - for (; iter != devices.end(); iter++) { - if ((iter->second)->Driver() == AudioOutputDriver) { - pDevice = iter->second; - break; - } - } - // If it doesn't exist, create a new one with default parameters... - if (pDevice == NULL) { - std::map params; - pDevice = pSampler->CreateAudioOutputDevice(AudioOutputDriver, params); - } - // Must have a device... - if (pDevice == NULL) - throw Exception("Internal error: could not create audio output device."); - // Set it as the current channel device... - pSamplerChannel->SetAudioOutputDevice(pDevice); + + std::map devices = pSampler->GetMidiInputDevices(); + if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId)); + MidiInputDevice* pDevice = devices[MIDIDeviceId]; + + std::vector vPorts = pSamplerChannel->GetMidiInputPorts(); + for (int i = 0; i < vPorts.size(); ++i) + if (vPorts[i]->GetDevice() == pDevice) + pSamplerChannel->Disconnect(vPorts[i]); + + } catch (Exception e) { + result.Error(e); } - catch (Exception e) { - result.Error(e); + return result.Produce(); +} + +String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId, uint MIDIPort) { + dmsg(2,("LSCPServer: RemoveChannelMidiInput(uiSamplerChannel=%d, MIDIDeviceId=%d, MIDIPort=%d)\n",uiSamplerChannel,MIDIDeviceId,MIDIPort)); + LSCPResultSet result; + try { + SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); + if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); + + std::map devices = pSampler->GetMidiInputDevices(); + if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId)); + MidiInputDevice* pDevice = devices[MIDIDeviceId]; + + MidiInputPort* pPort = pDevice->GetPort(MIDIPort); + if (!pPort) throw Exception("There is no MIDI input port with index " + ToString(MIDIPort) + " on MIDI input device with index " + ToString(MIDIDeviceId)); + + pSamplerChannel->Disconnect(pPort); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::ListChannelMidiInputs(uint uiSamplerChannel) { + dmsg(2,("LSCPServer: ListChannelMidiInputs(uiSamplerChannel=%d)\n",uiSamplerChannel)); + LSCPResultSet result; + try { + SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); + if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); + std::vector vPorts = pSamplerChannel->GetMidiInputPorts(); + + String s; + for (int i = 0; i < vPorts.size(); ++i) { + const int iDeviceID = vPorts[i]->GetDevice()->MidiInputDeviceID(); + const int iPortNr = vPorts[i]->GetPortNumber(); + if (s.size()) s += ","; + s += "{" + ToString(iDeviceID) + "," + + ToString(iPortNr) + "}"; + } + result.Add(s); + } catch (Exception e) { + result.Error(e); } - UnlockRTNotify(); return result.Produce(); } @@ -1641,7 +2005,6 @@ pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params); // Make it with at least one initial port. std::map parameters = pDevice->DeviceParameters(); - parameters["PORTS"]->SetValue("1"); } // Must have a device... if (pDevice == NULL) @@ -1684,10 +2047,7 @@ dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); - if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); - EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel(); - if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); pEngineChannel->Volume(dVolume); } catch (Exception e) { @@ -1703,11 +2063,7 @@ dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); - if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); - - EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel(); - if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0); else pEngineChannel->SetMute(1); @@ -1724,11 +2080,7 @@ dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); - if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); - - EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel(); - if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); bool oldSolo = pEngineChannel->GetSolo(); bool hadSoloChannel = HasSoloChannel(); @@ -1848,7 +2200,7 @@ dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n")); LSCPResultSet result; try { - result.Add(MidiInstrumentMapper::Entries(MidiMapID).size()); + result.Add(MidiInstrumentMapper::GetInstrumentCount(MidiMapID)); } catch (Exception e) { result.Error(e); } @@ -1859,14 +2211,11 @@ String LSCPServer::GetAllMidiInstrumentMappings() { dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n")); LSCPResultSet result; - std::vector maps = MidiInstrumentMapper::Maps(); - int totalMappings = 0; - for (int i = 0; i < maps.size(); i++) { - try { - totalMappings += MidiInstrumentMapper::Entries(maps[i]).size(); - } catch (Exception e) { /*NOOP*/ } + try { + result.Add(MidiInstrumentMapper::GetInstrumentCount()); + } catch (Exception e) { + result.Error(e); } - result.Add(totalMappings); return result.Produce(); } @@ -1874,56 +2223,46 @@ dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n")); LSCPResultSet result; try { - midi_prog_index_t idx; - idx.midi_bank_msb = (MidiBank >> 7) & 0x7f; - idx.midi_bank_lsb = MidiBank & 0x7f; - idx.midi_prog = MidiProg; - - std::map mappings = MidiInstrumentMapper::Entries(MidiMapID); - std::map::iterator iter = mappings.find(idx); - if (iter == mappings.end()) result.Error("there is no map entry with that index"); - else { // found - - // convert the filename into the correct encoding as defined for LSCP - // (especially in terms of special characters -> escape sequences) + MidiInstrumentMapper::entry_t entry = MidiInstrumentMapper::GetEntry(MidiMapID, MidiBank, MidiProg); + // convert the filename into the correct encoding as defined for LSCP + // (especially in terms of special characters -> escape sequences) #if WIN32 - const String instrumentFileName = Path::fromWindows(iter->second.InstrumentFile).toLscp(); + const String instrumentFileName = Path::fromWindows(entry.InstrumentFile).toLscp(); #else - // assuming POSIX - const String instrumentFileName = Path::fromPosix(iter->second.InstrumentFile).toLscp(); + // assuming POSIX + const String instrumentFileName = Path::fromPosix(entry.InstrumentFile).toLscp(); #endif - result.Add("NAME", _escapeLscpResponse(iter->second.Name)); - result.Add("ENGINE_NAME", iter->second.EngineName); - result.Add("INSTRUMENT_FILE", instrumentFileName); - result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex); - String instrumentName; - Engine* pEngine = EngineFactory::Create(iter->second.EngineName); - if (pEngine) { - if (pEngine->GetInstrumentManager()) { - InstrumentManager::instrument_id_t instrID; - instrID.FileName = iter->second.InstrumentFile; - instrID.Index = iter->second.InstrumentIndex; - instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID); - } - EngineFactory::Destroy(pEngine); + result.Add("NAME", _escapeLscpResponse(entry.Name)); + result.Add("ENGINE_NAME", entry.EngineName); + result.Add("INSTRUMENT_FILE", instrumentFileName); + result.Add("INSTRUMENT_NR", (int) entry.InstrumentIndex); + String instrumentName; + Engine* pEngine = EngineFactory::Create(entry.EngineName); + if (pEngine) { + if (pEngine->GetInstrumentManager()) { + InstrumentManager::instrument_id_t instrID; + instrID.FileName = entry.InstrumentFile; + instrID.Index = entry.InstrumentIndex; + instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID); } - result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName)); - switch (iter->second.LoadMode) { - case MidiInstrumentMapper::ON_DEMAND: - result.Add("LOAD_MODE", "ON_DEMAND"); - break; - case MidiInstrumentMapper::ON_DEMAND_HOLD: - result.Add("LOAD_MODE", "ON_DEMAND_HOLD"); - break; - case MidiInstrumentMapper::PERSISTENT: - result.Add("LOAD_MODE", "PERSISTENT"); - break; - default: - throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!"); - } - result.Add("VOLUME", iter->second.Volume); + EngineFactory::Destroy(pEngine); + } + result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName)); + switch (entry.LoadMode) { + case MidiInstrumentMapper::ON_DEMAND: + result.Add("LOAD_MODE", "ON_DEMAND"); + break; + case MidiInstrumentMapper::ON_DEMAND_HOLD: + result.Add("LOAD_MODE", "ON_DEMAND_HOLD"); + break; + case MidiInstrumentMapper::PERSISTENT: + result.Add("LOAD_MODE", "PERSISTENT"); + break; + default: + throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!"); } + result.Add("VOLUME", entry.Volume); } catch (Exception e) { result.Error(e); } @@ -2094,11 +2433,7 @@ dmsg(2,("LSCPServer: SetChannelMap()\n")); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); - if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); - - EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel(); - if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); if (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone(); else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault(); @@ -2206,11 +2541,17 @@ AudioRouting += ToString(pFxSend->DestinationChannel(chan)); } + const String sEffectRouting = + (pFxSend->DestinationEffectChain() >= 0 && pFxSend->DestinationEffectChainPosition() >= 0) + ? ToString(pFxSend->DestinationEffectChain()) + "," + ToString(pFxSend->DestinationEffectChainPosition()) + : "NONE"; + // success result.Add("NAME", _escapeLscpResponse(pFxSend->Name())); result.Add("MIDI_CONTROLLER", pFxSend->MidiController()); result.Add("LEVEL", ToString(pFxSend->Level())); result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting); + result.Add("EFFECT", sEffectRouting); } catch (Exception e) { result.Error(e); } @@ -2273,14 +2614,478 @@ return result.Produce(); } +String LSCPServer::SetFxSendEffect(uint uiSamplerChannel, uint FxSendID, int iSendEffectChain, int iEffectChainPosition) { + dmsg(2,("LSCPServer: SetFxSendEffect(%d,%d)\n", iSendEffectChain, iEffectChainPosition)); + LSCPResultSet result; + try { + FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID); + + pFxSend->SetDestinationEffect(iSendEffectChain, iEffectChainPosition); + LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID)); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::GetAvailableEffects() { + dmsg(2,("LSCPServer: GetAvailableEffects()\n")); + LSCPResultSet result; + try { + int n = EffectFactory::AvailableEffectsCount(); + result.Add(n); + } + catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::ListAvailableEffects() { + dmsg(2,("LSCPServer: ListAvailableEffects()\n")); + LSCPResultSet result; + String list; + try { + //FIXME: for now we simply enumerate from 0 .. EffectFactory::AvailableEffectsCount() here, in future we should use unique IDs for effects during the whole sampler session. This issue comes into game when the user forces a reload of available effect plugins + int n = EffectFactory::AvailableEffectsCount(); + for (int i = 0; i < n; i++) { + if (i) list += ","; + list += ToString(i); + } + } + catch (Exception e) { + result.Error(e); + } + result.Add(list); + return result.Produce(); +} + +String LSCPServer::GetEffectInfo(int iEffectIndex) { + dmsg(2,("LSCPServer: GetEffectInfo(%d)\n", iEffectIndex)); + LSCPResultSet result; + try { + EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(iEffectIndex); + if (!pEffectInfo) + throw Exception("There is no effect with index " + ToString(iEffectIndex)); + + // convert the filename into the correct encoding as defined for LSCP + // (especially in terms of special characters -> escape sequences) +#if WIN32 + const String dllFileName = Path::fromWindows(pEffectInfo->Module()).toLscp(); +#else + // assuming POSIX + const String dllFileName = Path::fromPosix(pEffectInfo->Module()).toLscp(); +#endif + + result.Add("SYSTEM", pEffectInfo->EffectSystem()); + result.Add("MODULE", dllFileName); + result.Add("NAME", _escapeLscpResponse(pEffectInfo->Name())); + result.Add("DESCRIPTION", _escapeLscpResponse(pEffectInfo->Description())); + } + catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::GetEffectInstanceInfo(int iEffectInstance) { + dmsg(2,("LSCPServer: GetEffectInstanceInfo(%d)\n", iEffectInstance)); + LSCPResultSet result; + try { + Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance); + if (!pEffect) + throw Exception("There is no effect instance with ID " + ToString(iEffectInstance)); + + EffectInfo* pEffectInfo = pEffect->GetEffectInfo(); + + // convert the filename into the correct encoding as defined for LSCP + // (especially in terms of special characters -> escape sequences) +#if WIN32 + const String dllFileName = Path::fromWindows(pEffectInfo->Module()).toLscp(); +#else + // assuming POSIX + const String dllFileName = Path::fromPosix(pEffectInfo->Module()).toLscp(); +#endif + + result.Add("SYSTEM", pEffectInfo->EffectSystem()); + result.Add("MODULE", dllFileName); + result.Add("NAME", _escapeLscpResponse(pEffectInfo->Name())); + result.Add("DESCRIPTION", _escapeLscpResponse(pEffectInfo->Description())); + result.Add("INPUT_CONTROLS", ToString(pEffect->InputControlCount())); + } + catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::GetEffectInstanceInputControlInfo(int iEffectInstance, int iInputControlIndex) { + dmsg(2,("LSCPServer: GetEffectInstanceInputControlInfo(%d,%d)\n", iEffectInstance, iInputControlIndex)); + LSCPResultSet result; + try { + Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance); + if (!pEffect) + throw Exception("There is no effect instance with ID " + ToString(iEffectInstance)); + + EffectControl* pEffectControl = pEffect->InputControl(iInputControlIndex); + if (!pEffectControl) + throw Exception( + "Effect instance " + ToString(iEffectInstance) + + " does not have an input control with index " + + ToString(iInputControlIndex) + ); + + result.Add("DESCRIPTION", _escapeLscpResponse(pEffectControl->Description())); + result.Add("VALUE", pEffectControl->Value()); + if (pEffectControl->MinValue()) + result.Add("RANGE_MIN", *pEffectControl->MinValue()); + if (pEffectControl->MaxValue()) + result.Add("RANGE_MAX", *pEffectControl->MaxValue()); + if (!pEffectControl->Possibilities().empty()) + result.Add("POSSIBILITIES", pEffectControl->Possibilities()); + if (pEffectControl->DefaultValue()) + result.Add("DEFAULT", *pEffectControl->DefaultValue()); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::SetEffectInstanceInputControlValue(int iEffectInstance, int iInputControlIndex, double dValue) { + dmsg(2,("LSCPServer: SetEffectInstanceInputControlValue(%d,%d,%f)\n", iEffectInstance, iInputControlIndex, dValue)); + LSCPResultSet result; + try { + Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance); + if (!pEffect) + throw Exception("There is no effect instance with ID " + ToString(iEffectInstance)); + + EffectControl* pEffectControl = pEffect->InputControl(iInputControlIndex); + if (!pEffectControl) + throw Exception( + "Effect instance " + ToString(iEffectInstance) + + " does not have an input control with index " + + ToString(iInputControlIndex) + ); + + pEffectControl->SetValue(dValue); + LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_info, iEffectInstance)); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::CreateEffectInstance(int iEffectIndex) { + dmsg(2,("LSCPServer: CreateEffectInstance(%d)\n", iEffectIndex)); + LSCPResultSet result; + try { + EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(iEffectIndex); + if (!pEffectInfo) + throw Exception("There is no effect with index " + ToString(iEffectIndex)); + Effect* pEffect = EffectFactory::Create(pEffectInfo); + result = pEffect->ID(); // success + LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_count, EffectFactory::EffectInstancesCount())); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::CreateEffectInstance(String effectSystem, String module, String effectName) { + dmsg(2,("LSCPServer: CreateEffectInstance('%s','%s','%s')\n", effectSystem.c_str(), module.c_str(), effectName.c_str())); + LSCPResultSet result; + try { + // to allow loading the same LSCP session file on different systems + // successfully, probably with different effect plugin DLL paths or even + // running completely different operating systems, we do the following + // for finding the right effect: + // + // first try to search for an exact match of the effect plugin DLL + // (a.k.a 'module'), to avoid picking the wrong DLL with the same + // effect name ... + EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_MATCH_EXACTLY); + // ... if no effect with exactly matchin DLL filename was found, then + // try to lower the restrictions of matching the effect plugin DLL + // filename and try again and again ... + if (!pEffectInfo) { + dmsg(2,("no exact module match, trying MODULE_IGNORE_PATH\n")); + pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH); + } + if (!pEffectInfo) { + dmsg(2,("no module match, trying MODULE_IGNORE_PATH | MODULE_IGNORE_CASE\n")); + pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH | EffectFactory::MODULE_IGNORE_CASE); + } + if (!pEffectInfo) { + dmsg(2,("no module match, trying MODULE_IGNORE_PATH | MODULE_IGNORE_CASE | MODULE_IGNORE_EXTENSION\n")); + pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH | EffectFactory::MODULE_IGNORE_CASE | EffectFactory::MODULE_IGNORE_EXTENSION); + } + // ... if there was still no effect found, then completely ignore the + // DLL plugin filename argument and just search for the matching effect + // system type and effect name + if (!pEffectInfo) { + dmsg(2,("no module match, trying MODULE_IGNORE_ALL\n")); + pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_ALL); + } + if (!pEffectInfo) + throw Exception("There is no such effect '" + effectSystem + "' '" + module + "' '" + effectName + "'"); + + Effect* pEffect = EffectFactory::Create(pEffectInfo); + result = LSCPResultSet(pEffect->ID()); + LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_count, EffectFactory::EffectInstancesCount())); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::DestroyEffectInstance(int iEffectInstance) { + dmsg(2,("LSCPServer: DestroyEffectInstance(%d)\n", iEffectInstance)); + LSCPResultSet result; + try { + Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance); + if (!pEffect) + throw Exception("There is no effect instance with ID " + ToString(iEffectInstance)); + EffectFactory::Destroy(pEffect); + LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_count, EffectFactory::EffectInstancesCount())); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::GetEffectInstances() { + dmsg(2,("LSCPServer: GetEffectInstances()\n")); + LSCPResultSet result; + try { + int n = EffectFactory::EffectInstancesCount(); + result.Add(n); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::ListEffectInstances() { + dmsg(2,("LSCPServer: ListEffectInstances()\n")); + LSCPResultSet result; + String list; + try { + int n = EffectFactory::EffectInstancesCount(); + for (int i = 0; i < n; i++) { + Effect* pEffect = EffectFactory::GetEffectInstance(i); + if (i) list += ","; + list += ToString(pEffect->ID()); + } + } catch (Exception e) { + result.Error(e); + } + result.Add(list); + return result.Produce(); +} + +String LSCPServer::GetSendEffectChains(int iAudioOutputDevice) { + dmsg(2,("LSCPServer: GetSendEffectChains(%d)\n", iAudioOutputDevice)); + LSCPResultSet result; + try { + std::map devices = pSampler->GetAudioOutputDevices(); + if (!devices.count(iAudioOutputDevice)) + throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + "."); + AudioOutputDevice* pDevice = devices[iAudioOutputDevice]; + int n = pDevice->SendEffectChainCount(); + result.Add(n); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::ListSendEffectChains(int iAudioOutputDevice) { + dmsg(2,("LSCPServer: ListSendEffectChains(%d)\n", iAudioOutputDevice)); + LSCPResultSet result; + String list; + try { + std::map devices = pSampler->GetAudioOutputDevices(); + if (!devices.count(iAudioOutputDevice)) + throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + "."); + AudioOutputDevice* pDevice = devices[iAudioOutputDevice]; + int n = pDevice->SendEffectChainCount(); + for (int i = 0; i < n; i++) { + EffectChain* pEffectChain = pDevice->SendEffectChain(i); + if (i) list += ","; + list += ToString(pEffectChain->ID()); + } + } catch (Exception e) { + result.Error(e); + } + result.Add(list); + return result.Produce(); +} + +String LSCPServer::AddSendEffectChain(int iAudioOutputDevice) { + dmsg(2,("LSCPServer: AddSendEffectChain(%d)\n", iAudioOutputDevice)); + LSCPResultSet result; + try { + std::map devices = pSampler->GetAudioOutputDevices(); + if (!devices.count(iAudioOutputDevice)) + throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + "."); + AudioOutputDevice* pDevice = devices[iAudioOutputDevice]; + EffectChain* pEffectChain = pDevice->AddSendEffectChain(); + result = pEffectChain->ID(); + LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_count, iAudioOutputDevice, pDevice->SendEffectChainCount())); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::RemoveSendEffectChain(int iAudioOutputDevice, int iSendEffectChain) { + dmsg(2,("LSCPServer: RemoveSendEffectChain(%d,%d)\n", iAudioOutputDevice, iSendEffectChain)); + LSCPResultSet result; + try { + std::map devices = pSampler->GetAudioOutputDevices(); + if (!devices.count(iAudioOutputDevice)) + throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + "."); + + std::set engineChannels = EngineChannelFactory::EngineChannelInstances(); + std::set::iterator itEngineChannel = engineChannels.begin(); + std::set::iterator itEnd = engineChannels.end(); + for (; itEngineChannel != itEnd; ++itEngineChannel) { + AudioOutputDevice* pDev = (*itEngineChannel)->GetAudioOutputDevice(); + if (pDev != NULL && pDev->deviceId() == iAudioOutputDevice) { + for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) { + FxSend* fxs = (*itEngineChannel)->GetFxSend(i); + if(fxs != NULL && fxs->DestinationEffectChain() == iSendEffectChain) { + throw Exception("The effect chain is still in use by channel " + ToString((*itEngineChannel)->GetSamplerChannel()->Index())); + } + } + } + } + + AudioOutputDevice* pDevice = devices[iAudioOutputDevice]; + for (int i = 0; i < pDevice->SendEffectChainCount(); i++) { + EffectChain* pEffectChain = pDevice->SendEffectChain(i); + if (pEffectChain->ID() == iSendEffectChain) { + pDevice->RemoveSendEffectChain(i); + LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_count, iAudioOutputDevice, pDevice->SendEffectChainCount())); + return result.Produce(); + } + } + throw Exception( + "There is no send effect chain with ID " + + ToString(iSendEffectChain) + " for audio output device " + + ToString(iAudioOutputDevice) + "." + ); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +static EffectChain* _getSendEffectChain(Sampler* pSampler, int iAudioOutputDevice, int iSendEffectChain) throw (Exception) { + std::map devices = pSampler->GetAudioOutputDevices(); + if (!devices.count(iAudioOutputDevice)) + throw Exception( + "There is no audio output device with index " + + ToString(iAudioOutputDevice) + "." + ); + AudioOutputDevice* pDevice = devices[iAudioOutputDevice]; + EffectChain* pEffectChain = pDevice->SendEffectChainByID(iSendEffectChain); + if(pEffectChain != NULL) return pEffectChain; + throw Exception( + "There is no send effect chain with ID " + + ToString(iSendEffectChain) + " for audio output device " + + ToString(iAudioOutputDevice) + "." + ); +} + +String LSCPServer::GetSendEffectChainInfo(int iAudioOutputDevice, int iSendEffectChain) { + dmsg(2,("LSCPServer: GetSendEffectChainInfo(%d,%d)\n", iAudioOutputDevice, iSendEffectChain)); + LSCPResultSet result; + try { + EffectChain* pEffectChain = + _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain); + String sEffectSequence; + for (int i = 0; i < pEffectChain->EffectCount(); i++) { + if (i) sEffectSequence += ","; + sEffectSequence += ToString(pEffectChain->GetEffect(i)->ID()); + } + result.Add("EFFECT_COUNT", pEffectChain->EffectCount()); + result.Add("EFFECT_SEQUENCE", sEffectSequence); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::AppendSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectInstance) { + dmsg(2,("LSCPServer: AppendSendEffectChainEffect(%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectInstance)); + LSCPResultSet result; + try { + EffectChain* pEffectChain = + _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain); + Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance); + if (!pEffect) + throw Exception("There is no effect instance with ID " + ToString(iEffectInstance)); + pEffectChain->AppendEffect(pEffect); + LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_info, iAudioOutputDevice, iSendEffectChain, pEffectChain->EffectCount())); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::InsertSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectChainPosition, int iEffectInstance) { + dmsg(2,("LSCPServer: InsertSendEffectChainEffect(%d,%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectChainPosition, iEffectInstance)); + LSCPResultSet result; + try { + EffectChain* pEffectChain = + _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain); + Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance); + if (!pEffect) + throw Exception("There is no effect instance with index " + ToString(iEffectInstance)); + pEffectChain->InsertEffect(pEffect, iEffectChainPosition); + LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_info, iAudioOutputDevice, iSendEffectChain, pEffectChain->EffectCount())); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::RemoveSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectChainPosition) { + dmsg(2,("LSCPServer: RemoveSendEffectChainEffect(%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectChainPosition)); + LSCPResultSet result; + try { + EffectChain* pEffectChain = + _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain); + + std::set engineChannels = EngineChannelFactory::EngineChannelInstances(); + std::set::iterator itEngineChannel = engineChannels.begin(); + std::set::iterator itEnd = engineChannels.end(); + for (; itEngineChannel != itEnd; ++itEngineChannel) { + AudioOutputDevice* pDev = (*itEngineChannel)->GetAudioOutputDevice(); + if (pDev != NULL && pDev->deviceId() == iAudioOutputDevice) { + for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) { + FxSend* fxs = (*itEngineChannel)->GetFxSend(i); + if(fxs != NULL && fxs->DestinationEffectChain() == iSendEffectChain && fxs->DestinationEffectChainPosition() == iEffectChainPosition) { + throw Exception("The effect instance is still in use by channel " + ToString((*itEngineChannel)->GetSamplerChannel()->Index())); + } + } + } + } + + pEffectChain->RemoveEffect(iEffectChainPosition); + LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_info, iAudioOutputDevice, iSendEffectChain, pEffectChain->EffectCount())); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) { dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); - if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); - EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel(); - if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel"); Engine* pEngine = pEngineChannel->GetEngine(); InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager(); @@ -2295,6 +3100,48 @@ return result.Produce(); } +String LSCPServer::SendChannelMidiData(String MidiMsg, uint uiSamplerChannel, uint Arg1, uint Arg2) { + dmsg(2,("LSCPServer: SendChannelMidiData(MidiMsg=%s,uiSamplerChannel=%d,Arg1=%d,Arg2=%d)\n", MidiMsg.c_str(), uiSamplerChannel, Arg1, Arg2)); + LSCPResultSet result; + try { + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); + + if (Arg1 > 127 || Arg2 > 127) { + throw Exception("Invalid MIDI message"); + } + + VirtualMidiDevice* pMidiDevice = NULL; + std::vector::iterator iter = eventHandler.channelMidiListeners.begin(); + for (; iter != eventHandler.channelMidiListeners.end(); ++iter) { + if ((*iter).pEngineChannel == pEngineChannel) { + pMidiDevice = (*iter).pMidiListener; + break; + } + } + + if(pMidiDevice == NULL) throw Exception("Couldn't find virtual MIDI device"); + + if (MidiMsg == "NOTE_ON") { + pMidiDevice->SendNoteOnToDevice(Arg1, Arg2); + bool b = pMidiDevice->SendNoteOnToSampler(Arg1, Arg2); + if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2)); + } else if (MidiMsg == "NOTE_OFF") { + pMidiDevice->SendNoteOffToDevice(Arg1, Arg2); + bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2); + if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2)); + } else if (MidiMsg == "CC") { + pMidiDevice->SendCCToDevice(Arg1, Arg2); + bool b = pMidiDevice->SendCCToSampler(Arg1, Arg2); + if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2)); + } else { + throw Exception("Unknown MIDI message type: " + MidiMsg); + } + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + /** * Will be called by the parser to reset a particular sampler channel. */ @@ -2302,10 +3149,7 @@ dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel)); LSCPResultSet result; try { - SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel); - if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel)); - EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel(); - if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel"); + EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel); pEngineChannel->Reset(); } catch (Exception e) { @@ -2346,6 +3190,16 @@ } /** + * Will be called by the parser to return the current number of all active streams. + */ +String LSCPServer::GetTotalStreamCount() { + dmsg(2,("LSCPServer: GetTotalStreamCount()\n")); + LSCPResultSet result; + result.Add(pSampler->GetDiskStreamCount()); + return result.Produce(); +} + +/** * Will be called by the parser to return the current number of all active voices. */ String LSCPServer::GetTotalVoiceCount() { @@ -2361,7 +3215,65 @@ String LSCPServer::GetTotalVoiceCountMax() { dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n")); LSCPResultSet result; - result.Add(EngineFactory::EngineInstances().size() * CONFIG_MAX_VOICES); + result.Add(EngineFactory::EngineInstances().size() * pSampler->GetGlobalMaxVoices()); + return result.Produce(); +} + +/** + * Will be called by the parser to return the sampler global maximum + * allowed number of voices. + */ +String LSCPServer::GetGlobalMaxVoices() { + dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n")); + LSCPResultSet result; + result.Add(pSampler->GetGlobalMaxVoices()); + return result.Produce(); +} + +/** + * Will be called by the parser to set the sampler global maximum number of + * voices. + */ +String LSCPServer::SetGlobalMaxVoices(int iVoices) { + dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices)); + LSCPResultSet result; + try { + pSampler->SetGlobalMaxVoices(iVoices); + LSCPServer::SendLSCPNotify( + LSCPEvent(LSCPEvent::event_global_info, "VOICES", pSampler->GetGlobalMaxVoices()) + ); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +/** + * Will be called by the parser to return the sampler global maximum + * allowed number of disk streams. + */ +String LSCPServer::GetGlobalMaxStreams() { + dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n")); + LSCPResultSet result; + result.Add(pSampler->GetGlobalMaxStreams()); + return result.Produce(); +} + +/** + * Will be called by the parser to set the sampler global maximum number of + * disk streams. + */ +String LSCPServer::SetGlobalMaxStreams(int iStreams) { + dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams)); + LSCPResultSet result; + try { + pSampler->SetGlobalMaxStreams(iStreams); + LSCPServer::SendLSCPNotify( + LSCPEvent(LSCPEvent::event_global_info, "STREAMS", pSampler->GetGlobalMaxStreams()) + ); + } catch (Exception e) { + result.Error(e); + } return result.Produce(); } @@ -2375,7 +3287,7 @@ LSCPResultSet result; try { if (dVolume < 0) throw Exception("Volume may not be negative"); - GLOBAL_VOLUME = dVolume; // see common/global.cpp + GLOBAL_VOLUME = dVolume; // see common/global_private.cpp LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME)); } catch (Exception e) { result.Error(e); @@ -2502,6 +3414,26 @@ result.Add("FORMAT_VERSION", info.FormatVersion); result.Add("PRODUCT", info.Product); result.Add("ARTISTS", info.Artists); + + std::stringstream ss; + bool b = false; + for (int i = 0; i < 128; i++) { + if (info.KeyBindings[i]) { + if (b) ss << ','; + ss << i; b = true; + } + } + result.Add("KEY_BINDINGS", ss.str()); + + b = false; + std::stringstream ss2; + for (int i = 0; i < 128; i++) { + if (info.KeySwitchBindings[i]) { + if (b) ss2 << ','; + ss2 << i; b = true; + } + } + result.Add("KEYSWITCH_BINDINGS", ss2.str()); // no more need to ask other engine types bFound = true; } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str())); @@ -2517,17 +3449,22 @@ } void LSCPServer::VerifyFile(String Filename) { - struct stat statBuf; - int res = stat(Filename.c_str(), &statBuf); - if (res) { + #if WIN32 + WIN32_FIND_DATA win32FileAttributeData; + BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData ); + if (!res) { std::stringstream ss; - ss << "Fail to stat `" << Filename << "`: " << strerror(errno); + ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError(); throw Exception(ss.str()); } - - if (S_ISDIR(statBuf.st_mode)) { + if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { throw Exception("Directory is specified"); } + #else + File f(Filename); + if(!f.Exist()) throw Exception(f.GetErrorMsg()); + if (f.IsDirectory()) throw Exception("Directory is specified"); + #endif } /** @@ -2537,9 +3474,10 @@ String LSCPServer::SubscribeNotification(LSCPEvent::event_t type) { dmsg(2,("LSCPServer: SubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str())); LSCPResultSet result; - SubscriptionMutex.Lock(); - eventSubscriptions[type].push_back(currentSocket); - SubscriptionMutex.Unlock(); + { + LockGuard lock(SubscriptionMutex); + eventSubscriptions[type].push_back(currentSocket); + } return result.Produce(); } @@ -2550,9 +3488,10 @@ String LSCPServer::UnsubscribeNotification(LSCPEvent::event_t type) { dmsg(2,("LSCPServer: UnsubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str())); LSCPResultSet result; - SubscriptionMutex.Lock(); - eventSubscriptions[type].remove(currentSocket); - SubscriptionMutex.Unlock(); + { + LockGuard lock(SubscriptionMutex); + eventSubscriptions[type].remove(currentSocket); + } return result.Produce(); } @@ -2721,19 +3660,19 @@ return result.Produce(); } -String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) { - dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground)); +String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground, bool insDir) { + dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d,insDir=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground, insDir)); LSCPResultSet result; #if HAVE_SQLITE3 try { int id; InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb(); if (ScanMode.compare("RECURSIVE") == 0) { - id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground); + id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground, insDir); } else if (ScanMode.compare("NON_RECURSIVE") == 0) { - id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground); + id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground, insDir); } else if (ScanMode.compare("FLAT") == 0) { - id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground); + id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground, insDir); } else { throw Exception("Unknown scan mode: " + ScanMode); } @@ -2909,6 +3848,44 @@ return result.Produce(); } +String LSCPServer::SetDbInstrumentFilePath(String OldPath, String NewPath) { + dmsg(2,("LSCPServer: SetDbInstrumentFilePath(OldPath=%s,NewPath=%s)\n", OldPath.c_str(), NewPath.c_str())); + LSCPResultSet result; +#if HAVE_SQLITE3 + try { + InstrumentsDb::GetInstrumentsDb()->SetInstrumentFilePath(OldPath, NewPath); + } catch (Exception e) { + result.Error(e); + } +#else + result.Error(String(DOESNT_HAVE_SQLITE3), 0); +#endif + return result.Produce(); +} + +String LSCPServer::FindLostDbInstrumentFiles() { + dmsg(2,("LSCPServer: FindLostDbInstrumentFiles()\n")); + LSCPResultSet result; +#if HAVE_SQLITE3 + try { + String list; + StringListPtr pLostFiles = InstrumentsDb::GetInstrumentsDb()->FindLostInstrumentFiles(); + + for (int i = 0; i < pLostFiles->size(); i++) { + if (list != "") list += ","; + list += "'" + pLostFiles->at(i) + "'"; + } + + result.Add(list); + } catch (Exception e) { + result.Error(e); + } +#else + result.Error(String(DOESNT_HAVE_SQLITE3), 0); +#endif + return result.Produce(); +} + String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map Parameters, bool Recursive) { dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str())); LSCPResultSet result; @@ -3039,3 +4016,31 @@ } return result.Produce(); } + +String LSCPServer::SetShellInteract(yyparse_param_t* pSession, double boolean_value) { + dmsg(2,("LSCPServer: SetShellInteract(val=%f)\n", boolean_value)); + LSCPResultSet result; + try { + if (boolean_value == 0) pSession->bShellInteract = false; + else if (boolean_value == 1) pSession->bShellInteract = true; + else throw Exception("Not a boolean value, must either be 0 or 1"); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +String LSCPServer::SetShellAutoCorrect(yyparse_param_t* pSession, double boolean_value) { + dmsg(2,("LSCPServer: SetShellAutoCorrect(val=%f)\n", boolean_value)); + LSCPResultSet result; + try { + if (boolean_value == 0) pSession->bShellAutoCorrect = false; + else if (boolean_value == 1) pSession->bShellAutoCorrect = true; + else throw Exception("Not a boolean value, must either be 0 or 1"); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} + +}