/[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 2198 by iliev, Sun Jul 3 18:06:51 2011 UTC revision 2531 by schoenebeck, Wed Mar 5 00:02:21 2014 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 - 2010 Christian Schoenebeck                       *   *   Copyright (C) 2005 - 2014 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 47  Line 47 
47    
48  namespace LinuxSampler {  namespace LinuxSampler {
49    
50    String lscpParserProcessShellInteraction(String& line, yyparse_param_t* param, bool possibilities);
51    
52  /**  /**
53   * Returns a copy of the given string where all special characters are   * Returns a copy of the given string where all special characters are
54   * replaced by LSCP escape sequences ("\xHH"). This function shall be used   * replaced by LSCP escape sequences ("\xHH"). This function shall be used
# Line 97  static String _escapeLscpResponse(String Line 99  static String _escapeLscpResponse(String
99   */   */
100  fd_set LSCPServer::fdSet;  fd_set LSCPServer::fdSet;
101  int LSCPServer::currentSocket = -1;  int LSCPServer::currentSocket = -1;
102  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();  std::vector<yyparse_param_t> LSCPServer::Sessions;
103  std::vector<yyparse_param_t>::iterator itCurrentSession = std::vector<yyparse_param_t>::iterator();  std::vector<yyparse_param_t>::iterator itCurrentSession;
104  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedNotifies;
105  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedCommands;
106  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;
107  Mutex LSCPServer::NotifyMutex = Mutex();  Mutex LSCPServer::NotifyMutex;
108  Mutex LSCPServer::NotifyBufferMutex = Mutex();  Mutex LSCPServer::NotifyBufferMutex;
109  Mutex LSCPServer::SubscriptionMutex = Mutex();  Mutex LSCPServer::SubscriptionMutex;
110  Mutex LSCPServer::RTNotifyMutex = Mutex();  Mutex LSCPServer::RTNotifyMutex;
111    
112  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) {
113      SocketAddress.sin_family      = AF_INET;      SocketAddress.sin_family      = AF_INET;
# Line 447  int LSCPServer::Main() { Line 449  int LSCPServer::Main() {
449          #endif          #endif
450          // 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
451          {          {
452                LockGuard lock(EngineChannelFactory::EngineChannelsMutex);
453              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
454              std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();              std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();
455              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
# Line 515  int LSCPServer::Main() { Line 518  int LSCPServer::Main() {
518              }              }
519          }          }
520    
521          //Now let's deliver late notifies (if any)          //Now let's deliver late notifies (if any)
522          NotifyBufferMutex.Lock();          {
523          for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {              LockGuard lock(NotifyBufferMutex);
524                for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {
525  #ifdef MSG_NOSIGNAL  #ifdef MSG_NOSIGNAL
526                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), MSG_NOSIGNAL);                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), MSG_NOSIGNAL);
527  #else  #else
528                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0);                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0);
529  #endif  #endif
530          }              }
531          bufferedNotifies.clear();              bufferedNotifies.clear();
532          NotifyBufferMutex.Unlock();          }
533    
534          fd_set selectSet = fdSet;          fd_set selectSet = fdSet;
535          timeout.tv_sec  = 0;          timeout.tv_sec  = 0;
# Line 590  int LSCPServer::Main() { Line 594  int LSCPServer::Main() {
594          //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.
595          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++) {
596                  if (FD_ISSET((*iter).hSession, &selectSet)) {   //Was it this socket?                  if (FD_ISSET((*iter).hSession, &selectSet)) {   //Was it this socket?
597                            currentSocket = (*iter).hSession;  //a hack
598                          if (GetLSCPCommand(iter)) {     //Have we read the entire command?                          if (GetLSCPCommand(iter)) {     //Have we read the entire command?
599                                  dmsg(3,("LSCPServer: Got command on socket %d, calling parser.\n", currentSocket));                                  dmsg(3,("LSCPServer: Got command on socket %d, calling parser.\n", currentSocket));
600                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
601                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
                                 currentSocket = (*iter).hSession;  //a hack  
602                                  itCurrentSession = iter; // another hack                                  itCurrentSession = iter; // another hack
603                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
604                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
# Line 608  int LSCPServer::Main() { Line 612  int LSCPServer::Main() {
612                                          CloseConnection(iter);                                          CloseConnection(iter);
613                                  }                                  }
614                          }                          }
615                            currentSocket = -1;     //continuation of a hack
616                          //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.
617                          //we'll be back if there is data.                          //we'll be back if there is data.
618                          break;                          break;
# Line 622  void LSCPServer::CloseConnection( std::v Line 627  void LSCPServer::CloseConnection( std::v
627          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection terminated on socket", socket));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection terminated on socket", socket));
628          Sessions.erase(iter);          Sessions.erase(iter);
629          FD_CLR(socket,  &fdSet);          FD_CLR(socket,  &fdSet);
630          SubscriptionMutex.Lock(); //Must unsubscribe this socket from all events (if any)          {
631          for (std::map< LSCPEvent::event_t, std::list<int> >::iterator iter = eventSubscriptions.begin(); iter != eventSubscriptions.end(); iter++) {              LockGuard lock(SubscriptionMutex);
632                  iter->second.remove(socket);              // 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++) {
634          SubscriptionMutex.Unlock();                  iter->second.remove(socket);
635          NotifyMutex.Lock();              }
636            }
637            LockGuard lock(NotifyMutex);
638          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
639          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
640          #if defined(WIN32)          #if defined(WIN32)
# Line 635  void LSCPServer::CloseConnection( std::v Line 642  void LSCPServer::CloseConnection( std::v
642          #else          #else
643          close(socket);          close(socket);
644          #endif          #endif
         NotifyMutex.Unlock();  
