/[svn]/linuxsampler/trunk/src/network/lscpserver.cpp
ViewVC logotype

Diff of /linuxsampler/trunk/src/network/lscpserver.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1781 by iliev, Mon Sep 29 18:21:21 2008 UTC revision 3055 by schoenebeck, Thu Dec 15 13:01:58 2016 UTC
# Line 3  Line 3 
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6   *   Copyright (C) 2005 - 2008 Christian Schoenebeck                       *   *   Copyright (C) 2005 - 2016 Christian Schoenebeck                       *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 24  Line 24 
24  #include <algorithm>  #include <algorithm>
25  #include <string>  #include <string>
26    
27    #include "../common/File.h"
28  #include "lscpserver.h"  #include "lscpserver.h"
29  #include "lscpresultset.h"  #include "lscpresultset.h"
30  #include "lscpevent.h"  #include "lscpevent.h"
31    
32  #if defined(WIN32)  #if defined(WIN32)
33  #include <windows.h>  #include <windows.h>
34    typedef unsigned short in_port_t;
35    typedef unsigned long in_addr_t;
36  #else  #else
37  #include <fcntl.h>  #include <fcntl.h>
38  #endif  #endif
# Line 42  Line 45 
45  #include "../engines/EngineChannelFactory.h"  #include "../engines/EngineChannelFactory.h"
46  #include "../drivers/audio/AudioOutputDeviceFactory.h"  #include "../drivers/audio/AudioOutputDeviceFactory.h"
47  #include "../drivers/midi/MidiInputDeviceFactory.h"  #include "../drivers/midi/MidiInputDeviceFactory.h"
48    #include "../effects/EffectFactory.h"
49    
50  namespace LinuxSampler {  namespace LinuxSampler {
51    
52    String lscpParserProcessShellInteraction(String& line, yyparse_param_t* param, bool possibilities);
53    
54  /**  /**
55   * Returns a copy of the given string where all special characters are   * Returns a copy of the given string where all special characters are
56   * replaced by LSCP escape sequences ("\xHH"). This function shall be used   * replaced by LSCP escape sequences ("\xHH"). This function shall be used
# Line 95  static String _escapeLscpResponse(String Line 101  static String _escapeLscpResponse(String
101   */   */
102  fd_set LSCPServer::fdSet;  fd_set LSCPServer::fdSet;
103  int LSCPServer::currentSocket = -1;  int LSCPServer::currentSocket = -1;
104  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();  std::vector<yyparse_param_t> LSCPServer::Sessions;
105  std::vector<yyparse_param_t>::iterator itCurrentSession = std::vector<yyparse_param_t>::iterator();  std::vector<yyparse_param_t>::iterator itCurrentSession;
106  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedNotifies;
107  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedCommands;
108  std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions = std::map< LSCPEvent::event_t, std::list<int> >();  std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions;
109  Mutex LSCPServer::NotifyMutex = Mutex();  Mutex LSCPServer::NotifyMutex;
110  Mutex LSCPServer::NotifyBufferMutex = Mutex();  Mutex LSCPServer::NotifyBufferMutex;
111  Mutex LSCPServer::SubscriptionMutex = Mutex();  Mutex LSCPServer::SubscriptionMutex;
112  Mutex LSCPServer::RTNotifyMutex = Mutex();  Mutex LSCPServer::RTNotifyMutex;
113    
114  LSCPServer::LSCPServer(Sampler* pSampler, long int addr, short int port) : Thread(true, false, 0, -4), eventHandler(this) {  LSCPServer::LSCPServer(Sampler* pSampler, long int addr, short int port) : Thread(true, false, 0, -4), eventHandler(this) {
115      SocketAddress.sin_family      = AF_INET;      SocketAddress.sin_family      = AF_INET;
116      SocketAddress.sin_addr.s_addr = addr;      SocketAddress.sin_addr.s_addr = (in_addr_t)addr;
117      SocketAddress.sin_port        = port;      SocketAddress.sin_port        = (in_port_t)port;
118      this->pSampler = pSampler;      this->pSampler = pSampler;
119      LSCPEvent::RegisterEvent(LSCPEvent::event_audio_device_count, "AUDIO_OUTPUT_DEVICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_audio_device_count, "AUDIO_OUTPUT_DEVICE_COUNT");
120      LSCPEvent::RegisterEvent(LSCPEvent::event_audio_device_info, "AUDIO_OUTPUT_DEVICE_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_audio_device_info, "AUDIO_OUTPUT_DEVICE_INFO");
# Line 136  LSCPServer::LSCPServer(Sampler* pSampler Line 142  LSCPServer::LSCPServer(Sampler* pSampler
142      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
143      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");
144      LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI");      LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI");
145        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_instance_count, "EFFECT_INSTANCE_COUNT");
146        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_instance_info, "EFFECT_INSTANCE_INFO");
147        LSCPEvent::RegisterEvent(LSCPEvent::event_send_fx_chain_count, "SEND_EFFECT_CHAIN_COUNT");
148        LSCPEvent::RegisterEvent(LSCPEvent::event_send_fx_chain_info, "SEND_EFFECT_CHAIN_INFO");
149      hSocket = -1;      hSocket = -1;
150  }  }
151    
152  LSCPServer::~LSCPServer() {  LSCPServer::~LSCPServer() {
153        CloseAllConnections();
154        InstrumentManager::StopBackgroundThread();
155  #if defined(WIN32)  #if defined(WIN32)
156      if (hSocket >= 0) closesocket(hSocket);      if (hSocket >= 0) closesocket(hSocket);
157  #else  #else
# Line 334  void LSCPServer::DbInstrumentsEventHandl Line 346  void LSCPServer::DbInstrumentsEventHandl
346  }  }
347  #endif // HAVE_SQLITE3  #endif // HAVE_SQLITE3
348    
349    void LSCPServer::RemoveListeners() {
350        pSampler->RemoveChannelCountListener(&eventHandler);
351        pSampler->RemoveAudioDeviceCountListener(&eventHandler);
352        pSampler->RemoveMidiDeviceCountListener(&eventHandler);
353        pSampler->RemoveVoiceCountListener(&eventHandler);
354        pSampler->RemoveStreamCountListener(&eventHandler);
355        pSampler->RemoveBufferFillListener(&eventHandler);
356        pSampler->RemoveTotalStreamCountListener(&eventHandler);
357        pSampler->RemoveTotalVoiceCountListener(&eventHandler);
358        pSampler->RemoveFxSendCountListener(&eventHandler);
359        MidiInstrumentMapper::RemoveMidiInstrumentCountListener(&eventHandler);
360        MidiInstrumentMapper::RemoveMidiInstrumentInfoListener(&eventHandler);
361        MidiInstrumentMapper::RemoveMidiInstrumentMapCountListener(&eventHandler);
362        MidiInstrumentMapper::RemoveMidiInstrumentMapInfoListener(&eventHandler);
363    #if HAVE_SQLITE3
364        InstrumentsDb::GetInstrumentsDb()->RemoveInstrumentsDbListener(&dbInstrumentsEventHandler);
365    #endif
366    }
367    
368  /**  /**
369   * Blocks the calling thread until the LSCP Server is initialized and   * Blocks the calling thread until the LSCP Server is initialized and
# Line 421  int LSCPServer::Main() { Line 451  int LSCPServer::Main() {
451          #endif          #endif
452          // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers          // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers
453          {          {
454                LockGuard lock(EngineChannelFactory::EngineChannelsMutex);
455              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
456              std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();              std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();
457              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
# Line 489  int LSCPServer::Main() { Line 520  int LSCPServer::Main() {
520              }              }
521          }          }
522    
523          //Now let's deliver late notifies (if any)          //Now let's deliver late notifies (if any)
524          NotifyBufferMutex.Lock();          {
525          for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {              LockGuard lock(NotifyBufferMutex);
526                for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {
527  #ifdef MSG_NOSIGNAL  #ifdef MSG_NOSIGNAL
528                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), MSG_NOSIGNAL);                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), MSG_NOSIGNAL);
529  #else  #else
530                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0);                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0);
531  #endif  #endif
532          }              }
533          bufferedNotifies.clear();              bufferedNotifies.clear();
534          NotifyBufferMutex.Unlock();          }
535    
536          fd_set selectSet = fdSet;          fd_set selectSet = fdSet;
537          timeout.tv_sec  = 0;          timeout.tv_sec  = 0;
# Line 507  int LSCPServer::Main() { Line 539  int LSCPServer::Main() {
539    
540          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);
541    
542          if (retval == 0)          if (retval == 0 || (retval == -1 && errno == EINTR))
543                  continue; //Nothing try again                  continue; //Nothing try again
544          if (retval == -1) {          if (retval == -1) {
545                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
# Line 534  int LSCPServer::Main() { Line 566  int LSCPServer::Main() {
566                    exit(EXIT_FAILURE);                    exit(EXIT_FAILURE);
567                  }                  }
568          #else          #else
569                    struct linger linger;
570                    linger.l_onoff = 1;
571                    linger.l_linger = 0;
572                    if(setsockopt(socket, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger))) {
573                        std::cerr << "LSCPServer: Failed to set SO_LINGER\n";
574                    }
575    
576                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
577                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
578                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
# Line 557  int LSCPServer::Main() { Line 596  int LSCPServer::Main() {
596          //Something was selected and it was not the hSocket, so it must be some command(s) coming.          //Something was selected and it was not the hSocket, so it must be some command(s) coming.
597          for (std::vector<yyparse_param_t>::iterator iter = Sessions.begin(); iter != Sessions.end(); iter++) {          for (std::vector<yyparse_param_t>::iterator iter = Sessions.begin(); iter != Sessions.end(); iter++) {
598                  if (FD_ISSET((*iter).hSession, &selectSet)) {   //Was it this socket?                  if (FD_ISSET((*iter).hSession, &selectSet)) {   //Was it this socket?
599                            currentSocket = (*iter).hSession;  //a hack
600                          if (GetLSCPCommand(iter)) {     //Have we read the entire command?                          if (GetLSCPCommand(iter)) {     //Have we read the entire command?
601                                  dmsg(3,("LSCPServer: Got command on socket %d, calling parser.\n", currentSocket));                                  dmsg(3,("LSCPServer: Got command on socket %d, calling parser.\n", currentSocket));
602                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
603                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
                                 currentSocket = (*iter).hSession;  //a hack  
604                                  itCurrentSession = iter; // another hack                                  itCurrentSession = iter; // another hack
605                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
606                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
# Line 575  int LSCPServer::Main() { Line 614  int LSCPServer::Main() {
614                                          CloseConnection(iter);                                          CloseConnection(iter);
615                                  }                                  }
616                          }                          }
617                            currentSocket = -1;     //continuation of a hack
618                          //socket may have been closed, iter may be invalid, get out of the loop for now.                          //socket may have been closed, iter may be invalid, get out of the loop for now.
619                          //we'll be back if there is data.                          //we'll be back if there is data.
620                          break;                          break;
# Line 589  void LSCPServer::CloseConnection( std::v Line 629  void LSCPServer::CloseConnection( std::v
629          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection terminated on socket", socket));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection terminated on socket", socket));
630          Sessions.erase(iter);          Sessions.erase(iter);
631          FD_CLR(socket,  &fdSet);          FD_CLR(socket,  &fdSet);
632          SubscriptionMutex.Lock(); //Must unsubscribe this socket from all events (if any)          {
633          for (std::map< LSCPEvent::event_t, std::list<int> >::iterator iter = eventSubscriptions.begin(); iter != eventSubscriptions.end(); iter++) {              LockGuard lock(SubscriptionMutex);
634                  iter->second.remove(socket);              // Must unsubscribe this socket from all events (if any)
635          }              for (std::map< LSCPEvent::event_t, std::list<int> >::iterator iter = eventSubscriptions.begin(); iter != eventSubscriptions.end(); iter++) {
636          SubscriptionMutex.Unlock();                  iter->second.remove(socket);
637          NotifyMutex.Lock();              }
638            }
639            LockGuard lock(NotifyMutex);
640          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
641          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
642          #if defined(WIN32)          #if defined(WIN32)
# Line 602  void LSCPServer::CloseConnection( std::v Line 644  void LSCPServer::CloseConnection( std::v
644          #else          #else
645          close(socket);          close(socket);
646          #endif          #endif
         NotifyMutex.Unlock();  
 }  
   
 void LSCPServer::LockRTNotify() {  
     RTNotifyMutex.Lock();  
647  }  }
648    
649  void LSCPServer::UnlockRTNotify() {  void LSCPServer::CloseAllConnections() {
650      RTNotifyMutex.Unlock();      std::vector<yyparse_param_t>::iterator iter = Sessions.begin();
651        while(iter != Sessions.end()) {
652            CloseConnection(iter);
653            iter = Sessions.begin();
654        }
655  }  }
656    
657  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
658          int subs = 0;          int subs = 0;
659          SubscriptionMutex.Lock();          LockGuard lock(SubscriptionMutex);
660          for( std::list<LSCPEvent::event_t>::iterator iter = events.begin();          for( std::list<LSCPEvent::event_t>::iterator iter = events.begin();
661                          iter != events.end(); iter++)                          iter != events.end(); iter++)
662          {          {
663                  subs += eventSubscriptions.count(*iter);                  subs += eventSubscriptions.count(*iter);
664          }          }
         SubscriptionMutex.Unlock();  
665          return subs;          return subs;
666  }  }
667    
668  void LSCPServer::SendLSCPNotify( LSCPEvent event ) {  void LSCPServer::SendLSCPNotify( LSCPEvent event ) {
669          SubscriptionMutex.Lock();          LockGuard lock(SubscriptionMutex);
670          if (eventSubscriptions.count(event.GetType()) == 0) {          if (eventSubscriptions.count(event.GetType()) == 0) {
671                  SubscriptionMutex.Unlock();     //Nobody is subscribed to this event                  // Nobody is subscribed to this event
672                  return;                  return;
673          }          }
674          std::list<int>::iterator iter = eventSubscriptions[event.GetType()].begin();          std::list<int>::iterator iter = eventSubscriptions[event.GetType()].begin();
# Line 654  void LSCPServer::SendLSCPNotify( LSCPEve Line 694  void LSCPServer::SendLSCPNotify( LSCPEve
694                          }                          }
695                  }                  }
696          }          }
         SubscriptionMutex.Unlock();  
697  }  }
698    
699  extern int GetLSCPCommand( void *buf, int max_size ) {  extern int GetLSCPCommand( void *buf, int max_size ) {
# Line 671  extern int GetLSCPCommand( void *buf, in Line 710  extern int GetLSCPCommand( void *buf, in
710    
711          strcpy((char*) buf, command.c_str());          strcpy((char*) buf, command.c_str());
712          LSCPServer::bufferedCommands.erase(LSCPServer::currentSocket);          LSCPServer::bufferedCommands.erase(LSCPServer::currentSocket);
713          return command.size();          return (int) command.size();
714  }  }
715    
716  extern yyparse_param_t* GetCurrentYaccSession() {  extern yyparse_param_t* GetCurrentYaccSession() {
# Line 679  extern yyparse_param_t* GetCurrentYaccSe Line 718  extern yyparse_param_t* GetCurrentYaccSe
718  }  }
719    
720  /**  /**
721     * Generate the relevant LSCP documentation reference section if necessary.
722     * The documentation section for the currently active command on the LSCP
723     * shell's command line will be encoded in a special format, specifically for
724     * the LSCP shell application.
725     *
726     * @param line - current LSCP command line
727     * @param param - reentrant Bison parser parameters
728     *
729     * @return encoded reference string or empty string if nothing shall be sent
730     *         to LSCP shell (client) at this point
731     */
732    String LSCPServer::generateLSCPDocReply(const String& line, yyparse_param_t* param) {
733        String result;
734        lscp_ref_entry_t* ref = lscp_reference_for_command(line.c_str());
735        // Pointer comparison works here, since the function above always
736        // returns the same constant pointer for the respective LSCP
737        // command ... Only send the LSCP reference section to the client if
738        // another LSCP reference section became relevant now:
739        if (ref != param->pLSCPDocRef) {
740            param->pLSCPDocRef = ref;
741            if (ref) { // send a new LSCP doc section to client ...
742                result += "SHD:" + ToString(LSCP_SHD_MATCH) + ":" + String(ref->name) + "\n";
743                result += String(ref->section) + "\n";
744                result += "."; // dot line marks the end of the text for client
745            } else { // inform client that no LSCP doc section matches right now ...
746                result = "SHD:" + ToString(LSCP_SHD_NO_MATCH);
747            }
748        }
749        dmsg(4,("LSCP doc reply -> '%s'\n", result.c_str()));
750        return result;
751    }
752    
753    /**
754   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
755   * If command is read, it will return true. Otherwise false is returned.   * If command is read, it will return true. Otherwise false is returned.
756   * In any case the received portion (complete or incomplete) is saved into bufferedCommand map.   * In any case the received portion (complete or incomplete) is saved into bufferedCommand map.
757   */   */
758  bool LSCPServer::GetLSCPCommand( std::vector<yyparse_param_t>::iterator iter ) {  bool LSCPServer::GetLSCPCommand( std::vector<yyparse_param_t>::iterator iter ) {
759          int socket = (*iter).hSession;          int socket = (*iter).hSession;
760            int result;
761          char c;          char c;
762          int i = 0;          std::vector<char> input;
763    
764            // first get as many character as possible and add it to the 'input' buffer
765          while (true) {          while (true) {
766                  #if defined(WIN32)                  #if defined(WIN32)
767                  int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now                  result = (int)recv(socket, (char*)&c, 1, 0); //Read one character at a time for now
768                  #else                  #else
769                  int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now                  result = (int)recv(socket, (void*)&c, 1, 0); //Read one character at a time for now
770                  #endif                  #endif
771                  if (result == 0) { //socket was selected, so 0 here means client has closed the connection                  if (result == 1) input.push_back(c);
772                          CloseConnection(iter);                  else break; // end of input or some error
773                          break;                  if (c == '\n') break; // process line by line
774            }
775    
776            // process input buffer
777            for (int i = 0; i < input.size(); ++i) {
778                    c = input[i];
779                    if (c == '\r') continue; //Ignore CR
780                    if (c == '\n') {
781                            // only if the other side is the LSCP shell application:
782                            // check the current (incomplete) command line for syntax errors,
783                            // possible completions and report everything back to the shell
784                            if ((*iter).bShellInteract || (*iter).bShellAutoCorrect) {
785                                    String s = lscpParserProcessShellInteraction(bufferedCommands[socket], &(*iter), false);
786                                    if (!s.empty() && (*iter).bShellInteract) AnswerClient(s + "\n");
787                            }
788                            // if other side is LSCP shell application, send the relevant LSCP
789                            // documentation section of the current command line (if necessary)
790                            if ((*iter).bShellSendLSCPDoc && (*iter).bShellInteract) {
791                                    String s = generateLSCPDocReply(bufferedCommands[socket], &(*iter));
792                                    if (!s.empty()) AnswerClient(s + "\n");
793                            }
794                            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Received \'" + bufferedCommands[socket] + "\' on socket", socket));
795                            bufferedCommands[socket] += "\r\n";
796                            return true; //Complete command was read
797                    } else if (c == 2) { // custom ASCII code usage for moving cursor left (LSCP shell)
798                            if (iter->iCursorOffset + bufferedCommands[socket].size() > 0)
799                                    iter->iCursorOffset--;
800                    } else if (c == 3) { // custom ASCII code usage for moving cursor right (LSCP shell)
801                            if (iter->iCursorOffset < 0) iter->iCursorOffset++;
802                    } else {
803                            ssize_t cursorPos = bufferedCommands[socket].size() + iter->iCursorOffset;
804                            // backspace character - should only happen with shell
805                            if (c == '\b') {
806                                    if (!bufferedCommands[socket].empty() && cursorPos > 0)
807                                            bufferedCommands[socket].erase(cursorPos - 1, 1);
808                            } else { // append (or insert) new character (at current cursor position) ...
809                                    if (cursorPos >= 0)
810                                            bufferedCommands[socket].insert(cursorPos, String(1,c)); // insert
811                                    else
812                                            bufferedCommands[socket] += c; // append
813                            }
814                  }                  }
815                  if (result == 1) {                  // Only if the other side (client) is the LSCP shell application:
816                          if (c == '\r')                  // The following block takes care about automatic correction, auto
817                                  continue; //Ignore CR                  // completion (and suggestions), LSCP reference documentation, etc.
818                          if (c == '\n') {                  // The "if" statement here is for optimization reasons, so that the
819                                  LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Received \'" + bufferedCommands[socket] + "\' on socket", socket));                  // heavy LSCP grammar evaluation algorithm is only executed once for an
820                                  bufferedCommands[socket] += "\r\n";                  // entire command line received.
821                                  return true; //Complete command was read                  if (i == input.size() - 1) {
822                            // check the current (incomplete) command line for syntax errors,
823                            // possible completions and report everything back to the shell
824                            if ((*iter).bShellInteract || (*iter).bShellAutoCorrect) {
825                                    String s = lscpParserProcessShellInteraction(bufferedCommands[socket], &(*iter), true);
826                                    if (!s.empty() && (*iter).bShellInteract && i == input.size() - 1)
827                                            AnswerClient(s + "\n");
828                            }
829                            // if other side is LSCP shell application, send the relevant LSCP
830                            // documentation section of the current command line (if necessary)
831                            if ((*iter).bShellSendLSCPDoc && (*iter).bShellInteract) {
832                                    String s = generateLSCPDocReply(bufferedCommands[socket], &(*iter));
833                                    if (!s.empty()) AnswerClient(s + "\n");
834                          }                          }
                         bufferedCommands[socket] += c;  
835                  }                  }
836                  #if defined(WIN32)          }
837                  if (result == SOCKET_ERROR) {  
838                      int wsa_lasterror = WSAGetLastError();          // handle network errors ...
839                          if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.          if (result == 0) { //socket was selected, so 0 here means client has closed the connection
840                    CloseConnection(iter);
841                    return false;
842            }
843            #if defined(WIN32)
844            if (result == SOCKET_ERROR) {
845                    int wsa_lasterror = WSAGetLastError();
846                    if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
847                            return false;
848                    dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
849                    CloseConnection(iter);
850                    return false;
851            }
852            #else
853            if (result == -1) {
854                    if (errno == EAGAIN) //Would block, try again later.
855                            return false;
856                    switch(errno) {
857                            case EBADF:
858                                    dmsg(2,("LSCPScanner: The argument s is an invalid descriptor.\n"));
859                                  return false;                                  return false;
860                          dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));                          case ECONNREFUSED:
861                          CloseConnection(iter);                                  dmsg(2,("LSCPScanner: A remote host refused to allow the network connection (typically because it is not running the requested service).\n"));
862                          break;                                  return false;
863                  }                          case ENOTCONN:
864                  #else                                  dmsg(2,("LSCPScanner: The socket is associated with a connection-oriented protocol and has not been connected (see connect(2) and accept(2)).\n"));
865                  if (result == -1) {                                  return false;
866                          if (errno == EAGAIN) //Would block, try again later.                          case ENOTSOCK:
867                                    dmsg(2,("LSCPScanner: The argument s does not refer to a socket.\n"));
868                                    return false;
869                            case EAGAIN:
870                                    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"));
871                                    return false;
872                            case EINTR:
873                                    dmsg(2,("LSCPScanner: The receive was interrupted by delivery of a signal before any data were available.\n"));
874                                    return false;
875                            case EFAULT:
876                                    dmsg(2,("LSCPScanner: The receive buffer pointer(s) point outside the process's address space.\n"));
877                                    return false;
878                            case EINVAL:
879                                    dmsg(2,("LSCPScanner: Invalid argument passed.\n"));
880                                    return false;
881                            case ENOMEM:
882                                    dmsg(2,("LSCPScanner: Could not allocate memory for recvmsg.\n"));
883                                    return false;
884                            default:
885                                    dmsg(2,("LSCPScanner: Unknown recv() error.\n"));
886                                  return false;                                  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;  
887                  }                  }
888                  #endif                  CloseConnection(iter);
889                    return false;
890          }          }
891            #endif
892    
893          return false;          return false;
894  }  }
895    
# Line 767  bool LSCPServer::GetLSCPCommand( std::ve Line 900  bool LSCPServer::GetLSCPCommand( std::ve
900   * @param ReturnMessage - message that will be send to the client   * @param ReturnMessage - message that will be send to the client
901   */   */
902  void LSCPServer::AnswerClient(String ReturnMessage) {  void LSCPServer::AnswerClient(String ReturnMessage) {
903      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str()));      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage='%s')", ReturnMessage.c_str()));
904      if (currentSocket != -1) {      if (currentSocket != -1) {
905              NotifyMutex.Lock();              LockGuard lock(NotifyMutex);
906    
907            // just if other side is LSCP shell: in case respose is a multi-line
908            // one, then inform client about it before sending the actual mult-line
909            // response
910            if (GetCurrentYaccSession()->bShellInteract) {
911                // check if this is a multi-line response
912                int n = 0;
913                for (int i = 0; i < ReturnMessage.size(); ++i)
914                    if (ReturnMessage[i] == '\n') ++n;
915                if (n >= 2) {
916                    dmsg(2,("LSCP Shell <- expect mult-line response\n"));
917                    String s = LSCP_SHK_EXPECT_MULTI_LINE "\r\n";
918    #ifdef MSG_NOSIGNAL
919                    send(currentSocket, s.c_str(), s.size(), MSG_NOSIGNAL);
920    #else
921                    send(currentSocket, s.c_str(), s.size(), 0);
922    #endif                
923                }
924            }
925    
926  #ifdef MSG_NOSIGNAL  #ifdef MSG_NOSIGNAL
927              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), MSG_NOSIGNAL);              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), MSG_NOSIGNAL);
928  #else  #else
929              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);
930  #endif  #endif
             NotifyMutex.Unlock();  
