--- linuxsampler/trunk/src/network/lscpserver.cpp 2009/02/28 21:23:06 1848 +++ linuxsampler/trunk/src/network/lscpserver.cpp 2015/08/23 06:14:00 2837 @@ -3,7 +3,7 @@ * LinuxSampler - modular, streaming capable sampler * * * * Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck * - * Copyright (C) 2005 - 2008 Christian Schoenebeck * + * Copyright (C) 2005 - 2015 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 * @@ -43,9 +43,12 @@ #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 * replaced by LSCP escape sequences ("\xHH"). This function shall be used @@ -96,15 +99,15 @@ */ 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), eventHandler(this) { SocketAddress.sin_family = AF_INET; @@ -137,11 +140,16 @@ 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 @@ -441,6 +449,7 @@ #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(); @@ -509,17 +518,18 @@ } } - //Now let's deliver late notifies (if any) - NotifyBufferMutex.Lock(); - for (std::map::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) { + //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; @@ -554,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); @@ -577,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 @@ -595,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; @@ -609,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) @@ -622,7 +642,6 @@ #else close(socket); #endif - NotifyMutex.Unlock(); } void LSCPServer::CloseAllConnections() { @@ -633,30 +652,21 @@ } } -void LSCPServer::LockRTNotify() { - RTNotifyMutex.Lock(); -} - -void LSCPServer::UnlockRTNotify() { - RTNotifyMutex.Unlock(); -} - 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(); @@ -682,7 +692,6 @@ } } } - SubscriptionMutex.Unlock(); } extern int GetLSCPCommand( void *buf, int max_size ) { @@ -707,84 +716,178 @@ } /** + * Generate the relevant LSCP documentation reference section if necessary. + * The documentation section for the currently active command on the LSCP + * shell's command line will be encoded in a special format, specifically for + * the LSCP shell application. + * + * @param line - current LSCP command line + * @param param - reentrant Bison parser parameters + * + * @return encoded reference string or empty string if nothing shall be sent + * to LSCP shell (client) at this point + */ +String LSCPServer::generateLSCPDocReply(const String& line, yyparse_param_t* param) { + String result; + lscp_ref_entry_t* ref = lscp_reference_for_command(line.c_str()); + // Pointer comparison works here, since the function above always + // returns the same constant pointer for the respective LSCP + // command ... Only send the LSCP reference section to the client if + // another LSCP reference section became relevant now: + if (ref != param->pLSCPDocRef) { + param->pLSCPDocRef = ref; + if (ref) { // send a new LSCP doc section to client ... + result += "SHD:" + ToString(LSCP_SHD_MATCH) + ":" + String(ref->name) + "\n"; + result += String(ref->section) + "\n"; + result += "."; // dot line marks the end of the text for client + } else { // inform client that no LSCP doc section matches right now ... + result = "SHD:" + ToString(LSCP_SHD_NO_MATCH); + } + } + dmsg(4,("LSCP doc reply -> '%s'\n", result.c_str())); + return result; +} + +/** * Will be called to try to read the command from the socket * If command is read, it will return true. Otherwise false is returned. * In any case the received portion (complete or incomplete) is saved into bufferedCommand map. */ 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"); + } + // if other side is LSCP shell application, send the relevant LSCP + // documentation section of the current command line (if necessary) + if ((*iter).bShellSendLSCPDoc && (*iter).bShellInteract) { + String s = generateLSCPDocReply(bufferedCommands[socket], &(*iter)); + if (!s.empty()) 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 + } else if (c == 2) { // custom ASCII code usage for moving cursor left (LSCP shell) + if (iter->iCursorOffset + bufferedCommands[socket].size() > 0) + iter->iCursorOffset--; + } else if (c == 3) { // custom ASCII code usage for moving cursor right (LSCP shell) + if (iter->iCursorOffset < 0) iter->iCursorOffset++; + } else { + size_t cursorPos = bufferedCommands[socket].size() + iter->iCursorOffset; + // backspace character - should only happen with shell + if (c == '\b') { + if (!bufferedCommands[socket].empty() && cursorPos > 0) + bufferedCommands[socket].erase(cursorPos - 1, 1); + } else { // append (or insert) new character (at current cursor position) ... + if (cursorPos >= 0) + bufferedCommands[socket].insert(cursorPos, String(1,c)); // insert + else + bufferedCommands[socket] += c; // append + } } - 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 + // Only if the other side (client) is the LSCP shell application: + // The following block takes care about automatic correction, auto + // completion (and suggestions), LSCP reference documentation, etc. + // The "if" statement here is for optimization reasons, so that the + // heavy LSCP grammar evaluation algorithm is only executed once for an + // entire command line received. + if (i == input.size() - 1) { + // 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 other side is LSCP shell application, send the relevant LSCP + // documentation section of the current command line (if necessary) + if ((*iter).bShellSendLSCPDoc && (*iter).bShellInteract) { + String s = generateLSCPDocReply(bufferedCommands[socket], &(*iter)); + if (!s.empty()) AnswerClient(s + "\n"); } - bufferedCommands[socket] += c; } - #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; } @@ -795,15 +898,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(); } } @@ -953,10 +1075,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); @@ -996,9 +1117,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(); } @@ -1009,9 +1132,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(); } @@ -1054,17 +1178,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(); } @@ -1324,7 +1449,7 @@ } String LSCPServer::GetMidiInputDriverParameterInfo(String Driver, String Parameter, std::map DependencyList) { - dmsg(2,("LSCPServer: GetMidiInputDriverParameterInfo(Driver=%s,Parameter=%s,DependencyListSize=%d)\n",Driver.c_str(),Parameter.c_str(),DependencyList.size())); + dmsg(2,("LSCPServer: GetMidiInputDriverParameterInfo(Driver=%s,Parameter=%s,DependencyListSize=%d)\n",Driver.c_str(),Parameter.c_str(),int(DependencyList.size()))); LSCPResultSet result; try { DeviceCreationParameter* pParameter = MidiInputDeviceFactory::GetDriverParameter(Driver, Parameter); @@ -1352,7 +1477,7 @@ } String LSCPServer::GetAudioOutputDriverParameterInfo(String Driver, String Parameter, std::map DependencyList) { - dmsg(2,("LSCPServer: GetAudioOutputDriverParameterInfo(Driver=%s,Parameter=%s,DependencyListSize=%d)\n",Driver.c_str(),Parameter.c_str(),DependencyList.size())); + dmsg(2,("LSCPServer: GetAudioOutputDriverParameterInfo(Driver=%s,Parameter=%s,DependencyListSize=%d)\n",Driver.c_str(),Parameter.c_str(),int(DependencyList.size()))); LSCPResultSet result; try { DeviceCreationParameter* pParameter = AudioOutputDeviceFactory::GetDriverParameter(Driver, Parameter); @@ -1509,7 +1634,7 @@ } String LSCPServer::GetAudioOutputChannelInfo(uint DeviceId, uint ChannelId) { - dmsg(2,("LSCPServer: GetAudioOutputChannelInfo(DeviceId=%d,ChannelId)\n",DeviceId,ChannelId)); + dmsg(2,("LSCPServer: GetAudioOutputChannelInfo(DeviceId=%u,ChannelId=%u)\n",DeviceId,ChannelId)); LSCPResultSet result; try { // get audio output device @@ -1713,58 +1838,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(); } @@ -1838,7 +2065,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) @@ -2375,11 +2601,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); } @@ -2442,6 +2674,473 @@ 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; @@ -2454,7 +3153,7 @@ InstrumentManager::instrument_id_t instrumentID; instrumentID.FileName = pEngineChannel->InstrumentFileName(); instrumentID.Index = pEngineChannel->InstrumentIndex(); - pInstrumentManager->LaunchInstrumentEditor(instrumentID); + pInstrumentManager->LaunchInstrumentEditor(pEngineChannel, instrumentID); } catch (Exception e) { result.Error(e); } @@ -2490,6 +3189,10 @@ 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); } @@ -2572,7 +3275,7 @@ String LSCPServer::GetTotalVoiceCountMax() { dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n")); LSCPResultSet result; - result.Add(EngineFactory::EngineInstances().size() * GLOBAL_MAX_VOICES); + result.Add(EngineFactory::EngineInstances().size() * pSampler->GetGlobalMaxVoices()); return result.Produce(); } @@ -2583,7 +3286,7 @@ String LSCPServer::GetGlobalMaxVoices() { dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n")); LSCPResultSet result; - result.Add(GLOBAL_MAX_VOICES); + result.Add(pSampler->GetGlobalMaxVoices()); return result.Produce(); } @@ -2595,17 +3298,10 @@ dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices)); LSCPResultSet result; try { - if (iVoices < 1) throw Exception("Maximum voices may not be less than 1"); - GLOBAL_MAX_VOICES = iVoices; // see common/global_private.cpp - const std::set& engines = EngineFactory::EngineInstances(); - if (engines.size() > 0) { - std::set::iterator iter = engines.begin(); - std::set::iterator end = engines.end(); - for (; iter != end; ++iter) { - (*iter)->SetMaxVoices(iVoices); - } - } - LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOICES", GLOBAL_MAX_VOICES)); + pSampler->SetGlobalMaxVoices(iVoices); + LSCPServer::SendLSCPNotify( + LSCPEvent(LSCPEvent::event_global_info, "VOICES", pSampler->GetGlobalMaxVoices()) + ); } catch (Exception e) { result.Error(e); } @@ -2619,7 +3315,7 @@ String LSCPServer::GetGlobalMaxStreams() { dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n")); LSCPResultSet result; - result.Add(GLOBAL_MAX_STREAMS); + result.Add(pSampler->GetGlobalMaxStreams()); return result.Produce(); } @@ -2631,17 +3327,10 @@ dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams)); LSCPResultSet result; try { - if (iStreams < 0) throw Exception("Maximum disk streams may not be negative"); - GLOBAL_MAX_STREAMS = iStreams; // see common/global_private.cpp - const std::set& engines = EngineFactory::EngineInstances(); - if (engines.size() > 0) { - std::set::iterator iter = engines.begin(); - std::set::iterator end = engines.end(); - for (; iter != end; ++iter) { - (*iter)->SetMaxDiskStreams(iStreams); - } - } - LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "STREAMS", GLOBAL_MAX_STREAMS)); + pSampler->SetGlobalMaxStreams(iStreams); + LSCPServer::SendLSCPNotify( + LSCPEvent(LSCPEvent::event_global_info, "STREAMS", pSampler->GetGlobalMaxStreams()) + ); } catch (Exception e) { result.Error(e); } @@ -2845,9 +3534,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(); } @@ -2858,9 +3548,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(); } @@ -3385,5 +4076,44 @@ } 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(); +} + +String LSCPServer::SetShellDoc(yyparse_param_t* pSession, double boolean_value) { + dmsg(2,("LSCPServer: SetShellDoc(val=%f)\n", boolean_value)); + LSCPResultSet result; + try { + if (boolean_value == 0) pSession->bShellSendLSCPDoc = false; + else if (boolean_value == 1) pSession->bShellSendLSCPDoc = true; + else throw Exception("Not a boolean value, must either be 0 or 1"); + } catch (Exception e) { + result.Error(e); + } + return result.Produce(); +} }