645  }  }
646    
647  void LSCPServer::CloseAllConnections() {  void LSCPServer::CloseAllConnections() {
# Line 646  void LSCPServer::CloseAllConnections() { Line 652  void LSCPServer::CloseAllConnections() {
652      }      }
653  }  }
654    
 void LSCPServer::LockRTNotify() {  
     RTNotifyMutex.Lock();  
 }  
   
 void LSCPServer::UnlockRTNotify() {  
     RTNotifyMutex.Unlock();  
 }  
   
655  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
656          int subs = 0;          int subs = 0;
657          SubscriptionMutex.Lock();          LockGuard lock(SubscriptionMutex);
658          for( std::list<LSCPEvent::event_t>::iterator iter = events.begin();          for( std::list<LSCPEvent::event_t>::iterator iter = events.begin();
659                          iter != events.end(); iter++)                          iter != events.end(); iter++)
660          {          {
661                  subs += eventSubscriptions.count(*iter);                  subs += eventSubscriptions.count(*iter);
662          }          }
         SubscriptionMutex.Unlock();  
663          return subs;          return subs;
664  }  }
665    
666  void LSCPServer::SendLSCPNotify( LSCPEvent event ) {  void LSCPServer::SendLSCPNotify( LSCPEvent event ) {
667          SubscriptionMutex.Lock();          LockGuard lock(SubscriptionMutex);
668          if (eventSubscriptions.count(event.GetType()) == 0) {          if (eventSubscriptions.count(event.GetType()) == 0) {
669                  SubscriptionMutex.Unlock();     //Nobody is subscribed to this event                  // Nobody is subscribed to this event
670                  return;                  return;
671          }          }
672          std::list<int>::iterator iter = eventSubscriptions[event.GetType()].begin();          std::list<int>::iterator iter = eventSubscriptions[event.GetType()].begin();
# Line 695  void LSCPServer::SendLSCPNotify( LSCPEve Line 692  void LSCPServer::SendLSCPNotify( LSCPEve
692                          }                          }
693                  }                  }
694          }          }
         SubscriptionMutex.Unlock();  