931      }      }
932  }  }
933    
# Line 925  String LSCPServer::SetEngineType(String Line 1077  String LSCPServer::SetEngineType(String
1077      try {      try {
1078          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1079          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1080          LockRTNotify();          LockGuard lock(RTNotifyMutex);
1081          pSamplerChannel->SetEngineType(EngineName);          pSamplerChannel->SetEngineType(EngineName);
1082          if(HasSoloChannel()) pSamplerChannel->GetEngineChannel()->SetMute(-1);          if(HasSoloChannel()) pSamplerChannel->GetEngineChannel()->SetMute(-1);
         UnlockRTNotify();  
1083      }      }
1084      catch (Exception e) {      catch (Exception e) {
1085           result.Error(e);           result.Error(e);
# Line 968  String LSCPServer::ListChannels() { Line 1119  String LSCPServer::ListChannels() {
1119   */   */
1120  String LSCPServer::AddChannel() {  String LSCPServer::AddChannel() {
1121      dmsg(2,("LSCPServer: AddChannel()\n"));      dmsg(2,("LSCPServer: AddChannel()\n"));
1122      LockRTNotify();      SamplerChannel* pSamplerChannel;
1123      SamplerChannel* pSamplerChannel = pSampler->AddSamplerChannel();      {
1124      UnlockRTNotify();          LockGuard lock(RTNotifyMutex);
1125            pSamplerChannel = pSampler->AddSamplerChannel();
1126        }
1127      LSCPResultSet result(pSamplerChannel->Index());      LSCPResultSet result(pSamplerChannel->Index());
1128      return result.Produce();      return result.Produce();
1129  }  }
# Line 981  String LSCPServer::AddChannel() { Line 1134  String LSCPServer::AddChannel() {
1134  String LSCPServer::RemoveChannel(uint uiSamplerChannel) {  String LSCPServer::RemoveChannel(uint uiSamplerChannel) {
1135      dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel));
1136      LSCPResultSet result;      LSCPResultSet result;
1137      LockRTNotify();      {
1138      pSampler->RemoveSamplerChannel(uiSamplerChannel);          LockGuard lock(RTNotifyMutex);
1139      UnlockRTNotify();          pSampler->RemoveSamplerChannel(uiSamplerChannel);
1140        }
1141      return result.Produce();      return result.Produce();
1142  }  }
1143    
# Line 994  String LSCPServer::GetAvailableEngines() Line 1148  String LSCPServer::GetAvailableEngines()
1148      dmsg(2,("LSCPServer: GetAvailableEngines()\n"));      dmsg(2,("LSCPServer: GetAvailableEngines()\n"));
1149      LSCPResultSet result;      LSCPResultSet result;
1150      try {      try {
1151          int n = EngineFactory::AvailableEngineTypes().size();          int n = (int)EngineFactory::AvailableEngineTypes().size();
1152          result.Add(n);          result.Add(n);
1153      }      }
1154      catch (Exception e) {      catch (Exception e) {
# Line 1026  String LSCPServer::ListAvailableEngines( Line 1180  String LSCPServer::ListAvailableEngines(
1180  String LSCPServer::GetEngineInfo(String EngineName) {  String LSCPServer::GetEngineInfo(String EngineName) {
1181      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));
1182      LSCPResultSet result;      LSCPResultSet result;
1183      LockRTNotify();      {
1184      try {          LockGuard lock(RTNotifyMutex);
1185          Engine* pEngine = EngineFactory::Create(EngineName);          try {
1186          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));              Engine* pEngine = EngineFactory::Create(EngineName);
1187          result.Add("VERSION",     pEngine->Version());              result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
1188          EngineFactory::Destroy(pEngine);              result.Add("VERSION",     pEngine->Version());
1189      }              EngineFactory::Destroy(pEngine);
1190      catch (Exception e) {          }
1191           result.Error(e);          catch (Exception e) {
1192                result.Error(e);
1193            }
1194      }      }
     UnlockRTNotify();  
1195      return result.Produce();      return result.Produce();
1196  }  }
1197    
# Line 1197  String LSCPServer::GetAvailableAudioOutp Line 1352  String LSCPServer::GetAvailableAudioOutp
1352      dmsg(2,("LSCPServer: GetAvailableAudioOutputDrivers()\n"));      dmsg(2,("LSCPServer: GetAvailableAudioOutputDrivers()\n"));
1353      LSCPResultSet result;      LSCPResultSet result;
1354      try {      try {
1355          int n = AudioOutputDeviceFactory::AvailableDrivers().size();          int n = (int) AudioOutputDeviceFactory::AvailableDrivers().size();
1356          result.Add(n);          result.Add(n);
1357      }      }
1358      catch (Exception e) {      catch (Exception e) {
# Line 1223  String LSCPServer::GetAvailableMidiInput Line 1378  String LSCPServer::GetAvailableMidiInput
1378      dmsg(2,("LSCPServer: GetAvailableMidiInputDrivers()\n"));      dmsg(2,("LSCPServer: GetAvailableMidiInputDrivers()\n"));
1379      LSCPResultSet result;      LSCPResultSet result;
1380      try {      try {
1381          int n = MidiInputDeviceFactory::AvailableDrivers().size();          int n = (int)MidiInputDeviceFactory::AvailableDrivers().size();
1382          result.Add(n);          result.Add(n);
1383      }      }
1384      catch (Exception e) {      catch (Exception e) {
# Line 1259  String LSCPServer::GetMidiInputDriverInf Line 1414  String LSCPServer::GetMidiInputDriverInf
1414              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1415                  if (s != "") s += ",";                  if (s != "") s += ",";
1416                  s += iter->first;                  s += iter->first;
1417                    delete iter->second;
1418              }              }
1419              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1420          }          }
# Line 1283  String LSCPServer::GetAudioOutputDriverI Line 1439  String LSCPServer::GetAudioOutputDriverI
1439              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1440                  if (s != "") s += ",";                  if (s != "") s += ",";
1441                  s += iter->first;                  s += iter->first;
1442                    delete iter->second;
1443              }              }
1444              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1445          }          }
# Line 1294  String LSCPServer::GetAudioOutputDriverI Line 1451  String LSCPServer::GetAudioOutputDriverI
1451  }  }
1452    
1453  String LSCPServer::GetMidiInputDriverParameterInfo(String Driver, String Parameter, std::map<String,String> DependencyList) {  String LSCPServer::GetMidiInputDriverParameterInfo(String Driver, String Parameter, std::map<String,String> DependencyList) {
1454      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())));
1455      LSCPResultSet result;      LSCPResultSet result;
1456      try {      try {
1457          DeviceCreationParameter* pParameter = MidiInputDeviceFactory::GetDriverParameter(Driver, Parameter);          DeviceCreationParameter* pParameter = MidiInputDeviceFactory::GetDriverParameter(Driver, Parameter);
# Line 1313  String LSCPServer::GetMidiInputDriverPar Line 1470  String LSCPServer::GetMidiInputDriverPar
1470          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1471          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1472          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1473            delete pParameter;
1474      }      }
1475      catch (Exception e) {      catch (Exception e) {
1476          result.Error(e);          result.Error(e);
# Line 1321  String LSCPServer::GetMidiInputDriverPar Line 1479  String LSCPServer::GetMidiInputDriverPar
1479  }  }
1480    
1481  String LSCPServer::GetAudioOutputDriverParameterInfo(String Driver, String Parameter, std::map<String,String> DependencyList) {  String LSCPServer::GetAudioOutputDriverParameterInfo(String Driver, String Parameter, std::map<String,String> DependencyList) {
1482      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())));
1483      LSCPResultSet result;      LSCPResultSet result;
1484      try {      try {
1485          DeviceCreationParameter* pParameter = AudioOutputDeviceFactory::GetDriverParameter(Driver, Parameter);          DeviceCreationParameter* pParameter = AudioOutputDeviceFactory::GetDriverParameter(Driver, Parameter);
# Line 1340  String LSCPServer::GetAudioOutputDriverP Line 1498  String LSCPServer::GetAudioOutputDriverP
1498          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1499          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1500          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1501            delete pParameter;
1502      }      }
1503      catch (Exception e) {      catch (Exception e) {
1504          result.Error(e);          result.Error(e);
# Line 1477  String LSCPServer::GetMidiInputPortInfo( Line 1636  String LSCPServer::GetMidiInputPortInfo(
1636  }  }
1637    
1638  String LSCPServer::GetAudioOutputChannelInfo(uint DeviceId, uint ChannelId) {  String LSCPServer::GetAudioOutputChannelInfo(uint DeviceId, uint ChannelId) {
1639      dmsg(2,("LSCPServer: GetAudioOutputChannelInfo(DeviceId=%d,ChannelId)\n",DeviceId,ChannelId));      dmsg(2,("LSCPServer: GetAudioOutputChannelInfo(DeviceId=%u,ChannelId=%u)\n",DeviceId,ChannelId));
1640      LSCPResultSet result;      LSCPResultSet result;
1641      try {      try {
1642          // get audio output device          // get audio output device
# Line 1681  String LSCPServer::SetAudioOutputChannel Line 1840  String LSCPServer::SetAudioOutputChannel
1840  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {
1841      dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));      dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));
1842      LSCPResultSet result;      LSCPResultSet result;
1843      LockRTNotify();      {
1844            LockGuard lock(RTNotifyMutex);
1845            try {
1846                SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1847                if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1848                std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1849                if (!devices.count(AudioDeviceId)) throw Exception("There is no audio output device with index " + ToString(AudioDeviceId));
1850                AudioOutputDevice* pDevice = devices[AudioDeviceId];
1851                pSamplerChannel->SetAudioOutputDevice(pDevice);
1852            }
1853            catch (Exception e) {
1854                result.Error(e);
1855            }
1856        }
1857        return result.Produce();
1858    }
1859    
1860    String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {
1861        dmsg(2,("LSCPServer: SetAudioOutputType(String AudioOutputDriver=%s, SamplerChannel=%d)\n",AudioOutputDriver.c_str(),uiSamplerChannel));
1862        LSCPResultSet result;
1863        {
1864            LockGuard lock(RTNotifyMutex);
1865            try {
1866                SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1867                if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1868                // Driver type name aliasing...
1869                if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA";
1870                if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK";
1871                // Check if there's one audio output device already created
1872                // for the intended audio driver type (AudioOutputDriver)...
1873                AudioOutputDevice *pDevice = NULL;
1874                std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1875                std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();
1876                for (; iter != devices.end(); iter++) {
1877                    if ((iter->second)->Driver() == AudioOutputDriver) {
1878                        pDevice = iter->second;
1879                        break;
1880                    }
1881                }
1882                // If it doesn't exist, create a new one with default parameters...
1883                if (pDevice == NULL) {
1884                    std::map<String,String> params;
1885                    pDevice = pSampler->CreateAudioOutputDevice(AudioOutputDriver, params);
1886                }
1887                // Must have a device...
1888                if (pDevice == NULL)
1889                    throw Exception("Internal error: could not create audio output device.");
1890                // Set it as the current channel device...
1891                pSamplerChannel->SetAudioOutputDevice(pDevice);
1892            }
1893            catch (Exception e) {
1894                result.Error(e);
1895            }
1896        }
1897        return result.Produce();
1898    }
1899    
1900    String LSCPServer::AddChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId, uint MIDIPort) {
1901        dmsg(2,("LSCPServer: AddChannelMidiInput(uiSamplerChannel=%d, MIDIDeviceId=%d, MIDIPort=%d)\n",uiSamplerChannel,MIDIDeviceId,MIDIPort));
1902        LSCPResultSet result;
1903      try {      try {
1904          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1905          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1906          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();  
1907          if (!devices.count(AudioDeviceId)) throw Exception("There is no audio output device with index " + ToString(AudioDeviceId));          std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1908          AudioOutputDevice* pDevice = devices[AudioDeviceId];          if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1909          pSamplerChannel->SetAudioOutputDevice(pDevice);          MidiInputDevice* pDevice = devices[MIDIDeviceId];
1910    
1911            MidiInputPort* pPort = pDevice->GetPort(MIDIPort);
1912            if (!pPort) throw Exception("There is no MIDI input port with index " + ToString(MIDIPort) + " on MIDI input device with index " + ToString(MIDIDeviceId));
1913    
1914            pSamplerChannel->Connect(pPort);
1915        } catch (Exception e) {
1916            result.Error(e);
1917      }      }
1918      catch (Exception e) {      return result.Produce();
1919           result.Error(e);  }
1920    
1921    String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel) {
1922        dmsg(2,("LSCPServer: RemoveChannelMidiInput(uiSamplerChannel=%d)\n",uiSamplerChannel));
1923        LSCPResultSet result;
1924        try {
1925            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1926            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1927            pSamplerChannel->DisconnectAllMidiInputPorts();
1928        } catch (Exception e) {
1929            result.Error(e);
1930      }      }
     UnlockRTNotify();  