695  }  }
696    
697  extern int GetLSCPCommand( void *buf, int max_size ) {  extern int GetLSCPCommand( void *buf, int max_size ) {
# Line 726  extern yyparse_param_t* GetCurrentYaccSe Line 722  extern yyparse_param_t* GetCurrentYaccSe
722   */   */
723  bool LSCPServer::GetLSCPCommand( std::vector<yyparse_param_t>::iterator iter ) {  bool LSCPServer::GetLSCPCommand( std::vector<yyparse_param_t>::iterator iter ) {
724          int socket = (*iter).hSession;          int socket = (*iter).hSession;
725            int result;
726          char c;          char c;
727          int i = 0;          std::vector<char> input;
728    
729            // first get as many character as possible and add it to the 'input' buffer
730          while (true) {          while (true) {
731                  #if defined(WIN32)                  #if defined(WIN32)
732                  int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now                  result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
733                  #else                  #else
734                  int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now                  result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now
735                  #endif                  #endif
736                  if (result == 0) { //socket was selected, so 0 here means client has closed the connection                  if (result == 1) input.push_back(c);
737                          CloseConnection(iter);                  else break; // end of input or some error
738                          break;                  if (c == '\n') break; // process line by line
739                  }          }
740                  if (result == 1) {  
741                          if (c == '\r')          // process input buffer
742                                  continue; //Ignore CR          for (int i = 0; i < input.size(); ++i) {
743                          if (c == '\n') {                  c = input[i];
744                                  LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Received \'" + bufferedCommands[socket] + "\' on socket", socket));                  if (c == '\r') continue; //Ignore CR
745                                  bufferedCommands[socket] += "\r\n";                  if (c == '\n') {
746                                  return true; //Complete command was read                          // only if the other side is the LSCP shell application:
747                            // check the current (incomplete) command line for syntax errors,
748                            // possible completions and report everything back to the shell
749                            if ((*iter).bShellInteract || (*iter).bShellAutoCorrect) {
750                                    String s = lscpParserProcessShellInteraction(bufferedCommands[socket], &(*iter), false);
751                                    if (!s.empty() && (*iter).bShellInteract) AnswerClient(s + "\n");
752                            }
753    
754                            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Received \'" + bufferedCommands[socket] + "\' on socket", socket));
755                            bufferedCommands[socket] += "\r\n";
756                            return true; //Complete command was read
757                    } else if (c == 2) { // custom ASCII code usage for moving cursor left (LSCP shell)
758                            if (iter->iCursorOffset + bufferedCommands[socket].size() > 0)
759                                    iter->iCursorOffset--;
760                    } else if (c == 3) { // custom ASCII code usage for moving cursor right (LSCP shell)
761                            if (iter->iCursorOffset < 0) iter->iCursorOffset++;
762                    } else {
763                            size_t cursorPos = bufferedCommands[socket].size() + iter->iCursorOffset;
764                            // backspace character - should only happen with shell
765                            if (c == '\b') {
766                                    if (!bufferedCommands[socket].empty() && cursorPos > 0)
767                                            bufferedCommands[socket].erase(cursorPos - 1, 1);
768                            } else { // append (or insert) new character (at current cursor position) ...
769                                    if (cursorPos >= 0)
770                                            bufferedCommands[socket].insert(cursorPos, String(1,c)); // insert
771                                    else
772                                            bufferedCommands[socket] += c; // append
773                          }                          }
                         bufferedCommands[socket] += c;  
774                  }                  }
775                  #if defined(WIN32)                  // only if the other side is the LSCP shell application:
776                  if (result == SOCKET_ERROR) {                  // check the current (incomplete) command line for syntax errors,
777                      int wsa_lasterror = WSAGetLastError();                  // possible completions and report everything back to the shell
778                          if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.                  if ((*iter).bShellInteract || (*iter).bShellAutoCorrect) {
779                                  return false;                          String s = lscpParserProcessShellInteraction(bufferedCommands[socket], &(*iter), true);
780                          dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));                          if (!s.empty() && (*iter).bShellInteract && i == input.size() - 1)
781                          CloseConnection(iter);                                  AnswerClient(s + "\n");
                         break;  
782                  }                  }
783                  #else          }
784                  if (result == -1) {  
785                          if (errno == EAGAIN) //Would block, try again later.          // handle network errors ...
786            if (result == 0) { //socket was selected, so 0 here means client has closed the connection
787                    CloseConnection(iter);
788                    return false;
789            }
790            #if defined(WIN32)
791            if (result == SOCKET_ERROR) {
792                    int wsa_lasterror = WSAGetLastError();
793                    if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
794                            return false;
795                    dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
796                    CloseConnection(iter);
797                    return false;
798            }
799            #else
800            if (result == -1) {
801                    if (errno == EAGAIN) //Would block, try again later.
802                            return false;
803                    switch(errno) {
804                            case EBADF:
805                                    dmsg(2,("LSCPScanner: The argument s is an invalid descriptor.\n"));
806                                    return false;
807                            case ECONNREFUSED:
808                                    dmsg(2,("LSCPScanner: A remote host refused to allow the network connection (typically because it is not running the requested service).\n"));
809                                    return false;
810                            case ENOTCONN:
811                                    dmsg(2,("LSCPScanner: The socket is associated with a connection-oriented protocol and has not been connected (see connect(2) and accept(2)).\n"));
812                                    return false;
813                            case ENOTSOCK:
814                                    dmsg(2,("LSCPScanner: The argument s does not refer to a socket.\n"));
815                                    return false;
816                            case EAGAIN:
817                                    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"));
818                                    return false;
819                            case EINTR:
820                                    dmsg(2,("LSCPScanner: The receive was interrupted by delivery of a signal before any data were available.\n"));
821                                    return false;
822                            case EFAULT:
823                                    dmsg(2,("LSCPScanner: The receive buffer pointer(s) point outside the process's address space.\n"));
824                                    return false;
825                            case EINVAL:
826                                    dmsg(2,("LSCPScanner: Invalid argument passed.\n"));
827                                    return false;
828                            case ENOMEM:
829                                    dmsg(2,("LSCPScanner: Could not allocate memory for recvmsg.\n"));
830                                    return false;
831                            default:
832                                    dmsg(2,("LSCPScanner: Unknown recv() error.\n"));
833                                  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;  
834                  }                  }
835                  #endif                  CloseConnection(iter);
836                    return false;
837          }          }
838            #endif
839    
840          return false;          return false;
841  }  }
842    
# Line 808  bool LSCPServer::GetLSCPCommand( std::ve Line 847  bool LSCPServer::GetLSCPCommand( std::ve
847   * @param ReturnMessage - message that will be send to the client   * @param ReturnMessage - message that will be send to the client
848   */   */
849  void LSCPServer::AnswerClient(String ReturnMessage) {  void LSCPServer::AnswerClient(String ReturnMessage) {
850      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str()));      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage='%s')", ReturnMessage.c_str()));
851      if (currentSocket != -1) {      if (currentSocket != -1) {
852              NotifyMutex.Lock();              LockGuard lock(NotifyMutex);
853    
854            // just if other side is LSCP shell: in case respose is a multi-line
855            // one, then inform client about it before sending the actual mult-line
856            // response
857            if (GetCurrentYaccSession()->bShellInteract) {
858                // check if this is a multi-line response
859                int n = 0;
860                for (int i = 0; i < ReturnMessage.size(); ++i)
861                    if (ReturnMessage[i] == '\n') ++n;
862                if (n >= 2) {
863                    dmsg(2,("LSCP Shell <- expect mult-line response\n"));
864                    String s = LSCP_SHK_EXPECT_MULTI_LINE "\r\n";
865    #ifdef MSG_NOSIGNAL
866                    send(currentSocket, s.c_str(), s.size(), MSG_NOSIGNAL);
867    #else
868                    send(currentSocket, s.c_str(), s.size(), 0);
869    #endif                
870                }
871            }
872    
873  #ifdef MSG_NOSIGNAL  #ifdef MSG_NOSIGNAL
874              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), MSG_NOSIGNAL);              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), MSG_NOSIGNAL);
875  #else  #else
876              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);
877  #endif  #endif
             NotifyMutex.Unlock();  