1931      return result.Produce();      return result.Produce();
1932  }  }
1933    
1934  String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {  String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId) {
1935      dmsg(2,("LSCPServer: SetAudioOutputType(String AudioOutputDriver=%s, SamplerChannel=%d)\n",AudioOutputDriver.c_str(),uiSamplerChannel));      dmsg(2,("LSCPServer: RemoveChannelMidiInput(uiSamplerChannel=%d, MIDIDeviceId=%d)\n",uiSamplerChannel,MIDIDeviceId));
1936      LSCPResultSet result;      LSCPResultSet result;
     LockRTNotify();  
1937      try {      try {
1938          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1939          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1940          // Driver type name aliasing...  
1941          if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA";          std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1942          if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK";          if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1943          // Check if there's one audio output device already created          MidiInputDevice* pDevice = devices[MIDIDeviceId];
1944          // for the intended audio driver type (AudioOutputDriver)...          
1945          AudioOutputDevice *pDevice = NULL;          std::vector<MidiInputPort*> vPorts = pSamplerChannel->GetMidiInputPorts();
1946          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          for (int i = 0; i < vPorts.size(); ++i)
1947          std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();              if (vPorts[i]->GetDevice() == pDevice)
1948          for (; iter != devices.end(); iter++) {                  pSamplerChannel->Disconnect(vPorts[i]);
1949              if ((iter->second)->Driver() == AudioOutputDriver) {  
1950                  pDevice = iter->second;      } catch (Exception e) {
1951                  break;          result.Error(e);
             }  
         }  
         // If it doesn't exist, create a new one with default parameters...  
         if (pDevice == NULL) {  
             std::map<String,String> 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);  
1952      }      }
1953      catch (Exception e) {      return result.Produce();
1954           result.Error(e);  }
1955    
1956    String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId, uint MIDIPort) {
1957        dmsg(2,("LSCPServer: RemoveChannelMidiInput(uiSamplerChannel=%d, MIDIDeviceId=%d, MIDIPort=%d)\n",uiSamplerChannel,MIDIDeviceId,MIDIPort));
1958        LSCPResultSet result;
1959        try {
1960            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1961            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1962    
1963            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1964            if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1965            MidiInputDevice* pDevice = devices[MIDIDeviceId];
1966    
1967            MidiInputPort* pPort = pDevice->GetPort(MIDIPort);
1968            if (!pPort) throw Exception("There is no MIDI input port with index " + ToString(MIDIPort) + " on MIDI input device with index " + ToString(MIDIDeviceId));
1969    
1970            pSamplerChannel->Disconnect(pPort);
1971        } catch (Exception e) {
1972            result.Error(e);
1973        }
1974        return result.Produce();
1975    }
1976    
1977    String LSCPServer::ListChannelMidiInputs(uint uiSamplerChannel) {
1978        dmsg(2,("LSCPServer: ListChannelMidiInputs(uiSamplerChannel=%d)\n",uiSamplerChannel));
1979        LSCPResultSet result;
1980        try {
1981            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1982            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1983            std::vector<MidiInputPort*> vPorts = pSamplerChannel->GetMidiInputPorts();
1984    
1985            String s;
1986            for (int i = 0; i < vPorts.size(); ++i) {
1987                const int iDeviceID = vPorts[i]->GetDevice()->MidiInputDeviceID();
1988                const int iPortNr   = vPorts[i]->GetPortNumber();
1989                if (s.size()) s += ",";
1990                s += "{" + ToString(iDeviceID) + ","
1991                         + ToString(iPortNr) + "}";
1992            }
1993            result.Add(s);
1994        } catch (Exception e) {
1995            result.Error(e);
1996      }      }
     UnlockRTNotify();  