878      }      }
879  }  }
880    
# Line 966  String LSCPServer::SetEngineType(String Line 1024  String LSCPServer::SetEngineType(String
1024      try {      try {
1025          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1026          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1027          LockRTNotify();          LockGuard lock(RTNotifyMutex);
1028          pSamplerChannel->SetEngineType(EngineName);          pSamplerChannel->SetEngineType(EngineName);
1029          if(HasSoloChannel()) pSamplerChannel->GetEngineChannel()->SetMute(-1);          if(HasSoloChannel()) pSamplerChannel->GetEngineChannel()->SetMute(-1);
         UnlockRTNotify();  
1030      }      }
1031      catch (Exception e) {      catch (Exception e) {
1032           result.Error(e);           result.Error(e);
# Line 1009  String LSCPServer::ListChannels() { Line 1066  String LSCPServer::ListChannels() {
1066   */   */
1067  String LSCPServer::AddChannel() {  String LSCPServer::AddChannel() {
1068      dmsg(2,("LSCPServer: AddChannel()\n"));      dmsg(2,("LSCPServer: AddChannel()\n"));
1069      LockRTNotify();      SamplerChannel* pSamplerChannel;
1070      SamplerChannel* pSamplerChannel = pSampler->AddSamplerChannel();      {
1071      UnlockRTNotify();          LockGuard lock(RTNotifyMutex);
1072            pSamplerChannel = pSampler->AddSamplerChannel();
1073        }
1074      LSCPResultSet result(pSamplerChannel->Index());      LSCPResultSet result(pSamplerChannel->Index());
1075      return result.Produce();      return result.Produce();
1076  }  }
# Line 1022  String LSCPServer::AddChannel() { Line 1081  String LSCPServer::AddChannel() {
1081  String LSCPServer::RemoveChannel(uint uiSamplerChannel) {  String LSCPServer::RemoveChannel(uint uiSamplerChannel) {
1082      dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel));
1083      LSCPResultSet result;      LSCPResultSet result;
1084      LockRTNotify();      {
1085      pSampler->RemoveSamplerChannel(uiSamplerChannel);          LockGuard lock(RTNotifyMutex);
1086      UnlockRTNotify();          pSampler->RemoveSamplerChannel(uiSamplerChannel);
1087        }
1088      return result.Produce();      return result.Produce();
1089  }  }
1090    
# Line 1067  String LSCPServer::ListAvailableEngines( Line 1127  String LSCPServer::ListAvailableEngines(
1127  String LSCPServer::GetEngineInfo(String EngineName) {  String LSCPServer::GetEngineInfo(String EngineName) {
1128      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));
1129      LSCPResultSet result;      LSCPResultSet result;
1130      LockRTNotify();      {
1131      try {          LockGuard lock(RTNotifyMutex);
1132          Engine* pEngine = EngineFactory::Create(EngineName);          try {
1133          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));              Engine* pEngine = EngineFactory::Create(EngineName);
1134          result.Add("VERSION",     pEngine->Version());              result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
1135          EngineFactory::Destroy(pEngine);              result.Add("VERSION",     pEngine->Version());
1136      }              EngineFactory::Destroy(pEngine);
1137      catch (Exception e) {          }
1138           result.Error(e);          catch (Exception e) {
1139                result.Error(e);
1140            }
1141      }      }
     UnlockRTNotify();  