1997      return result.Produce();      return result.Produce();
1998  }  }
1999    
# Line 1806  String LSCPServer::SetMIDIInputType(Stri Line 2067  String LSCPServer::SetMIDIInputType(Stri
2067              pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);              pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);
2068              // Make it with at least one initial port.              // Make it with at least one initial port.
2069              std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();              std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
             parameters["PORTS"]->SetValue("1");  
2070          }          }
2071          // Must have a device...          // Must have a device...
2072          if (pDevice == NULL)          if (pDevice == NULL)
# Line 2176  String LSCPServer::GetMidiInstrumentMaps Line 2436  String LSCPServer::GetMidiInstrumentMaps
2436      dmsg(2,("LSCPServer: GetMidiInstrumentMaps()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMaps()\n"));
2437      LSCPResultSet result;      LSCPResultSet result;
2438      try {      try {
2439          result.Add(MidiInstrumentMapper::Maps().size());          result.Add(int(MidiInstrumentMapper::Maps().size()));
2440      } catch (Exception e) {      } catch (Exception e) {
2441          result.Error(e);          result.Error(e);
2442      }      }
# Line 2343  String LSCPServer::GetFxSendInfo(uint ui Line 2603  String LSCPServer::GetFxSendInfo(uint ui
2603              AudioRouting += ToString(pFxSend->DestinationChannel(chan));              AudioRouting += ToString(pFxSend->DestinationChannel(chan));
2604          }          }
2605    
2606            const String sEffectRouting =
2607                (pFxSend->DestinationEffectChain() >= 0 && pFxSend->DestinationEffectChainPosition() >= 0)
2608                    ? ToString(pFxSend->DestinationEffectChain()) + "," + ToString(pFxSend->DestinationEffectChainPosition())
2609                    : "NONE";
2610    
2611          // success          // success
2612          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2613          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2614          result.Add("LEVEL", ToString(pFxSend->Level()));          result.Add("LEVEL", ToString(pFxSend->Level()));
2615          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
2616            result.Add("EFFECT", sEffectRouting);
2617      } catch (Exception e) {      } catch (Exception e) {
2618          result.Error(e);          result.Error(e);
2619      }      }
# Line 2410  String LSCPServer::SetFxSendLevel(uint u Line 2676  String LSCPServer::SetFxSendLevel(uint u
2676      return result.Produce();      return result.Produce();
2677  }  }
2678    
2679    String LSCPServer::SetFxSendEffect(uint uiSamplerChannel, uint FxSendID, int iSendEffectChain, int iEffectChainPosition) {
2680        dmsg(2,("LSCPServer: SetFxSendEffect(%d,%d)\n", iSendEffectChain, iEffectChainPosition));
2681        LSCPResultSet result;
2682        try {
2683            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2684    
2685            pFxSend->SetDestinationEffect(iSendEffectChain, iEffectChainPosition);
2686            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2687        } catch (Exception e) {
2688            result.Error(e);
2689        }
2690        return result.Produce();
2691    }
2692    
2693    String LSCPServer::GetAvailableEffects() {
2694        dmsg(2,("LSCPServer: GetAvailableEffects()\n"));
2695        LSCPResultSet result;
2696        try {
2697            int n = EffectFactory::AvailableEffectsCount();
2698            result.Add(n);
2699        }
2700        catch (Exception e) {
2701            result.Error(e);
2702        }
2703        return result.Produce();
2704    }
2705    
2706    String LSCPServer::ListAvailableEffects() {
2707        dmsg(2,("LSCPServer: ListAvailableEffects()\n"));
2708        LSCPResultSet result;
2709        String list;
2710        try {
2711            //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
2712            int n = EffectFactory::AvailableEffectsCount();
2713            for (int i = 0; i < n; i++) {
2714                if (i) list += ",";
2715                list += ToString(i);
2716            }
2717        }
2718        catch (Exception e) {
2719            result.Error(e);
2720        }
2721        result.Add(list);
2722        return result.Produce();
2723    }
2724    
2725    String LSCPServer::GetEffectInfo(int iEffectIndex) {
2726        dmsg(2,("LSCPServer: GetEffectInfo(%d)\n", iEffectIndex));
2727        LSCPResultSet result;
2728        try {
2729            EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(iEffectIndex);
2730            if (!pEffectInfo)
2731                throw Exception("There is no effect with index " + ToString(iEffectIndex));
2732    
2733            // convert the filename into the correct encoding as defined for LSCP
2734            // (especially in terms of special characters -> escape sequences)
2735    #if WIN32
2736            const String dllFileName = Path::fromWindows(pEffectInfo->Module()).toLscp();
2737    #else
2738            // assuming POSIX
2739            const String dllFileName = Path::fromPosix(pEffectInfo->Module()).toLscp();
2740    #endif
2741    
2742            result.Add("SYSTEM", pEffectInfo->EffectSystem());
2743            result.Add("MODULE", dllFileName);
2744            result.Add("NAME", _escapeLscpResponse(pEffectInfo->Name()));
2745            result.Add("DESCRIPTION", _escapeLscpResponse(pEffectInfo->Description()));
2746        }
2747        catch (Exception e) {
2748            result.Error(e);
2749        }
2750        return result.Produce();    
2751    }
2752    
2753    String LSCPServer::GetEffectInstanceInfo(int iEffectInstance) {
2754        dmsg(2,("LSCPServer: GetEffectInstanceInfo(%d)\n", iEffectInstance));
2755        LSCPResultSet result;
2756        try {
2757            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2758            if (!pEffect)
2759                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2760    
2761            EffectInfo* pEffectInfo = pEffect->GetEffectInfo();
2762    
2763            // convert the filename into the correct encoding as defined for LSCP
2764            // (especially in terms of special characters -> escape sequences)
2765    #if WIN32
2766            const String dllFileName = Path::fromWindows(pEffectInfo->Module()).toLscp();
2767    #else
2768            // assuming POSIX
2769            const String dllFileName = Path::fromPosix(pEffectInfo->Module()).toLscp();
2770    #endif
2771    
2772            result.Add("SYSTEM", pEffectInfo->EffectSystem());
2773            result.Add("MODULE", dllFileName);
2774            result.Add("NAME", _escapeLscpResponse(pEffectInfo->Name()));
2775            result.Add("DESCRIPTION", _escapeLscpResponse(pEffectInfo->Description()));
2776            result.Add("INPUT_CONTROLS", ToString(pEffect->InputControlCount()));
2777        }
2778        catch (Exception e) {
2779            result.Error(e);
2780        }
2781        return result.Produce();
2782    }
2783    
2784    String LSCPServer::GetEffectInstanceInputControlInfo(int iEffectInstance, int iInputControlIndex) {
2785        dmsg(2,("LSCPServer: GetEffectInstanceInputControlInfo(%d,%d)\n", iEffectInstance, iInputControlIndex));
2786        LSCPResultSet result;
2787        try {
2788            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2789            if (!pEffect)
2790                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2791    
2792            EffectControl* pEffectControl = pEffect->InputControl(iInputControlIndex);
2793            if (!pEffectControl)
2794                throw Exception(
2795                    "Effect instance " + ToString(iEffectInstance) +
2796                    " does not have an input control with index " +
2797                    ToString(iInputControlIndex)
2798                );
2799    
2800            result.Add("DESCRIPTION", _escapeLscpResponse(pEffectControl->Description()));
2801            result.Add("VALUE", pEffectControl->Value());
2802            if (pEffectControl->MinValue())
2803                 result.Add("RANGE_MIN", *pEffectControl->MinValue());
2804            if (pEffectControl->MaxValue())
2805                 result.Add("RANGE_MAX", *pEffectControl->MaxValue());
2806            if (!pEffectControl->Possibilities().empty())
2807                 result.Add("POSSIBILITIES", pEffectControl->Possibilities());
2808            if (pEffectControl->DefaultValue())
2809                 result.Add("DEFAULT", *pEffectControl->DefaultValue());
2810        } catch (Exception e) {
2811            result.Error(e);
2812        }
2813        return result.Produce();
2814    }
2815    
2816    String LSCPServer::SetEffectInstanceInputControlValue(int iEffectInstance, int iInputControlIndex, double dValue) {
2817        dmsg(2,("LSCPServer: SetEffectInstanceInputControlValue(%d,%d,%f)\n", iEffectInstance, iInputControlIndex, dValue));
2818        LSCPResultSet result;
2819        try {
2820            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2821            if (!pEffect)
2822                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2823    
2824            EffectControl* pEffectControl = pEffect->InputControl(iInputControlIndex);
2825            if (!pEffectControl)
2826                throw Exception(
2827                    "Effect instance " + ToString(iEffectInstance) +
2828                    " does not have an input control with index " +
2829                    ToString(iInputControlIndex)
2830                );
2831    
2832            pEffectControl->SetValue(dValue);
2833            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_info, iEffectInstance));
2834        } catch (Exception e) {
2835            result.Error(e);
2836        }
2837        return result.Produce();
2838    }
2839    
2840    String LSCPServer::CreateEffectInstance(int iEffectIndex) {
2841        dmsg(2,("LSCPServer: CreateEffectInstance(%d)\n", iEffectIndex));
2842        LSCPResultSet result;
2843        try {
2844            EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(iEffectIndex);
2845            if (!pEffectInfo)
2846                throw Exception("There is no effect with index " + ToString(iEffectIndex));
2847            Effect* pEffect = EffectFactory::Create(pEffectInfo);
2848            result = pEffect->ID(); // success
2849            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_count, EffectFactory::EffectInstancesCount()));
2850        } catch (Exception e) {
2851            result.Error(e);
2852        }
2853        return result.Produce();
2854    }
2855    
2856    String LSCPServer::CreateEffectInstance(String effectSystem, String module, String effectName) {
2857        dmsg(2,("LSCPServer: CreateEffectInstance('%s','%s','%s')\n", effectSystem.c_str(), module.c_str(), effectName.c_str()));
2858        LSCPResultSet result;
2859        try {
2860            // to allow loading the same LSCP session file on different systems
2861            // successfully, probably with different effect plugin DLL paths or even
2862            // running completely different operating systems, we do the following
2863            // for finding the right effect:
2864            //
2865            // first try to search for an exact match of the effect plugin DLL
2866            // (a.k.a 'module'), to avoid picking the wrong DLL with the same
2867            // effect name ...
2868            EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_MATCH_EXACTLY);
2869            // ... if no effect with exactly matchin DLL filename was found, then
2870            // try to lower the restrictions of matching the effect plugin DLL
2871            // filename and try again and again ...
2872            if (!pEffectInfo) {
2873                dmsg(2,("no exact module match, trying MODULE_IGNORE_PATH\n"));
2874                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH);
2875            }
2876            if (!pEffectInfo) {
2877                dmsg(2,("no module match, trying MODULE_IGNORE_PATH | MODULE_IGNORE_CASE\n"));
2878                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH | EffectFactory::MODULE_IGNORE_CASE);
2879            }
2880            if (!pEffectInfo) {
2881                dmsg(2,("no module match, trying MODULE_IGNORE_PATH | MODULE_IGNORE_CASE | MODULE_IGNORE_EXTENSION\n"));
2882                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH | EffectFactory::MODULE_IGNORE_CASE | EffectFactory::MODULE_IGNORE_EXTENSION);
2883            }
2884            // ... if there was still no effect found, then completely ignore the
2885            // DLL plugin filename argument and just search for the matching effect
2886            // system type and effect name
2887            if (!pEffectInfo) {
2888                dmsg(2,("no module match, trying MODULE_IGNORE_ALL\n"));
2889                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_ALL);
2890            }
2891            if (!pEffectInfo)
2892                throw Exception("There is no such effect '" + effectSystem + "' '" + module + "' '" + effectName + "'");
2893    
2894            Effect* pEffect = EffectFactory::Create(pEffectInfo);
2895            result = LSCPResultSet(pEffect->ID());
2896            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_count, EffectFactory::EffectInstancesCount()));
2897        } catch (Exception e) {
2898            result.Error(e);
2899        }
2900        return result.Produce();
2901    }
2902    
2903    String LSCPServer::DestroyEffectInstance(int iEffectInstance) {
2904        dmsg(2,("LSCPServer: DestroyEffectInstance(%d)\n", iEffectInstance));
2905        LSCPResultSet result;
2906        try {
2907            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2908            if (!pEffect)
2909                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2910            EffectFactory::Destroy(pEffect);
2911            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_count, EffectFactory::EffectInstancesCount()));
2912        } catch (Exception e) {
2913            result.Error(e);
2914        }
2915        return result.Produce();
2916    }
2917    
2918    String LSCPServer::GetEffectInstances() {
2919        dmsg(2,("LSCPServer: GetEffectInstances()\n"));
2920        LSCPResultSet result;
2921        try {
2922            int n = EffectFactory::EffectInstancesCount();
2923            result.Add(n);
2924        } catch (Exception e) {
2925            result.Error(e);
2926        }
2927        return result.Produce();
2928    }
2929    
2930    String LSCPServer::ListEffectInstances() {
2931        dmsg(2,("LSCPServer: ListEffectInstances()\n"));
2932        LSCPResultSet result;
2933        String list;
2934        try {
2935            int n = EffectFactory::EffectInstancesCount();
2936            for (int i = 0; i < n; i++) {
2937                Effect* pEffect = EffectFactory::GetEffectInstance(i);
2938                if (i) list += ",";
2939                list += ToString(pEffect->ID());
2940            }
2941        } catch (Exception e) {
2942            result.Error(e);
2943        }
2944        result.Add(list);
2945        return result.Produce();
2946    }
2947    
2948    String LSCPServer::GetSendEffectChains(int iAudioOutputDevice) {
2949        dmsg(2,("LSCPServer: GetSendEffectChains(%d)\n", iAudioOutputDevice));
2950        LSCPResultSet result;
2951        try {
2952            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2953            if (!devices.count(iAudioOutputDevice))
2954                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2955            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2956            int n = pDevice->SendEffectChainCount();
2957            result.Add(n);
2958        } catch (Exception e) {
2959            result.Error(e);
2960        }
2961        return result.Produce();
2962    }
2963    
2964    String LSCPServer::ListSendEffectChains(int iAudioOutputDevice) {
2965        dmsg(2,("LSCPServer: ListSendEffectChains(%d)\n", iAudioOutputDevice));
2966        LSCPResultSet result;
2967        String list;
2968        try {
2969            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2970            if (!devices.count(iAudioOutputDevice))
2971                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2972            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2973            int n = pDevice->SendEffectChainCount();
2974            for (int i = 0; i < n; i++) {
2975                EffectChain* pEffectChain = pDevice->SendEffectChain(i);
2976                if (i) list += ",";
2977                list += ToString(pEffectChain->ID());
2978            }
2979        } catch (Exception e) {
2980            result.Error(e);
2981        }
2982        result.Add(list);
2983        return result.Produce();
2984    }
2985    
2986    String LSCPServer::AddSendEffectChain(int iAudioOutputDevice) {
2987        dmsg(2,("LSCPServer: AddSendEffectChain(%d)\n", iAudioOutputDevice));
2988        LSCPResultSet result;
2989        try {
2990            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2991            if (!devices.count(iAudioOutputDevice))
2992                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2993            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2994            EffectChain* pEffectChain = pDevice->AddSendEffectChain();
2995            result = pEffectChain->ID();
2996            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_count, iAudioOutputDevice, pDevice->SendEffectChainCount()));
2997        } catch (Exception e) {
2998            result.Error(e);
2999        }
3000        return result.Produce();
3001    }
3002    
3003    String LSCPServer::RemoveSendEffectChain(int iAudioOutputDevice, int iSendEffectChain) {
3004        dmsg(2,("LSCPServer: RemoveSendEffectChain(%d,%d)\n", iAudioOutputDevice, iSendEffectChain));
3005        LSCPResultSet result;
3006        try {
3007            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
3008            if (!devices.count(iAudioOutputDevice))
3009                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
3010    
3011            std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
3012            std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();
3013            std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
3014            for (; itEngineChannel != itEnd; ++itEngineChannel) {
3015                AudioOutputDevice* pDev = (*itEngineChannel)->GetAudioOutputDevice();
3016                if (pDev != NULL && pDev->deviceId() == iAudioOutputDevice) {
3017                    for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
3018                        FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
3019                        if(fxs != NULL && fxs->DestinationEffectChain() == iSendEffectChain) {
3020                            throw Exception("The effect chain is still in use by channel " + ToString((*itEngineChannel)->GetSamplerChannel()->Index()));
3021                        }
3022                    }
3023                }
3024            }
3025    
3026            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
3027            for (int i = 0; i < pDevice->SendEffectChainCount(); i++) {
3028                EffectChain* pEffectChain = pDevice->SendEffectChain(i);
3029                if (pEffectChain->ID() == iSendEffectChain) {
3030                    pDevice->RemoveSendEffectChain(i);
3031                    LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_count, iAudioOutputDevice, pDevice->SendEffectChainCount()));
3032                    return result.Produce();
3033                }
3034            }
3035            throw Exception(
3036                "There is no send effect chain with ID " +
3037                ToString(iSendEffectChain) + " for audio output device " +
3038                ToString(iAudioOutputDevice) + "."
3039            );
3040        } catch (Exception e) {
3041            result.Error(e);
3042        }
3043        return result.Produce();
3044    }
3045    
3046    static EffectChain* _getSendEffectChain(Sampler* pSampler, int iAudioOutputDevice, int iSendEffectChain) throw (Exception) {
3047        std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
3048        if (!devices.count(iAudioOutputDevice))
3049            throw Exception(
3050                "There is no audio output device with index " +
3051                ToString(iAudioOutputDevice) + "."
3052            );
3053        AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
3054        EffectChain* pEffectChain = pDevice->SendEffectChainByID(iSendEffectChain);
3055        if(pEffectChain != NULL) return pEffectChain;
3056        throw Exception(
3057            "There is no send effect chain with ID " +
3058            ToString(iSendEffectChain) + " for audio output device " +
3059            ToString(iAudioOutputDevice) + "."
3060        );
3061    }
3062    
3063    String LSCPServer::GetSendEffectChainInfo(int iAudioOutputDevice, int iSendEffectChain) {
3064        dmsg(2,("LSCPServer: GetSendEffectChainInfo(%d,%d)\n", iAudioOutputDevice, iSendEffectChain));
3065        LSCPResultSet result;
3066        try {
3067            EffectChain* pEffectChain =
3068                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
3069            String sEffectSequence;
3070            for (int i = 0; i < pEffectChain->EffectCount(); i++) {
3071                if (i) sEffectSequence += ",";
3072                sEffectSequence += ToString(pEffectChain->GetEffect(i)->ID());
3073            }
3074            result.Add("EFFECT_COUNT", pEffectChain->EffectCount());
3075            result.Add("EFFECT_SEQUENCE", sEffectSequence);
3076        } catch (Exception e) {
3077            result.Error(e);
3078        }
3079        return result.Produce();
3080    }
3081    
3082    String LSCPServer::AppendSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectInstance) {
3083        dmsg(2,("LSCPServer: AppendSendEffectChainEffect(%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectInstance));
3084        LSCPResultSet result;
3085        try {
3086            EffectChain* pEffectChain =
3087                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
3088            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
3089            if (!pEffect)
3090                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
3091            pEffectChain->AppendEffect(pEffect);
3092            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_info, iAudioOutputDevice, iSendEffectChain, pEffectChain->EffectCount()));
3093        } catch (Exception e) {
3094            result.Error(e);
3095        }
3096        return result.Produce();
3097    }
3098    
3099    String LSCPServer::InsertSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectChainPosition, int iEffectInstance) {
3100        dmsg(2,("LSCPServer: InsertSendEffectChainEffect(%d,%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectChainPosition, iEffectInstance));
3101        LSCPResultSet result;
3102        try {
3103            EffectChain* pEffectChain =
3104                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
3105            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
3106            if (!pEffect)
3107                throw Exception("There is no effect instance with index " + ToString(iEffectInstance));
3108            pEffectChain->InsertEffect(pEffect, iEffectChainPosition);
3109            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_info, iAudioOutputDevice, iSendEffectChain, pEffectChain->EffectCount()));
3110        } catch (Exception e) {
3111            result.Error(e);
3112        }
3113        return result.Produce();
3114    }
3115    
3116    String LSCPServer::RemoveSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectChainPosition) {
3117        dmsg(2,("LSCPServer: RemoveSendEffectChainEffect(%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectChainPosition));
3118        LSCPResultSet result;
3119        try {
3120            EffectChain* pEffectChain =
3121                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
3122    
3123            std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
3124            std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();
3125            std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
3126            for (; itEngineChannel != itEnd; ++itEngineChannel) {
3127                AudioOutputDevice* pDev = (*itEngineChannel)->GetAudioOutputDevice();
3128                if (pDev != NULL && pDev->deviceId() == iAudioOutputDevice) {
3129                    for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
3130                        FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
3131                        if(fxs != NULL && fxs->DestinationEffectChain() == iSendEffectChain && fxs->DestinationEffectChainPosition() == iEffectChainPosition) {
3132                            throw Exception("The effect instance is still in use by channel " + ToString((*itEngineChannel)->GetSamplerChannel()->Index()));
3133                        }
3134                    }
3135                }
3136            }
3137    
3138            pEffectChain->RemoveEffect(iEffectChainPosition);
3139            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_info, iAudioOutputDevice, iSendEffectChain, pEffectChain->EffectCount()));
3140        } catch (Exception e) {
3141            result.Error(e);
3142        }
3143        return result.Produce();
3144    }
3145    
3146  String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {  String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
3147      dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
3148      LSCPResultSet result;      LSCPResultSet result;
# Line 2422  String LSCPServer::EditSamplerChannelIns Line 3155  String LSCPServer::EditSamplerChannelIns
3155          InstrumentManager::instrument_id_t instrumentID;          InstrumentManager::instrument_id_t instrumentID;
3156          instrumentID.FileName = pEngineChannel->InstrumentFileName();          instrumentID.FileName = pEngineChannel->InstrumentFileName();
3157          instrumentID.Index    = pEngineChannel->InstrumentIndex();          instrumentID.Index    = pEngineChannel->InstrumentIndex();
3158          pInstrumentManager->LaunchInstrumentEditor(instrumentID);          pInstrumentManager->LaunchInstrumentEditor(pEngineChannel, instrumentID);
3159      } catch (Exception e) {      } catch (Exception e) {
3160          result.Error(e);          result.Error(e);
3161      }      }
# Line 2458  String LSCPServer::SendChannelMidiData(S Line 3191  String LSCPServer::SendChannelMidiData(S
3191              pMidiDevice->SendNoteOffToDevice(Arg1, Arg2);              pMidiDevice->SendNoteOffToDevice(Arg1, Arg2);
3192              bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2);              bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2);
3193              if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));              if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
3194            } else if (MidiMsg == "CC") {
3195                pMidiDevice->SendCCToDevice(Arg1, Arg2);
3196                bool b = pMidiDevice->SendCCToSampler(Arg1, Arg2);
3197                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
3198          } else {          } else {
3199              throw Exception("Unknown MIDI message type: " + MidiMsg);              throw Exception("Unknown MIDI message type: " + MidiMsg);
3200          }          }
# Line 2540  String LSCPServer::GetTotalVoiceCount() Line 3277  String LSCPServer::GetTotalVoiceCount()
3277  String LSCPServer::GetTotalVoiceCountMax() {  String LSCPServer::GetTotalVoiceCountMax() {
3278      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));
3279      LSCPResultSet result;      LSCPResultSet result;
3280      result.Add(EngineFactory::EngineInstances().size() * CONFIG_MAX_VOICES);      result.Add(int(EngineFactory::EngineInstances().size() * pSampler->GetGlobalMaxVoices()));
3281        return result.Produce();
3282    }
3283    
3284    /**
3285     * Will be called by the parser to return the sampler global maximum
3286     * allowed number of voices.
3287     */
3288    String LSCPServer::GetGlobalMaxVoices() {
3289        dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n"));
3290        LSCPResultSet result;
3291        result.Add(pSampler->GetGlobalMaxVoices());
3292        return result.Produce();
3293    }
3294    
3295    /**
3296     * Will be called by the parser to set the sampler global maximum number of
3297     * voices.
3298     */
3299    String LSCPServer::SetGlobalMaxVoices(int iVoices) {
3300        dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices));
3301        LSCPResultSet result;
3302        try {
3303            pSampler->SetGlobalMaxVoices(iVoices);
3304            LSCPServer::SendLSCPNotify(
3305                LSCPEvent(LSCPEvent::event_global_info, "VOICES", pSampler->GetGlobalMaxVoices())
3306            );
3307        } catch (Exception e) {
3308            result.Error(e);
3309        }
3310        return result.Produce();
3311    }
3312    
3313    /**
3314     * Will be called by the parser to return the sampler global maximum
3315     * allowed number of disk streams.
3316     */
3317    String LSCPServer::GetGlobalMaxStreams() {
3318        dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n"));
3319        LSCPResultSet result;
3320        result.Add(pSampler->GetGlobalMaxStreams());
3321        return result.Produce();
3322    }
3323    
3324    /**
3325     * Will be called by the parser to set the sampler global maximum number of
3326     * disk streams.
3327     */
3328    String LSCPServer::SetGlobalMaxStreams(int iStreams) {
3329        dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams));
3330        LSCPResultSet result;
3331        try {
3332            pSampler->SetGlobalMaxStreams(iStreams);
3333            LSCPServer::SendLSCPNotify(
3334                LSCPEvent(LSCPEvent::event_global_info, "STREAMS", pSampler->GetGlobalMaxStreams())
3335            );
3336        } catch (Exception e) {
3337            result.Error(e);
3338        }
3339      return result.Produce();      return result.Produce();
3340  }  }
3341    
# Line 2584  String LSCPServer::GetFileInstruments(St Line 3379  String LSCPServer::GetFileInstruments(St
3379                  std::vector<InstrumentManager::instrument_id_t> IDs =                  std::vector<InstrumentManager::instrument_id_t> IDs =
3380                      pManager->GetInstrumentFileContent(Filename);                      pManager->GetInstrumentFileContent(Filename);
3381                  // return the amount of instruments in the file                  // return the amount of instruments in the file
3382                  result.Add(IDs.size());                  result.Add((int)IDs.size());
3383                  // no more need to ask other engine types                  // no more need to ask other engine types
3384                  bFound = true;                  bFound = true;
3385              } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));              } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
# Line 2728  void LSCPServer::VerifyFile(String Filen Line 3523  void LSCPServer::VerifyFile(String Filen
3523          throw Exception("Directory is specified");          throw Exception("Directory is specified");
3524      }      }
3525      #else      #else
3526      struct stat statBuf;      File f(Filename);
3527      int res = stat(Filename.c_str(), &statBuf);      if(!f.Exist()) throw Exception(f.GetErrorMsg());
3528      if (res) {      if (f.IsDirectory()) throw Exception("Directory is specified");
         std::stringstream ss;  
         ss << "Fail to stat `" << Filename << "`: " << strerror(errno);  
         throw Exception(ss.str());  
     }  
   
     if (S_ISDIR(statBuf.st_mode)) {  
         throw Exception("Directory is specified");  
     }  