1142      return result.Produce();      return result.Produce();
1143  }  }
1144    
# Line 1726  String LSCPServer::SetAudioOutputChannel Line 1787  String LSCPServer::SetAudioOutputChannel
1787  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {
1788      dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));      dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));
1789      LSCPResultSet result;      LSCPResultSet result;
1790      LockRTNotify();      {
1791            LockGuard lock(RTNotifyMutex);
1792            try {
1793                SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1794                if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1795                std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1796                if (!devices.count(AudioDeviceId)) throw Exception("There is no audio output device with index " + ToString(AudioDeviceId));
1797                AudioOutputDevice* pDevice = devices[AudioDeviceId];
1798                pSamplerChannel->SetAudioOutputDevice(pDevice);
1799            }
1800            catch (Exception e) {
1801                result.Error(e);
1802            }
1803        }
1804        return result.Produce();
1805    }
1806    
1807    String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {
1808        dmsg(2,("LSCPServer: SetAudioOutputType(String AudioOutputDriver=%s, SamplerChannel=%d)\n",AudioOutputDriver.c_str(),uiSamplerChannel));
1809        LSCPResultSet result;
1810        {
1811            LockGuard lock(RTNotifyMutex);
1812            try {
1813                SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1814                if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1815                // Driver type name aliasing...
1816                if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA";
1817                if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK";
1818                // Check if there's one audio output device already created
1819                // for the intended audio driver type (AudioOutputDriver)...
1820                AudioOutputDevice *pDevice = NULL;
1821                std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1822                std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();
1823                for (; iter != devices.end(); iter++) {
1824                    if ((iter->second)->Driver() == AudioOutputDriver) {
1825                        pDevice = iter->second;
1826                        break;
1827                    }
1828                }
1829                // If it doesn't exist, create a new one with default parameters...
1830                if (pDevice == NULL) {
1831                    std::map<String,String> params;
1832                    pDevice = pSampler->CreateAudioOutputDevice(AudioOutputDriver, params);
1833                }
1834                // Must have a device...
1835                if (pDevice == NULL)
1836                    throw Exception("Internal error: could not create audio output device.");
1837                // Set it as the current channel device...
1838                pSamplerChannel->SetAudioOutputDevice(pDevice);
1839            }
1840            catch (Exception e) {
1841                result.Error(e);
1842            }
1843        }
1844        return result.Produce();
1845    }
1846    
1847    String LSCPServer::AddChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId, uint MIDIPort) {
1848        dmsg(2,("LSCPServer: AddChannelMidiInput(uiSamplerChannel=%d, MIDIDeviceId=%d, MIDIPort=%d)\n",uiSamplerChannel,MIDIDeviceId,MIDIPort));
1849        LSCPResultSet result;
1850      try {      try {
1851          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1852          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1853          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();  
1854          if (!devices.count(AudioDeviceId)) throw Exception("There is no audio output device with index " + ToString(AudioDeviceId));          std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1855          AudioOutputDevice* pDevice = devices[AudioDeviceId];          if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1856          pSamplerChannel->SetAudioOutputDevice(pDevice);          MidiInputDevice* pDevice = devices[MIDIDeviceId];
1857    
1858            MidiInputPort* pPort = pDevice->GetPort(MIDIPort);
1859            if (!pPort) throw Exception("There is no MIDI input port with index " + ToString(MIDIPort) + " on MIDI input device with index " + ToString(MIDIDeviceId));
1860    
1861            pSamplerChannel->Connect(pPort);
1862        } catch (Exception e) {
1863            result.Error(e);
1864      }      }
1865      catch (Exception e) {      return result.Produce();
1866           result.Error(e);  }
1867    
1868    String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel) {
1869        dmsg(2,("LSCPServer: RemoveChannelMidiInput(uiSamplerChannel=%d)\n",uiSamplerChannel));
1870        LSCPResultSet result;
1871        try {
1872            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1873            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1874            pSamplerChannel->DisconnectAllMidiInputPorts();
1875        } catch (Exception e) {
1876            result.Error(e);
1877      }      }
     UnlockRTNotify();  
1878      return result.Produce();      return result.Produce();
1879  }  }
1880    
1881  String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {  String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId) {
1882      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));
1883      LSCPResultSet result;      LSCPResultSet result;
     LockRTNotify();  
1884      try {      try {
1885          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1886          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1887          // Driver type name aliasing...  
1888          if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA";          std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1889          if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK";          if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1890          // Check if there's one audio output device already created          MidiInputDevice* pDevice = devices[MIDIDeviceId];
1891          // for the intended audio driver type (AudioOutputDriver)...          
1892          AudioOutputDevice *pDevice = NULL;          std::vector<MidiInputPort*> vPorts = pSamplerChannel->GetMidiInputPorts();
1893          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          for (int i = 0; i < vPorts.size(); ++i)
1894          std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();              if (vPorts[i]->GetDevice() == pDevice)
1895          for (; iter != devices.end(); iter++) {                  pSamplerChannel->Disconnect(vPorts[i]);
1896              if ((iter->second)->Driver() == AudioOutputDriver) {  
1897                  pDevice = iter->second;      } catch (Exception e) {
1898                  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);  
1899      }      }
1900      catch (Exception e) {      return result.Produce();
1901           result.Error(e);  }
1902    
1903    String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId, uint MIDIPort) {
1904        dmsg(2,("LSCPServer: RemoveChannelMidiInput(uiSamplerChannel=%d, MIDIDeviceId=%d, MIDIPort=%d)\n",uiSamplerChannel,MIDIDeviceId,MIDIPort));
1905        LSCPResultSet result;
1906        try {
1907            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1908            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1909    
1910            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1911            if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1912            MidiInputDevice* pDevice = devices[MIDIDeviceId];
1913    
1914            MidiInputPort* pPort = pDevice->GetPort(MIDIPort);
1915            if (!pPort) throw Exception("There is no MIDI input port with index " + ToString(MIDIPort) + " on MIDI input device with index " + ToString(MIDIDeviceId));
1916    
1917            pSamplerChannel->Disconnect(pPort);
1918        } catch (Exception e) {
1919            result.Error(e);
1920        }
1921        return result.Produce();
1922    }
1923    
1924    String LSCPServer::ListChannelMidiInputs(uint uiSamplerChannel) {
1925        dmsg(2,("LSCPServer: ListChannelMidiInputs(uiSamplerChannel=%d)\n",uiSamplerChannel));
1926        LSCPResultSet result;
1927        try {
1928            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1929            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1930            std::vector<MidiInputPort*> vPorts = pSamplerChannel->GetMidiInputPorts();
1931    
1932            String s;
1933            for (int i = 0; i < vPorts.size(); ++i) {
1934                const int iDeviceID = vPorts[i]->GetDevice()->MidiInputDeviceID();
1935                const int iPortNr   = vPorts[i]->GetPortNumber();
1936                if (s.size()) s += ",";
1937                s += "{" + ToString(iDeviceID) + ","
1938                         + ToString(iPortNr) + "}";
1939            }
1940            result.Add(s);
1941        } catch (Exception e) {
1942            result.Error(e);
1943      }      }
     UnlockRTNotify();  