3529      #endif      #endif
3530  }  }
3531    
# Line 2749  void LSCPServer::VerifyFile(String Filen Line 3536  void LSCPServer::VerifyFile(String Filen
3536  String LSCPServer::SubscribeNotification(LSCPEvent::event_t type) {  String LSCPServer::SubscribeNotification(LSCPEvent::event_t type) {
3537      dmsg(2,("LSCPServer: SubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));      dmsg(2,("LSCPServer: SubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
3538      LSCPResultSet result;      LSCPResultSet result;
3539      SubscriptionMutex.Lock();      {
3540      eventSubscriptions[type].push_back(currentSocket);          LockGuard lock(SubscriptionMutex);
3541      SubscriptionMutex.Unlock();          eventSubscriptions[type].push_back(currentSocket);
3542        }
3543      return result.Produce();      return result.Produce();
3544  }  }
3545    
# Line 2762  String LSCPServer::SubscribeNotification Line 3550  String LSCPServer::SubscribeNotification
3550  String LSCPServer::UnsubscribeNotification(LSCPEvent::event_t type) {  String LSCPServer::UnsubscribeNotification(LSCPEvent::event_t type) {
3551      dmsg(2,("LSCPServer: UnsubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));      dmsg(2,("LSCPServer: UnsubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
3552      LSCPResultSet result;      LSCPResultSet result;
3553      SubscriptionMutex.Lock();      {
3554      eventSubscriptions[type].remove(currentSocket);          LockGuard lock(SubscriptionMutex);
3555      SubscriptionMutex.Unlock();          eventSubscriptions[type].remove(currentSocket);
3556        }
3557      return result.Produce();      return result.Produce();
3558  }  }
3559    
# Line 3289  String LSCPServer::SetEcho(yyparse_param Line 4078  String LSCPServer::SetEcho(yyparse_param
4078      }      }
4079      return result.Produce();      return result.Produce();
4080  }  }
4081    
4082    String LSCPServer::SetShellInteract(yyparse_param_t* pSession, double boolean_value) {
4083        dmsg(2,("LSCPServer: SetShellInteract(val=%f)\n", boolean_value));
4084        LSCPResultSet result;
4085        try {
4086            if      (boolean_value == 0) pSession->bShellInteract = false;
4087            else if (boolean_value == 1) pSession->bShellInteract = true;
4088            else throw Exception("Not a boolean value, must either be 0 or 1");
4089        } catch (Exception e) {
4090            result.Error(e);
4091        }
4092        return result.Produce();
4093    }
4094    
4095    String LSCPServer::SetShellAutoCorrect(yyparse_param_t* pSession, double boolean_value) {
4096        dmsg(2,("LSCPServer: SetShellAutoCorrect(val=%f)\n", boolean_value));
4097        LSCPResultSet result;
4098        try {
4099            if      (boolean_value == 0) pSession->bShellAutoCorrect = false;
4100            else if (boolean_value == 1) pSession->bShellAutoCorrect = true;
4101            else throw Exception("Not a boolean value, must either be 0 or 1");
4102        } catch (Exception e) {
4103            result.Error(e);
4104        }
4105        return result.Produce();
4106    }
4107    
4108    String LSCPServer::SetShellDoc(yyparse_param_t* pSession, double boolean_value) {
4109        dmsg(2,("LSCPServer: SetShellDoc(val=%f)\n", boolean_value));
4110        LSCPResultSet result;
4111        try {
4112            if      (boolean_value == 0) pSession->bShellSendLSCPDoc = false;
4113            else if (boolean_value == 1) pSession->bShellSendLSCPDoc = true;
4114            else throw Exception("Not a boolean value, must either be 0 or 1");
4115        } catch (Exception e) {
4116            result.Error(e);
4117        }
4118        return result.Produce();
4119    }
4120    
4121  }  }

Legend:
Removed from v.1781  
changed lines
  Added in v.3055

  ViewVC Help
Powered by ViewVC