1944      return result.Produce();      return result.Produce();
1945  }  }
1946    
# Line 3061  String LSCPServer::GetTotalVoiceCount() Line 3224  String LSCPServer::GetTotalVoiceCount()
3224  String LSCPServer::GetTotalVoiceCountMax() {  String LSCPServer::GetTotalVoiceCountMax() {
3225      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));
3226      LSCPResultSet result;      LSCPResultSet result;
3227      result.Add(EngineFactory::EngineInstances().size() * GLOBAL_MAX_VOICES);      result.Add(EngineFactory::EngineInstances().size() * pSampler->GetGlobalMaxVoices());
3228      return result.Produce();      return result.Produce();
3229  }  }
3230    
# Line 3072  String LSCPServer::GetTotalVoiceCountMax Line 3235  String LSCPServer::GetTotalVoiceCountMax
3235  String LSCPServer::GetGlobalMaxVoices() {  String LSCPServer::GetGlobalMaxVoices() {
3236      dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n"));      dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n"));
3237      LSCPResultSet result;      LSCPResultSet result;
3238      result.Add(GLOBAL_MAX_VOICES);      result.Add(pSampler->GetGlobalMaxVoices());
3239      return result.Produce();      return result.Produce();
3240  }  }
3241    
# Line 3084  String LSCPServer::SetGlobalMaxVoices(in Line 3247  String LSCPServer::SetGlobalMaxVoices(in
3247      dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices));      dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices));
3248      LSCPResultSet result;      LSCPResultSet result;
3249      try {      try {
3250          if (iVoices < 1) throw Exception("Maximum voices may not be less than 1");          pSampler->SetGlobalMaxVoices(iVoices);
3251          GLOBAL_MAX_VOICES = iVoices; // see common/global_private.cpp          LSCPServer::SendLSCPNotify(
3252          const std::set<Engine*>& engines = EngineFactory::EngineInstances();              LSCPEvent(LSCPEvent::event_global_info, "VOICES", pSampler->GetGlobalMaxVoices())
3253          if (engines.size() > 0) {          );
             std::set<Engine*>::iterator iter = engines.begin();  
             std::set<Engine*>::iterator end  = engines.end();  
             for (; iter != end; ++iter) {  
                 (*iter)->SetMaxVoices(iVoices);  
             }  
         }  
         LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOICES", GLOBAL_MAX_VOICES));  
3254      } catch (Exception e) {      } catch (Exception e) {
3255          result.Error(e);          result.Error(e);
3256      }      }
# Line 3108  String LSCPServer::SetGlobalMaxVoices(in Line 3264  String LSCPServer::SetGlobalMaxVoices(in
3264  String LSCPServer::GetGlobalMaxStreams() {  String LSCPServer::GetGlobalMaxStreams() {
3265      dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n"));      dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n"));
3266      LSCPResultSet result;      LSCPResultSet result;
3267      result.Add(GLOBAL_MAX_STREAMS);      result.Add(pSampler->GetGlobalMaxStreams());
3268      return result.Produce();      return result.Produce();
3269  }  }
3270    
# Line 3120  String LSCPServer::SetGlobalMaxStreams(i Line 3276  String LSCPServer::SetGlobalMaxStreams(i
3276      dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams));      dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams));
3277      LSCPResultSet result;      LSCPResultSet result;
3278      try {      try {
3279          if (iStreams < 0) throw Exception("Maximum disk streams may not be negative");          pSampler->SetGlobalMaxStreams(iStreams);
3280          GLOBAL_MAX_STREAMS = iStreams; // see common/global_private.cpp          LSCPServer::SendLSCPNotify(
3281          const std::set<Engine*>& engines = EngineFactory::EngineInstances();              LSCPEvent(LSCPEvent::event_global_info, "STREAMS", pSampler->GetGlobalMaxStreams())
3282          if (engines.size() > 0) {          );
             std::set<Engine*>::iterator iter = engines.begin();  
             std::set<Engine*>::iterator end  = engines.end();  
             for (; iter != end; ++iter) {  
                 (*iter)->SetMaxDiskStreams(iStreams);  
             }  
         }  
         LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "STREAMS", GLOBAL_MAX_STREAMS));  
3283      } catch (Exception e) {      } catch (Exception e) {
3284          result.Error(e);          result.Error(e);
3285      }      }
# Line 3334  void LSCPServer::VerifyFile(String Filen Line 3483  void LSCPServer::VerifyFile(String Filen
3483  String LSCPServer::SubscribeNotification(LSCPEvent::event_t type) {  String LSCPServer::SubscribeNotification(LSCPEvent::event_t type) {
3484      dmsg(2,("LSCPServer: SubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));      dmsg(2,("LSCPServer: SubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
3485      LSCPResultSet result;      LSCPResultSet result;
3486      SubscriptionMutex.Lock();      {
3487      eventSubscriptions[type].push_back(currentSocket);          LockGuard lock(SubscriptionMutex);
3488      SubscriptionMutex.Unlock();          eventSubscriptions[type].push_back(currentSocket);
3489        }
3490      return result.Produce();      return result.Produce();
3491  }  }
3492    
# Line 3347  String LSCPServer::SubscribeNotification Line 3497  String LSCPServer::SubscribeNotification
3497  String LSCPServer::UnsubscribeNotification(LSCPEvent::event_t type) {  String LSCPServer::UnsubscribeNotification(LSCPEvent::event_t type) {
3498      dmsg(2,("LSCPServer: UnsubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));      dmsg(2,("LSCPServer: UnsubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
3499      LSCPResultSet result;      LSCPResultSet result;
3500      SubscriptionMutex.Lock();      {
3501      eventSubscriptions[type].remove(currentSocket);          LockGuard lock(SubscriptionMutex);
3502      SubscriptionMutex.Unlock();          eventSubscriptions[type].remove(currentSocket);
3503        }
3504      return result.Produce();      return result.Produce();
3505  }  }
3506    
# Line 3874  String LSCPServer::SetEcho(yyparse_param Line 4025  String LSCPServer::SetEcho(yyparse_param
4025      }      }
4026      return result.Produce();      return result.Produce();
4027  }  }
4028    
4029    String LSCPServer::SetShellInteract(yyparse_param_t* pSession, double boolean_value) {
4030        dmsg(2,("LSCPServer: SetShellInteract(val=%f)\n", boolean_value));
4031        LSCPResultSet result;
4032        try {
4033            if      (boolean_value == 0) pSession->bShellInteract = false;
4034            else if (boolean_value == 1) pSession->bShellInteract = true;
4035            else throw Exception("Not a boolean value, must either be 0 or 1");
4036        } catch (Exception e) {
4037            result.Error(e);
4038        }
4039        return result.Produce();
4040    }
4041    
4042    String LSCPServer::SetShellAutoCorrect(yyparse_param_t* pSession, double boolean_value) {
4043        dmsg(2,("LSCPServer: SetShellAutoCorrect(val=%f)\n", boolean_value));
4044        LSCPResultSet result;
4045        try {
4046            if      (boolean_value == 0) pSession->bShellAutoCorrect = false;
4047            else if (boolean_value == 1) pSession->bShellAutoCorrect = true;
4048            else throw Exception("Not a boolean value, must either be 0 or 1");
4049        } catch (Exception e) {
4050            result.Error(e);
4051        }
4052        return result.Produce();
4053    }
4054    
4055  }  }

Legend:
Removed from v.2198  
changed lines
  Added in v.2531

  ViewVC Help
Powered by ViewVC