/[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 1727 by iliev, Tue Apr 29 15:44:09 2008 UTC revision 2528 by schoenebeck, Mon Mar 3 12:02:40 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 - 2008 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 22  Line 22 
22   ***************************************************************************/   ***************************************************************************/
23    
24  #include <algorithm>  #include <algorithm>
25    #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"
# Line 41  Line 43 
43  #include "../engines/EngineChannelFactory.h"  #include "../engines/EngineChannelFactory.h"
44  #include "../drivers/audio/AudioOutputDeviceFactory.h"  #include "../drivers/audio/AudioOutputDeviceFactory.h"
45  #include "../drivers/midi/MidiInputDeviceFactory.h"  #include "../drivers/midi/MidiInputDeviceFactory.h"
46    #include "../effects/EffectFactory.h"
47    
48    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
# Line 93  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 134  LSCPServer::LSCPServer(Sampler* pSampler Line 140  LSCPServer::LSCPServer(Sampler* pSampler
140      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
141      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");
142      LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI");      LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI");
143        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_instance_count, "EFFECT_INSTANCE_COUNT");
144        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_instance_info, "EFFECT_INSTANCE_INFO");
145        LSCPEvent::RegisterEvent(LSCPEvent::event_send_fx_chain_count, "SEND_EFFECT_CHAIN_COUNT");
146        LSCPEvent::RegisterEvent(LSCPEvent::event_send_fx_chain_info, "SEND_EFFECT_CHAIN_INFO");
147      hSocket = -1;      hSocket = -1;
148  }  }
149    
150  LSCPServer::~LSCPServer() {  LSCPServer::~LSCPServer() {
151        CloseAllConnections();
152        InstrumentManager::StopBackgroundThread();
153  #if defined(WIN32)  #if defined(WIN32)
154      if (hSocket >= 0) closesocket(hSocket);      if (hSocket >= 0) closesocket(hSocket);
155  #else  #else
# Line 332  void LSCPServer::DbInstrumentsEventHandl Line 344  void LSCPServer::DbInstrumentsEventHandl
344  }  }
345  #endif // HAVE_SQLITE3  #endif // HAVE_SQLITE3
346    
347    void LSCPServer::RemoveListeners() {
348        pSampler->RemoveChannelCountListener(&eventHandler);
349        pSampler->RemoveAudioDeviceCountListener(&eventHandler);
350        pSampler->RemoveMidiDeviceCountListener(&eventHandler);
351        pSampler->RemoveVoiceCountListener(&eventHandler);
352        pSampler->RemoveStreamCountListener(&eventHandler);
353        pSampler->RemoveBufferFillListener(&eventHandler);
354        pSampler->RemoveTotalStreamCountListener(&eventHandler);
355        pSampler->RemoveTotalVoiceCountListener(&eventHandler);
356        pSampler->RemoveFxSendCountListener(&eventHandler);
357        MidiInstrumentMapper::RemoveMidiInstrumentCountListener(&eventHandler);
358        MidiInstrumentMapper::RemoveMidiInstrumentInfoListener(&eventHandler);
359        MidiInstrumentMapper::RemoveMidiInstrumentMapCountListener(&eventHandler);
360        MidiInstrumentMapper::RemoveMidiInstrumentMapInfoListener(&eventHandler);
361    #if HAVE_SQLITE3
362        InstrumentsDb::GetInstrumentsDb()->RemoveInstrumentsDbListener(&dbInstrumentsEventHandler);
363    #endif
364    }
365    
366  /**  /**
367   * Blocks the calling thread until the LSCP Server is initialized and   * Blocks the calling thread until the LSCP Server is initialized and
# Line 419  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();
456              for (; itEngineChannel != itEnd; ++itEngineChannel) {              for (; itEngineChannel != itEnd; ++itEngineChannel) {
457                  if ((*itEngineChannel)->StatusChanged()) {                  if ((*itEngineChannel)->StatusChanged()) {
458                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->GetSamplerChannel()->Index()));
459                  }                  }
460    
461                  for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {                  for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
462                      FxSend* fxs = (*itEngineChannel)->GetFxSend(i);                      FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
463                      if(fxs != NULL && fxs->IsInfoChanged()) {                      if(fxs != NULL && fxs->IsInfoChanged()) {
464                          int chn = (*itEngineChannel)->iSamplerChannelIndex;                          int chn = (*itEngineChannel)->GetSamplerChannel()->Index();
465                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
466                          fxs->SetInfoChanged(false);                          fxs->SetInfoChanged(false);
467                      }                      }
# Line 487  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 505  int LSCPServer::Main() { Line 537  int LSCPServer::Main() {
537    
538          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);
539    
540          if (retval == 0)          if (retval == 0 || (retval == -1 && errno == EINTR))
541                  continue; //Nothing try again                  continue; //Nothing try again
542          if (retval == -1) {          if (retval == -1) {
543                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
# Line 532  int LSCPServer::Main() { Line 564  int LSCPServer::Main() {
564                    exit(EXIT_FAILURE);                    exit(EXIT_FAILURE);
565                  }                  }
566          #else          #else
567                    struct linger linger;
568                    linger.l_onoff = 1;
569                    linger.l_linger = 0;
570                    if(setsockopt(socket, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger))) {
571                        std::cerr << "LSCPServer: Failed to set SO_LINGER\n";
572                    }
573    
574                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
575                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
576                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
# Line 555  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 573  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 587  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 600  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();  
 }  
   
 void LSCPServer::LockRTNotify() {  
     RTNotifyMutex.Lock();  
645  }  }
646    
647  void LSCPServer::UnlockRTNotify() {  void LSCPServer::CloseAllConnections() {
648      RTNotifyMutex.Unlock();      std::vector<yyparse_param_t>::iterator iter = Sessions.begin();
649        while(iter != Sessions.end()) {
650            CloseConnection(iter);
651            iter = Sessions.begin();
652        }
653  }  }
654    
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 652  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 683  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    
741            // process input buffer
742            for (int i = 0; i < input.size(); ++i) {
743                    c = input[i];
744                    if (c == '\r') continue; //Ignore CR
745                    if (c == '\n') {
746                            // 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                  }                  }
758                  if (result == 1) {                  // backspace character - should only happen with shell
759                          if (c == '\r')                  if (c == '\b') {
760                                  continue; //Ignore CR                          if (!bufferedCommands[socket].empty()) {
761                          if (c == '\n') {                                  bufferedCommands[socket] = bufferedCommands[socket].substr(
762                                  LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Received \'" + bufferedCommands[socket] + "\' on socket", socket));                                          0, bufferedCommands[socket].length() - 1
763                                  bufferedCommands[socket] += "\r\n";                                  );
                                 return true; //Complete command was read  
764                          }                          }
765                          bufferedCommands[socket] += c;                  } else bufferedCommands[socket] += c;
766                    // only if the other side is the LSCP shell application:
767                    // check the current (incomplete) command line for syntax errors,
768                    // possible completions and report everything back to the shell
769                    if ((*iter).bShellInteract || (*iter).bShellAutoCorrect) {
770                            String s = lscpParserProcessShellInteraction(bufferedCommands[socket], &(*iter), true);
771                            if (!s.empty() && (*iter).bShellInteract && i == input.size() - 1)
772                                    AnswerClient(s + "\n");
773                  }                  }
774                  #if defined(WIN32)          }
775                  if (result == SOCKET_ERROR) {  
776                      int wsa_lasterror = WSAGetLastError();          // handle network errors ...
777                          if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.          if (result == 0) { //socket was selected, so 0 here means client has closed the connection
778                    CloseConnection(iter);
779                    return false;
780            }
781            #if defined(WIN32)
782            if (result == SOCKET_ERROR) {
783                    int wsa_lasterror = WSAGetLastError();
784                    if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
785                            return false;
786                    dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
787                    CloseConnection(iter);
788                    return false;
789            }
790            #else
791            if (result == -1) {
792                    if (errno == EAGAIN) //Would block, try again later.
793                            return false;
794                    switch(errno) {
795                            case EBADF:
796                                    dmsg(2,("LSCPScanner: The argument s is an invalid descriptor.\n"));
797                                  return false;                                  return false;
798                          dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));                          case ECONNREFUSED:
799                          CloseConnection(iter);                                  dmsg(2,("LSCPScanner: A remote host refused to allow the network connection (typically because it is not running the requested service).\n"));
800                          break;                                  return false;
801                  }                          case ENOTCONN:
802                  #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"));
803                  if (result == -1) {                                  return false;
804                          if (errno == EAGAIN) //Would block, try again later.                          case ENOTSOCK:
805                                    dmsg(2,("LSCPScanner: The argument s does not refer to a socket.\n"));
806                                    return false;
807                            case EAGAIN:
808                                    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"));
809                                    return false;
810                            case EINTR:
811                                    dmsg(2,("LSCPScanner: The receive was interrupted by delivery of a signal before any data were available.\n"));
812                                    return false;
813                            case EFAULT:
814                                    dmsg(2,("LSCPScanner: The receive buffer pointer(s) point outside the process's address space.\n"));
815                                    return false;
816                            case EINVAL:
817                                    dmsg(2,("LSCPScanner: Invalid argument passed.\n"));
818                                    return false;
819                            case ENOMEM:
820                                    dmsg(2,("LSCPScanner: Could not allocate memory for recvmsg.\n"));
821                                    return false;
822                            default:
823                                    dmsg(2,("LSCPScanner: Unknown recv() error.\n"));
824                                  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;  
825                  }                  }
826                  #endif                  CloseConnection(iter);
827                    return false;
828          }          }
829            #endif
830    
831          return false;          return false;
832  }  }
833    
# Line 765  bool LSCPServer::GetLSCPCommand( std::ve Line 838  bool LSCPServer::GetLSCPCommand( std::ve
838   * @param ReturnMessage - message that will be send to the client   * @param ReturnMessage - message that will be send to the client
839   */   */
840  void LSCPServer::AnswerClient(String ReturnMessage) {  void LSCPServer::AnswerClient(String ReturnMessage) {
841      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str()));      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage='%s')", ReturnMessage.c_str()));
842      if (currentSocket != -1) {      if (currentSocket != -1) {
843              NotifyMutex.Lock();              LockGuard lock(NotifyMutex);
844    
845            // just if other side is LSCP shell: in case respose is a multi-line
846            // one, then inform client about it before sending the actual mult-line
847            // response
848            if (GetCurrentYaccSession()->bShellInteract) {
849                // check if this is a multi-line response
850                int n = 0;
851                for (int i = 0; i < ReturnMessage.size(); ++i)
852                    if (ReturnMessage[i] == '\n') ++n;
853                if (n >= 2) {
854                    dmsg(2,("LSCP Shell <- expect mult-line response\n"));
855                    String s = LSCP_SHK_EXPECT_MULTI_LINE "\r\n";
856    #ifdef MSG_NOSIGNAL
857                    send(currentSocket, s.c_str(), s.size(), MSG_NOSIGNAL);
858    #else
859                    send(currentSocket, s.c_str(), s.size(), 0);
860    #endif                
861                }
862            }
863    
864  #ifdef MSG_NOSIGNAL  #ifdef MSG_NOSIGNAL
865              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), MSG_NOSIGNAL);              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), MSG_NOSIGNAL);
866  #else  #else
867              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);
868  #endif  #endif
             NotifyMutex.Unlock();  
869      }      }
870  }  }
871    
# Line 923  String LSCPServer::SetEngineType(String Line 1015  String LSCPServer::SetEngineType(String
1015      try {      try {
1016          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1017          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1018          LockRTNotify();          LockGuard lock(RTNotifyMutex);
1019          pSamplerChannel->SetEngineType(EngineName);          pSamplerChannel->SetEngineType(EngineName);
1020          if(HasSoloChannel()) pSamplerChannel->GetEngineChannel()->SetMute(-1);          if(HasSoloChannel()) pSamplerChannel->GetEngineChannel()->SetMute(-1);
         UnlockRTNotify();  
1021      }      }
1022      catch (Exception e) {      catch (Exception e) {
1023           result.Error(e);           result.Error(e);
# Line 966  String LSCPServer::ListChannels() { Line 1057  String LSCPServer::ListChannels() {
1057   */   */
1058  String LSCPServer::AddChannel() {  String LSCPServer::AddChannel() {
1059      dmsg(2,("LSCPServer: AddChannel()\n"));      dmsg(2,("LSCPServer: AddChannel()\n"));
1060      LockRTNotify();      SamplerChannel* pSamplerChannel;
1061      SamplerChannel* pSamplerChannel = pSampler->AddSamplerChannel();      {
1062      UnlockRTNotify();          LockGuard lock(RTNotifyMutex);
1063            pSamplerChannel = pSampler->AddSamplerChannel();
1064        }
1065      LSCPResultSet result(pSamplerChannel->Index());      LSCPResultSet result(pSamplerChannel->Index());
1066      return result.Produce();      return result.Produce();
1067  }  }
# Line 979  String LSCPServer::AddChannel() { Line 1072  String LSCPServer::AddChannel() {
1072  String LSCPServer::RemoveChannel(uint uiSamplerChannel) {  String LSCPServer::RemoveChannel(uint uiSamplerChannel) {
1073      dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel));
1074      LSCPResultSet result;      LSCPResultSet result;
1075      LockRTNotify();      {
1076      pSampler->RemoveSamplerChannel(uiSamplerChannel);          LockGuard lock(RTNotifyMutex);
1077      UnlockRTNotify();          pSampler->RemoveSamplerChannel(uiSamplerChannel);
1078        }
1079      return result.Produce();      return result.Produce();
1080  }  }
1081    
# Line 1024  String LSCPServer::ListAvailableEngines( Line 1118  String LSCPServer::ListAvailableEngines(
1118  String LSCPServer::GetEngineInfo(String EngineName) {  String LSCPServer::GetEngineInfo(String EngineName) {
1119      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));
1120      LSCPResultSet result;      LSCPResultSet result;
1121      LockRTNotify();      {
1122      try {          LockGuard lock(RTNotifyMutex);
1123          Engine* pEngine = EngineFactory::Create(EngineName);          try {
1124          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));              Engine* pEngine = EngineFactory::Create(EngineName);
1125          result.Add("VERSION",     pEngine->Version());              result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
1126          EngineFactory::Destroy(pEngine);              result.Add("VERSION",     pEngine->Version());
1127      }              EngineFactory::Destroy(pEngine);
1128      catch (Exception e) {          }
1129           result.Error(e);          catch (Exception e) {
1130                result.Error(e);
1131            }
1132      }      }
     UnlockRTNotify();  
1133      return result.Produce();      return result.Produce();
1134  }  }
1135    
# Line 1133  String LSCPServer::GetVoiceCount(uint ui Line 1228  String LSCPServer::GetVoiceCount(uint ui
1228      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));
1229      LSCPResultSet result;      LSCPResultSet result;
1230      try {      try {
1231          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine loaded on sampler channel");  
1232          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1233          result.Add(pEngineChannel->GetEngine()->VoiceCount());          result.Add(pEngineChannel->GetEngine()->VoiceCount());
1234      }      }
# Line 1154  String LSCPServer::GetStreamCount(uint u Line 1246  String LSCPServer::GetStreamCount(uint u
1246      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));
1247      LSCPResultSet result;      LSCPResultSet result;
1248      try {      try {
1249          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
1250          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1251          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());
1252      }      }
# Line 1175  String LSCPServer::GetBufferFill(fill_re Line 1264  String LSCPServer::GetBufferFill(fill_re
1264      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));
1265      LSCPResultSet result;      LSCPResultSet result;
1266      try {      try {
1267          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
1268          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1269          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");
1270          else {          else {
# Line 1266  String LSCPServer::GetMidiInputDriverInf Line 1352  String LSCPServer::GetMidiInputDriverInf
1352              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1353                  if (s != "") s += ",";                  if (s != "") s += ",";
1354                  s += iter->first;                  s += iter->first;
1355                    delete iter->second;
1356              }              }
1357              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1358          }          }
# Line 1290  String LSCPServer::GetAudioOutputDriverI Line 1377  String LSCPServer::GetAudioOutputDriverI
1377              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1378                  if (s != "") s += ",";                  if (s != "") s += ",";
1379                  s += iter->first;                  s += iter->first;
1380                    delete iter->second;
1381              }              }
1382              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1383          }          }
# Line 1320  String LSCPServer::GetMidiInputDriverPar Line 1408  String LSCPServer::GetMidiInputDriverPar
1408          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1409          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1410          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1411            delete pParameter;
1412      }      }
1413      catch (Exception e) {      catch (Exception e) {
1414          result.Error(e);          result.Error(e);
# Line 1347  String LSCPServer::GetAudioOutputDriverP Line 1436  String LSCPServer::GetAudioOutputDriverP
1436          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1437          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1438          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1439            delete pParameter;
1440      }      }
1441      catch (Exception e) {      catch (Exception e) {
1442          result.Error(e);          result.Error(e);
# Line 1688  String LSCPServer::SetAudioOutputChannel Line 1778  String LSCPServer::SetAudioOutputChannel
1778  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {
1779      dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));      dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));
1780      LSCPResultSet result;      LSCPResultSet result;
1781      LockRTNotify();      {
1782            LockGuard lock(RTNotifyMutex);
1783            try {
1784                SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1785                if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1786                std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1787                if (!devices.count(AudioDeviceId)) throw Exception("There is no audio output device with index " + ToString(AudioDeviceId));
1788                AudioOutputDevice* pDevice = devices[AudioDeviceId];
1789                pSamplerChannel->SetAudioOutputDevice(pDevice);
1790            }
1791            catch (Exception e) {
1792                result.Error(e);
1793            }
1794        }
1795        return result.Produce();
1796    }
1797    
1798    String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {
1799        dmsg(2,("LSCPServer: SetAudioOutputType(String AudioOutputDriver=%s, SamplerChannel=%d)\n",AudioOutputDriver.c_str(),uiSamplerChannel));
1800        LSCPResultSet result;
1801        {
1802            LockGuard lock(RTNotifyMutex);
1803            try {
1804                SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1805                if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1806                // Driver type name aliasing...
1807                if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA";
1808                if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK";
1809                // Check if there's one audio output device already created
1810                // for the intended audio driver type (AudioOutputDriver)...
1811                AudioOutputDevice *pDevice = NULL;
1812                std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1813                std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();
1814                for (; iter != devices.end(); iter++) {
1815                    if ((iter->second)->Driver() == AudioOutputDriver) {
1816                        pDevice = iter->second;
1817                        break;
1818                    }
1819                }
1820                // If it doesn't exist, create a new one with default parameters...
1821                if (pDevice == NULL) {
1822                    std::map<String,String> params;
1823                    pDevice = pSampler->CreateAudioOutputDevice(AudioOutputDriver, params);
1824                }
1825                // Must have a device...
1826                if (pDevice == NULL)
1827                    throw Exception("Internal error: could not create audio output device.");
1828                // Set it as the current channel device...
1829                pSamplerChannel->SetAudioOutputDevice(pDevice);
1830            }
1831            catch (Exception e) {
1832                result.Error(e);
1833            }
1834        }
1835        return result.Produce();
1836    }
1837    
1838    String LSCPServer::AddChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId, uint MIDIPort) {
1839        dmsg(2,("LSCPServer: AddChannelMidiInput(uiSamplerChannel=%d, MIDIDeviceId=%d, MIDIPort=%d)\n",uiSamplerChannel,MIDIDeviceId,MIDIPort));
1840        LSCPResultSet result;
1841      try {      try {
1842          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1843          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1844          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();  
1845          if (!devices.count(AudioDeviceId)) throw Exception("There is no audio output device with index " + ToString(AudioDeviceId));          std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1846          AudioOutputDevice* pDevice = devices[AudioDeviceId];          if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1847          pSamplerChannel->SetAudioOutputDevice(pDevice);          MidiInputDevice* pDevice = devices[MIDIDeviceId];
1848    
1849            MidiInputPort* pPort = pDevice->GetPort(MIDIPort);
1850            if (!pPort) throw Exception("There is no MIDI input port with index " + ToString(MIDIPort) + " on MIDI input device with index " + ToString(MIDIDeviceId));
1851    
1852            pSamplerChannel->Connect(pPort);
1853        } catch (Exception e) {
1854            result.Error(e);
1855      }      }
1856      catch (Exception e) {      return result.Produce();
1857           result.Error(e);  }
1858    
1859    String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel) {
1860        dmsg(2,("LSCPServer: RemoveChannelMidiInput(uiSamplerChannel=%d)\n",uiSamplerChannel));
1861        LSCPResultSet result;
1862        try {
1863            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1864            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1865            pSamplerChannel->DisconnectAllMidiInputPorts();
1866        } catch (Exception e) {
1867            result.Error(e);
1868      }      }
     UnlockRTNotify();  
1869      return result.Produce();      return result.Produce();
1870  }  }
1871    
1872  String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {  String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId) {
1873      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));
1874      LSCPResultSet result;      LSCPResultSet result;
     LockRTNotify();  
1875      try {      try {
1876          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1877          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1878          // Driver type name aliasing...  
1879          if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA";          std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1880          if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK";          if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1881          // Check if there's one audio output device already created          MidiInputDevice* pDevice = devices[MIDIDeviceId];
1882          // for the intended audio driver type (AudioOutputDriver)...          
1883          AudioOutputDevice *pDevice = NULL;          std::vector<MidiInputPort*> vPorts = pSamplerChannel->GetMidiInputPorts();
1884          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          for (int i = 0; i < vPorts.size(); ++i)
1885          std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();              if (vPorts[i]->GetDevice() == pDevice)
1886          for (; iter != devices.end(); iter++) {                  pSamplerChannel->Disconnect(vPorts[i]);
1887              if ((iter->second)->Driver() == AudioOutputDriver) {  
1888                  pDevice = iter->second;      } catch (Exception e) {
1889                  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);  
1890      }      }
1891      catch (Exception e) {      return result.Produce();
1892           result.Error(e);  }
1893    
1894    String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId, uint MIDIPort) {
1895        dmsg(2,("LSCPServer: RemoveChannelMidiInput(uiSamplerChannel=%d, MIDIDeviceId=%d, MIDIPort=%d)\n",uiSamplerChannel,MIDIDeviceId,MIDIPort));
1896        LSCPResultSet result;
1897        try {
1898            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1899            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1900    
1901            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1902            if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1903            MidiInputDevice* pDevice = devices[MIDIDeviceId];
1904    
1905            MidiInputPort* pPort = pDevice->GetPort(MIDIPort);
1906            if (!pPort) throw Exception("There is no MIDI input port with index " + ToString(MIDIPort) + " on MIDI input device with index " + ToString(MIDIDeviceId));
1907    
1908            pSamplerChannel->Disconnect(pPort);
1909        } catch (Exception e) {
1910            result.Error(e);
1911        }
1912        return result.Produce();
1913    }
1914    
1915    String LSCPServer::ListChannelMidiInputs(uint uiSamplerChannel) {
1916        dmsg(2,("LSCPServer: ListChannelMidiInputs(uiSamplerChannel=%d)\n",uiSamplerChannel));
1917        LSCPResultSet result;
1918        try {
1919            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1920            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1921            std::vector<MidiInputPort*> vPorts = pSamplerChannel->GetMidiInputPorts();
1922    
1923            String s;
1924            for (int i = 0; i < vPorts.size(); ++i) {
1925                const int iDeviceID = vPorts[i]->GetDevice()->MidiInputDeviceID();
1926                const int iPortNr   = vPorts[i]->GetPortNumber();
1927                if (s.size()) s += ",";
1928                s += "{" + ToString(iDeviceID) + ","
1929                         + ToString(iPortNr) + "}";
1930            }
1931            result.Add(s);
1932        } catch (Exception e) {
1933            result.Error(e);
1934      }      }
     UnlockRTNotify();  
1935      return result.Produce();      return result.Produce();
1936  }  }
1937    
# Line 1813  String LSCPServer::SetMIDIInputType(Stri Line 2005  String LSCPServer::SetMIDIInputType(Stri
2005              pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);              pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);
2006              // Make it with at least one initial port.              // Make it with at least one initial port.
2007              std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();              std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
             parameters["PORTS"]->SetValue("1");  
2008          }          }
2009          // Must have a device...          // Must have a device...
2010          if (pDevice == NULL)          if (pDevice == NULL)
# Line 1856  String LSCPServer::SetVolume(double dVol Line 2047  String LSCPServer::SetVolume(double dVol
2047      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));
2048      LSCPResultSet result;      LSCPResultSet result;
2049      try {      try {
2050          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
2051          pEngineChannel->Volume(dVolume);          pEngineChannel->Volume(dVolume);
2052      }      }
2053      catch (Exception e) {      catch (Exception e) {
# Line 1875  String LSCPServer::SetChannelMute(bool b Line 2063  String LSCPServer::SetChannelMute(bool b
2063      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));
2064      LSCPResultSet result;      LSCPResultSet result;
2065      try {      try {
2066          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
2067    
2068          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);
2069          else pEngineChannel->SetMute(1);          else pEngineChannel->SetMute(1);
# Line 1896  String LSCPServer::SetChannelSolo(bool b Line 2080  String LSCPServer::SetChannelSolo(bool b
2080      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));
2081      LSCPResultSet result;      LSCPResultSet result;
2082      try {      try {
2083          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
2084    
2085          bool oldSolo = pEngineChannel->GetSolo();          bool oldSolo = pEngineChannel->GetSolo();
2086          bool hadSoloChannel = HasSoloChannel();          bool hadSoloChannel = HasSoloChannel();
# Line 2020  String LSCPServer::GetMidiInstrumentMapp Line 2200  String LSCPServer::GetMidiInstrumentMapp
2200      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));
2201      LSCPResultSet result;      LSCPResultSet result;
2202      try {      try {
2203          result.Add(MidiInstrumentMapper::Entries(MidiMapID).size());          result.Add(MidiInstrumentMapper::GetInstrumentCount(MidiMapID));
2204      } catch (Exception e) {      } catch (Exception e) {
2205          result.Error(e);          result.Error(e);
2206      }      }
# Line 2031  String LSCPServer::GetMidiInstrumentMapp Line 2211  String LSCPServer::GetMidiInstrumentMapp
2211  String LSCPServer::GetAllMidiInstrumentMappings() {  String LSCPServer::GetAllMidiInstrumentMappings() {
2212      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));
2213      LSCPResultSet result;      LSCPResultSet result;
2214      std::vector<int> maps = MidiInstrumentMapper::Maps();      try {
2215      int totalMappings = 0;          result.Add(MidiInstrumentMapper::GetInstrumentCount());
2216      for (int i = 0; i < maps.size(); i++) {      } catch (Exception e) {
2217          try {          result.Error(e);
             totalMappings += MidiInstrumentMapper::Entries(maps[i]).size();  
         } catch (Exception e) { /*NOOP*/ }  
2218      }      }
     result.Add(totalMappings);  
2219      return result.Produce();      return result.Produce();
2220  }  }
2221    
# Line 2046  String LSCPServer::GetMidiInstrumentMapp Line 2223  String LSCPServer::GetMidiInstrumentMapp
2223      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));
2224      LSCPResultSet result;      LSCPResultSet result;
2225      try {      try {
2226          midi_prog_index_t idx;          MidiInstrumentMapper::entry_t entry = MidiInstrumentMapper::GetEntry(MidiMapID, MidiBank, MidiProg);
2227          idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;          // convert the filename into the correct encoding as defined for LSCP
2228          idx.midi_bank_lsb = MidiBank & 0x7f;          // (especially in terms of special characters -> escape sequences)
         idx.midi_prog     = MidiProg;  
   
         std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(MidiMapID);  
         std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);  
         if (iter == mappings.end()) result.Error("there is no map entry with that index");  
         else { // found  
   
             // convert the filename into the correct encoding as defined for LSCP  
             // (especially in terms of special characters -> escape sequences)  
2229  #if WIN32  #if WIN32
2230              const String instrumentFileName = Path::fromWindows(iter->second.InstrumentFile).toLscp();          const String instrumentFileName = Path::fromWindows(entry.InstrumentFile).toLscp();
2231  #else  #else
2232              // assuming POSIX          // assuming POSIX
2233              const String instrumentFileName = Path::fromPosix(iter->second.InstrumentFile).toLscp();          const String instrumentFileName = Path::fromPosix(entry.InstrumentFile).toLscp();
2234  #endif  #endif
2235    
2236              result.Add("NAME", _escapeLscpResponse(iter->second.Name));          result.Add("NAME", _escapeLscpResponse(entry.Name));
2237              result.Add("ENGINE_NAME", iter->second.EngineName);          result.Add("ENGINE_NAME", entry.EngineName);
2238              result.Add("INSTRUMENT_FILE", instrumentFileName);          result.Add("INSTRUMENT_FILE", instrumentFileName);
2239              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);          result.Add("INSTRUMENT_NR", (int) entry.InstrumentIndex);
2240              String instrumentName;          String instrumentName;
2241              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);          Engine* pEngine = EngineFactory::Create(entry.EngineName);
2242              if (pEngine) {          if (pEngine) {
2243                  if (pEngine->GetInstrumentManager()) {              if (pEngine->GetInstrumentManager()) {
2244                      InstrumentManager::instrument_id_t instrID;                  InstrumentManager::instrument_id_t instrID;
2245                      instrID.FileName = iter->second.InstrumentFile;                  instrID.FileName = entry.InstrumentFile;
2246                      instrID.Index    = iter->second.InstrumentIndex;                  instrID.Index    = entry.InstrumentIndex;
2247                      instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);                  instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);
                 }  
                 EngineFactory::Destroy(pEngine);  
             }  
             result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));  
             switch (iter->second.LoadMode) {  
                 case MidiInstrumentMapper::ON_DEMAND:  
                     result.Add("LOAD_MODE", "ON_DEMAND");  
                     break;  
                 case MidiInstrumentMapper::ON_DEMAND_HOLD:  
                     result.Add("LOAD_MODE", "ON_DEMAND_HOLD");  
                     break;  
                 case MidiInstrumentMapper::PERSISTENT:  
                     result.Add("LOAD_MODE", "PERSISTENT");  
                     break;  
                 default:  
                     throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");  
2248              }              }
2249              result.Add("VOLUME", iter->second.Volume);              EngineFactory::Destroy(pEngine);
2250          }          }
2251            result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
2252            switch (entry.LoadMode) {
2253                case MidiInstrumentMapper::ON_DEMAND:
2254                    result.Add("LOAD_MODE", "ON_DEMAND");
2255                    break;
2256                case MidiInstrumentMapper::ON_DEMAND_HOLD:
2257                    result.Add("LOAD_MODE", "ON_DEMAND_HOLD");
2258                    break;
2259                case MidiInstrumentMapper::PERSISTENT:
2260                    result.Add("LOAD_MODE", "PERSISTENT");
2261                    break;
2262                default:
2263                    throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");
2264            }
2265            result.Add("VOLUME", entry.Volume);
2266      } catch (Exception e) {      } catch (Exception e) {
2267          result.Error(e);          result.Error(e);
2268      }      }
# Line 2266  String LSCPServer::SetChannelMap(uint ui Line 2433  String LSCPServer::SetChannelMap(uint ui
2433      dmsg(2,("LSCPServer: SetChannelMap()\n"));      dmsg(2,("LSCPServer: SetChannelMap()\n"));
2434      LSCPResultSet result;      LSCPResultSet result;
2435      try {      try {
2436          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");  
2437    
2438          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();
2439          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();
# Line 2378  String LSCPServer::GetFxSendInfo(uint ui Line 2541  String LSCPServer::GetFxSendInfo(uint ui
2541              AudioRouting += ToString(pFxSend->DestinationChannel(chan));              AudioRouting += ToString(pFxSend->DestinationChannel(chan));
2542          }          }
2543    
2544            const String sEffectRouting =
2545                (pFxSend->DestinationEffectChain() >= 0 && pFxSend->DestinationEffectChainPosition() >= 0)
2546                    ? ToString(pFxSend->DestinationEffectChain()) + "," + ToString(pFxSend->DestinationEffectChainPosition())
2547                    : "NONE";
2548    
2549          // success          // success
2550          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2551          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2552          result.Add("LEVEL", ToString(pFxSend->Level()));          result.Add("LEVEL", ToString(pFxSend->Level()));
2553          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
2554            result.Add("EFFECT", sEffectRouting);
2555      } catch (Exception e) {      } catch (Exception e) {
2556          result.Error(e);          result.Error(e);
2557      }      }
# Line 2445  String LSCPServer::SetFxSendLevel(uint u Line 2614  String LSCPServer::SetFxSendLevel(uint u
2614      return result.Produce();      return result.Produce();
2615  }  }
2616    
2617    String LSCPServer::SetFxSendEffect(uint uiSamplerChannel, uint FxSendID, int iSendEffectChain, int iEffectChainPosition) {
2618        dmsg(2,("LSCPServer: SetFxSendEffect(%d,%d)\n", iSendEffectChain, iEffectChainPosition));
2619        LSCPResultSet result;
2620        try {
2621            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2622    
2623            pFxSend->SetDestinationEffect(iSendEffectChain, iEffectChainPosition);
2624            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2625        } catch (Exception e) {
2626            result.Error(e);
2627        }
2628        return result.Produce();
2629    }
2630    
2631    String LSCPServer::GetAvailableEffects() {
2632        dmsg(2,("LSCPServer: GetAvailableEffects()\n"));
2633        LSCPResultSet result;
2634        try {
2635            int n = EffectFactory::AvailableEffectsCount();
2636            result.Add(n);
2637        }
2638        catch (Exception e) {
2639            result.Error(e);
2640        }
2641        return result.Produce();
2642    }
2643    
2644    String LSCPServer::ListAvailableEffects() {
2645        dmsg(2,("LSCPServer: ListAvailableEffects()\n"));
2646        LSCPResultSet result;
2647        String list;
2648        try {
2649            //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
2650            int n = EffectFactory::AvailableEffectsCount();
2651            for (int i = 0; i < n; i++) {
2652                if (i) list += ",";
2653                list += ToString(i);
2654            }
2655        }
2656        catch (Exception e) {
2657            result.Error(e);
2658        }
2659        result.Add(list);
2660        return result.Produce();
2661    }
2662    
2663    String LSCPServer::GetEffectInfo(int iEffectIndex) {
2664        dmsg(2,("LSCPServer: GetEffectInfo(%d)\n", iEffectIndex));
2665        LSCPResultSet result;
2666        try {
2667            EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(iEffectIndex);
2668            if (!pEffectInfo)
2669                throw Exception("There is no effect with index " + ToString(iEffectIndex));
2670    
2671            // convert the filename into the correct encoding as defined for LSCP
2672            // (especially in terms of special characters -> escape sequences)
2673    #if WIN32
2674            const String dllFileName = Path::fromWindows(pEffectInfo->Module()).toLscp();
2675    #else
2676            // assuming POSIX
2677            const String dllFileName = Path::fromPosix(pEffectInfo->Module()).toLscp();
2678    #endif
2679    
2680            result.Add("SYSTEM", pEffectInfo->EffectSystem());
2681            result.Add("MODULE", dllFileName);
2682            result.Add("NAME", _escapeLscpResponse(pEffectInfo->Name()));
2683            result.Add("DESCRIPTION", _escapeLscpResponse(pEffectInfo->Description()));
2684        }
2685        catch (Exception e) {
2686            result.Error(e);
2687        }
2688        return result.Produce();    
2689    }
2690    
2691    String LSCPServer::GetEffectInstanceInfo(int iEffectInstance) {
2692        dmsg(2,("LSCPServer: GetEffectInstanceInfo(%d)\n", iEffectInstance));
2693        LSCPResultSet result;
2694        try {
2695            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2696            if (!pEffect)
2697                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2698    
2699            EffectInfo* pEffectInfo = pEffect->GetEffectInfo();
2700    
2701            // convert the filename into the correct encoding as defined for LSCP
2702            // (especially in terms of special characters -> escape sequences)
2703    #if WIN32
2704            const String dllFileName = Path::fromWindows(pEffectInfo->Module()).toLscp();
2705    #else
2706            // assuming POSIX
2707            const String dllFileName = Path::fromPosix(pEffectInfo->Module()).toLscp();
2708    #endif
2709    
2710            result.Add("SYSTEM", pEffectInfo->EffectSystem());
2711            result.Add("MODULE", dllFileName);
2712            result.Add("NAME", _escapeLscpResponse(pEffectInfo->Name()));
2713            result.Add("DESCRIPTION", _escapeLscpResponse(pEffectInfo->Description()));
2714            result.Add("INPUT_CONTROLS", ToString(pEffect->InputControlCount()));
2715        }
2716        catch (Exception e) {
2717            result.Error(e);
2718        }
2719        return result.Produce();
2720    }
2721    
2722    String LSCPServer::GetEffectInstanceInputControlInfo(int iEffectInstance, int iInputControlIndex) {
2723        dmsg(2,("LSCPServer: GetEffectInstanceInputControlInfo(%d,%d)\n", iEffectInstance, iInputControlIndex));
2724        LSCPResultSet result;
2725        try {
2726            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2727            if (!pEffect)
2728                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2729    
2730            EffectControl* pEffectControl = pEffect->InputControl(iInputControlIndex);
2731            if (!pEffectControl)
2732                throw Exception(
2733                    "Effect instance " + ToString(iEffectInstance) +
2734                    " does not have an input control with index " +
2735                    ToString(iInputControlIndex)
2736                );
2737    
2738            result.Add("DESCRIPTION", _escapeLscpResponse(pEffectControl->Description()));
2739            result.Add("VALUE", pEffectControl->Value());
2740            if (pEffectControl->MinValue())
2741                 result.Add("RANGE_MIN", *pEffectControl->MinValue());
2742            if (pEffectControl->MaxValue())
2743                 result.Add("RANGE_MAX", *pEffectControl->MaxValue());
2744            if (!pEffectControl->Possibilities().empty())
2745                 result.Add("POSSIBILITIES", pEffectControl->Possibilities());
2746            if (pEffectControl->DefaultValue())
2747                 result.Add("DEFAULT", *pEffectControl->DefaultValue());
2748        } catch (Exception e) {
2749            result.Error(e);
2750        }
2751        return result.Produce();
2752    }
2753    
2754    String LSCPServer::SetEffectInstanceInputControlValue(int iEffectInstance, int iInputControlIndex, double dValue) {
2755        dmsg(2,("LSCPServer: SetEffectInstanceInputControlValue(%d,%d,%f)\n", iEffectInstance, iInputControlIndex, dValue));
2756        LSCPResultSet result;
2757        try {
2758            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2759            if (!pEffect)
2760                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2761    
2762            EffectControl* pEffectControl = pEffect->InputControl(iInputControlIndex);
2763            if (!pEffectControl)
2764                throw Exception(
2765                    "Effect instance " + ToString(iEffectInstance) +
2766                    " does not have an input control with index " +
2767                    ToString(iInputControlIndex)
2768                );
2769    
2770            pEffectControl->SetValue(dValue);
2771            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_info, iEffectInstance));
2772        } catch (Exception e) {
2773            result.Error(e);
2774        }
2775        return result.Produce();
2776    }
2777    
2778    String LSCPServer::CreateEffectInstance(int iEffectIndex) {
2779        dmsg(2,("LSCPServer: CreateEffectInstance(%d)\n", iEffectIndex));
2780        LSCPResultSet result;
2781        try {
2782            EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(iEffectIndex);
2783            if (!pEffectInfo)
2784                throw Exception("There is no effect with index " + ToString(iEffectIndex));
2785            Effect* pEffect = EffectFactory::Create(pEffectInfo);
2786            result = pEffect->ID(); // success
2787            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_count, EffectFactory::EffectInstancesCount()));
2788        } catch (Exception e) {
2789            result.Error(e);
2790        }
2791        return result.Produce();
2792    }
2793    
2794    String LSCPServer::CreateEffectInstance(String effectSystem, String module, String effectName) {
2795        dmsg(2,("LSCPServer: CreateEffectInstance('%s','%s','%s')\n", effectSystem.c_str(), module.c_str(), effectName.c_str()));
2796        LSCPResultSet result;
2797        try {
2798            // to allow loading the same LSCP session file on different systems
2799            // successfully, probably with different effect plugin DLL paths or even
2800            // running completely different operating systems, we do the following
2801            // for finding the right effect:
2802            //
2803            // first try to search for an exact match of the effect plugin DLL
2804            // (a.k.a 'module'), to avoid picking the wrong DLL with the same
2805            // effect name ...
2806            EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_MATCH_EXACTLY);
2807            // ... if no effect with exactly matchin DLL filename was found, then
2808            // try to lower the restrictions of matching the effect plugin DLL
2809            // filename and try again and again ...
2810            if (!pEffectInfo) {
2811                dmsg(2,("no exact module match, trying MODULE_IGNORE_PATH\n"));
2812                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH);
2813            }
2814            if (!pEffectInfo) {
2815                dmsg(2,("no module match, trying MODULE_IGNORE_PATH | MODULE_IGNORE_CASE\n"));
2816                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH | EffectFactory::MODULE_IGNORE_CASE);
2817            }
2818            if (!pEffectInfo) {
2819                dmsg(2,("no module match, trying MODULE_IGNORE_PATH | MODULE_IGNORE_CASE | MODULE_IGNORE_EXTENSION\n"));
2820                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH | EffectFactory::MODULE_IGNORE_CASE | EffectFactory::MODULE_IGNORE_EXTENSION);
2821            }
2822            // ... if there was still no effect found, then completely ignore the
2823            // DLL plugin filename argument and just search for the matching effect
2824            // system type and effect name
2825            if (!pEffectInfo) {
2826                dmsg(2,("no module match, trying MODULE_IGNORE_ALL\n"));
2827                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_ALL);
2828            }
2829            if (!pEffectInfo)
2830                throw Exception("There is no such effect '" + effectSystem + "' '" + module + "' '" + effectName + "'");
2831    
2832            Effect* pEffect = EffectFactory::Create(pEffectInfo);
2833            result = LSCPResultSet(pEffect->ID());
2834            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_count, EffectFactory::EffectInstancesCount()));
2835        } catch (Exception e) {
2836            result.Error(e);
2837        }
2838        return result.Produce();
2839    }
2840    
2841    String LSCPServer::DestroyEffectInstance(int iEffectInstance) {
2842        dmsg(2,("LSCPServer: DestroyEffectInstance(%d)\n", iEffectInstance));
2843        LSCPResultSet result;
2844        try {
2845            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2846            if (!pEffect)
2847                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2848            EffectFactory::Destroy(pEffect);
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::GetEffectInstances() {
2857        dmsg(2,("LSCPServer: GetEffectInstances()\n"));
2858        LSCPResultSet result;
2859        try {
2860            int n = EffectFactory::EffectInstancesCount();
2861            result.Add(n);
2862        } catch (Exception e) {
2863            result.Error(e);
2864        }
2865        return result.Produce();
2866    }
2867    
2868    String LSCPServer::ListEffectInstances() {
2869        dmsg(2,("LSCPServer: ListEffectInstances()\n"));
2870        LSCPResultSet result;
2871        String list;
2872        try {
2873            int n = EffectFactory::EffectInstancesCount();
2874            for (int i = 0; i < n; i++) {
2875                Effect* pEffect = EffectFactory::GetEffectInstance(i);
2876                if (i) list += ",";
2877                list += ToString(pEffect->ID());
2878            }
2879        } catch (Exception e) {
2880            result.Error(e);
2881        }
2882        result.Add(list);
2883        return result.Produce();
2884    }
2885    
2886    String LSCPServer::GetSendEffectChains(int iAudioOutputDevice) {
2887        dmsg(2,("LSCPServer: GetSendEffectChains(%d)\n", iAudioOutputDevice));
2888        LSCPResultSet result;
2889        try {
2890            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2891            if (!devices.count(iAudioOutputDevice))
2892                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2893            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2894            int n = pDevice->SendEffectChainCount();
2895            result.Add(n);
2896        } catch (Exception e) {
2897            result.Error(e);
2898        }
2899        return result.Produce();
2900    }
2901    
2902    String LSCPServer::ListSendEffectChains(int iAudioOutputDevice) {
2903        dmsg(2,("LSCPServer: ListSendEffectChains(%d)\n", iAudioOutputDevice));
2904        LSCPResultSet result;
2905        String list;
2906        try {
2907            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2908            if (!devices.count(iAudioOutputDevice))
2909                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2910            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2911            int n = pDevice->SendEffectChainCount();
2912            for (int i = 0; i < n; i++) {
2913                EffectChain* pEffectChain = pDevice->SendEffectChain(i);
2914                if (i) list += ",";
2915                list += ToString(pEffectChain->ID());
2916            }
2917        } catch (Exception e) {
2918            result.Error(e);
2919        }
2920        result.Add(list);
2921        return result.Produce();
2922    }
2923    
2924    String LSCPServer::AddSendEffectChain(int iAudioOutputDevice) {
2925        dmsg(2,("LSCPServer: AddSendEffectChain(%d)\n", iAudioOutputDevice));
2926        LSCPResultSet result;
2927        try {
2928            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2929            if (!devices.count(iAudioOutputDevice))
2930                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2931            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2932            EffectChain* pEffectChain = pDevice->AddSendEffectChain();
2933            result = pEffectChain->ID();
2934            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_count, iAudioOutputDevice, pDevice->SendEffectChainCount()));
2935        } catch (Exception e) {
2936            result.Error(e);
2937        }
2938        return result.Produce();
2939    }
2940    
2941    String LSCPServer::RemoveSendEffectChain(int iAudioOutputDevice, int iSendEffectChain) {
2942        dmsg(2,("LSCPServer: RemoveSendEffectChain(%d,%d)\n", iAudioOutputDevice, iSendEffectChain));
2943        LSCPResultSet result;
2944        try {
2945            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2946            if (!devices.count(iAudioOutputDevice))
2947                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2948    
2949            std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
2950            std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();
2951            std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
2952            for (; itEngineChannel != itEnd; ++itEngineChannel) {
2953                AudioOutputDevice* pDev = (*itEngineChannel)->GetAudioOutputDevice();
2954                if (pDev != NULL && pDev->deviceId() == iAudioOutputDevice) {
2955                    for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
2956                        FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
2957                        if(fxs != NULL && fxs->DestinationEffectChain() == iSendEffectChain) {
2958                            throw Exception("The effect chain is still in use by channel " + ToString((*itEngineChannel)->GetSamplerChannel()->Index()));
2959                        }
2960                    }
2961                }
2962            }
2963    
2964            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2965            for (int i = 0; i < pDevice->SendEffectChainCount(); i++) {
2966                EffectChain* pEffectChain = pDevice->SendEffectChain(i);
2967                if (pEffectChain->ID() == iSendEffectChain) {
2968                    pDevice->RemoveSendEffectChain(i);
2969                    LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_count, iAudioOutputDevice, pDevice->SendEffectChainCount()));
2970                    return result.Produce();
2971                }
2972            }
2973            throw Exception(
2974                "There is no send effect chain with ID " +
2975                ToString(iSendEffectChain) + " for audio output device " +
2976                ToString(iAudioOutputDevice) + "."
2977            );
2978        } catch (Exception e) {
2979            result.Error(e);
2980        }
2981        return result.Produce();
2982    }
2983    
2984    static EffectChain* _getSendEffectChain(Sampler* pSampler, int iAudioOutputDevice, int iSendEffectChain) throw (Exception) {
2985        std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2986        if (!devices.count(iAudioOutputDevice))
2987            throw Exception(
2988                "There is no audio output device with index " +
2989                ToString(iAudioOutputDevice) + "."
2990            );
2991        AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2992        EffectChain* pEffectChain = pDevice->SendEffectChainByID(iSendEffectChain);
2993        if(pEffectChain != NULL) return pEffectChain;
2994        throw Exception(
2995            "There is no send effect chain with ID " +
2996            ToString(iSendEffectChain) + " for audio output device " +
2997            ToString(iAudioOutputDevice) + "."
2998        );
2999    }
3000    
3001    String LSCPServer::GetSendEffectChainInfo(int iAudioOutputDevice, int iSendEffectChain) {
3002        dmsg(2,("LSCPServer: GetSendEffectChainInfo(%d,%d)\n", iAudioOutputDevice, iSendEffectChain));
3003        LSCPResultSet result;
3004        try {
3005            EffectChain* pEffectChain =
3006                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
3007            String sEffectSequence;
3008            for (int i = 0; i < pEffectChain->EffectCount(); i++) {
3009                if (i) sEffectSequence += ",";
3010                sEffectSequence += ToString(pEffectChain->GetEffect(i)->ID());
3011            }
3012            result.Add("EFFECT_COUNT", pEffectChain->EffectCount());
3013            result.Add("EFFECT_SEQUENCE", sEffectSequence);
3014        } catch (Exception e) {
3015            result.Error(e);
3016        }
3017        return result.Produce();
3018    }
3019    
3020    String LSCPServer::AppendSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectInstance) {
3021        dmsg(2,("LSCPServer: AppendSendEffectChainEffect(%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectInstance));
3022        LSCPResultSet result;
3023        try {
3024            EffectChain* pEffectChain =
3025                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
3026            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
3027            if (!pEffect)
3028                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
3029            pEffectChain->AppendEffect(pEffect);
3030            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_info, iAudioOutputDevice, iSendEffectChain, pEffectChain->EffectCount()));
3031        } catch (Exception e) {
3032            result.Error(e);
3033        }
3034        return result.Produce();
3035    }
3036    
3037    String LSCPServer::InsertSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectChainPosition, int iEffectInstance) {
3038        dmsg(2,("LSCPServer: InsertSendEffectChainEffect(%d,%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectChainPosition, iEffectInstance));
3039        LSCPResultSet result;
3040        try {
3041            EffectChain* pEffectChain =
3042                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
3043            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
3044            if (!pEffect)
3045                throw Exception("There is no effect instance with index " + ToString(iEffectInstance));
3046            pEffectChain->InsertEffect(pEffect, iEffectChainPosition);
3047            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_info, iAudioOutputDevice, iSendEffectChain, pEffectChain->EffectCount()));
3048        } catch (Exception e) {
3049            result.Error(e);
3050        }
3051        return result.Produce();
3052    }
3053    
3054    String LSCPServer::RemoveSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectChainPosition) {
3055        dmsg(2,("LSCPServer: RemoveSendEffectChainEffect(%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectChainPosition));
3056        LSCPResultSet result;
3057        try {
3058            EffectChain* pEffectChain =
3059                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
3060    
3061            std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
3062            std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();
3063            std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
3064            for (; itEngineChannel != itEnd; ++itEngineChannel) {
3065                AudioOutputDevice* pDev = (*itEngineChannel)->GetAudioOutputDevice();
3066                if (pDev != NULL && pDev->deviceId() == iAudioOutputDevice) {
3067                    for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
3068                        FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
3069                        if(fxs != NULL && fxs->DestinationEffectChain() == iSendEffectChain && fxs->DestinationEffectChainPosition() == iEffectChainPosition) {
3070                            throw Exception("The effect instance is still in use by channel " + ToString((*itEngineChannel)->GetSamplerChannel()->Index()));
3071                        }
3072                    }
3073                }
3074            }
3075    
3076            pEffectChain->RemoveEffect(iEffectChainPosition);
3077            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_info, iAudioOutputDevice, iSendEffectChain, pEffectChain->EffectCount()));
3078        } catch (Exception e) {
3079            result.Error(e);
3080        }
3081        return result.Produce();
3082    }
3083    
3084  String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {  String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
3085      dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
3086      LSCPResultSet result;      LSCPResultSet result;
3087      try {      try {
3088          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
3089          if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");          if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
3090          Engine* pEngine = pEngineChannel->GetEngine();          Engine* pEngine = pEngineChannel->GetEngine();
3091          InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();          InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
# Line 2467  String LSCPServer::EditSamplerChannelIns Line 3100  String LSCPServer::EditSamplerChannelIns
3100      return result.Produce();      return result.Produce();
3101  }  }
3102    
3103    String LSCPServer::SendChannelMidiData(String MidiMsg, uint uiSamplerChannel, uint Arg1, uint Arg2) {
3104        dmsg(2,("LSCPServer: SendChannelMidiData(MidiMsg=%s,uiSamplerChannel=%d,Arg1=%d,Arg2=%d)\n", MidiMsg.c_str(), uiSamplerChannel, Arg1, Arg2));
3105        LSCPResultSet result;
3106        try {
3107            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
3108    
3109            if (Arg1 > 127 || Arg2 > 127) {
3110                throw Exception("Invalid MIDI message");
3111            }
3112    
3113            VirtualMidiDevice* pMidiDevice = NULL;
3114            std::vector<EventHandler::midi_listener_entry>::iterator iter = eventHandler.channelMidiListeners.begin();
3115            for (; iter != eventHandler.channelMidiListeners.end(); ++iter) {
3116                if ((*iter).pEngineChannel == pEngineChannel) {
3117                    pMidiDevice = (*iter).pMidiListener;
3118                    break;
3119                }
3120            }
3121            
3122            if(pMidiDevice == NULL) throw Exception("Couldn't find virtual MIDI device");
3123    
3124            if (MidiMsg == "NOTE_ON") {
3125                pMidiDevice->SendNoteOnToDevice(Arg1, Arg2);
3126                bool b = pMidiDevice->SendNoteOnToSampler(Arg1, Arg2);
3127                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
3128            } else if (MidiMsg == "NOTE_OFF") {
3129                pMidiDevice->SendNoteOffToDevice(Arg1, Arg2);
3130                bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2);
3131                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
3132            } else if (MidiMsg == "CC") {
3133                pMidiDevice->SendCCToDevice(Arg1, Arg2);
3134                bool b = pMidiDevice->SendCCToSampler(Arg1, Arg2);
3135                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
3136            } else {
3137                throw Exception("Unknown MIDI message type: " + MidiMsg);
3138            }
3139        } catch (Exception e) {
3140            result.Error(e);
3141        }
3142        return result.Produce();
3143    }
3144    
3145  /**  /**
3146   * Will be called by the parser to reset a particular sampler channel.   * Will be called by the parser to reset a particular sampler channel.
3147   */   */
# Line 2474  String LSCPServer::ResetChannel(uint uiS Line 3149  String LSCPServer::ResetChannel(uint uiS
3149      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));
3150      LSCPResultSet result;      LSCPResultSet result;
3151      try {      try {
3152          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");  
3153          pEngineChannel->Reset();          pEngineChannel->Reset();
3154      }      }
3155      catch (Exception e) {      catch (Exception e) {
# Line 2543  String LSCPServer::GetTotalVoiceCount() Line 3215  String LSCPServer::GetTotalVoiceCount()
3215  String LSCPServer::GetTotalVoiceCountMax() {  String LSCPServer::GetTotalVoiceCountMax() {
3216      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));
3217      LSCPResultSet result;      LSCPResultSet result;
3218      result.Add(EngineFactory::EngineInstances().size() * CONFIG_MAX_VOICES);      result.Add(EngineFactory::EngineInstances().size() * pSampler->GetGlobalMaxVoices());
3219        return result.Produce();
3220    }
3221    
3222    /**
3223     * Will be called by the parser to return the sampler global maximum
3224     * allowed number of voices.
3225     */
3226    String LSCPServer::GetGlobalMaxVoices() {
3227        dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n"));
3228        LSCPResultSet result;
3229        result.Add(pSampler->GetGlobalMaxVoices());
3230        return result.Produce();
3231    }
3232    
3233    /**
3234     * Will be called by the parser to set the sampler global maximum number of
3235     * voices.
3236     */
3237    String LSCPServer::SetGlobalMaxVoices(int iVoices) {
3238        dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices));
3239        LSCPResultSet result;
3240        try {
3241            pSampler->SetGlobalMaxVoices(iVoices);
3242            LSCPServer::SendLSCPNotify(
3243                LSCPEvent(LSCPEvent::event_global_info, "VOICES", pSampler->GetGlobalMaxVoices())
3244            );
3245        } catch (Exception e) {
3246            result.Error(e);
3247        }
3248        return result.Produce();
3249    }
3250    
3251    /**
3252     * Will be called by the parser to return the sampler global maximum
3253     * allowed number of disk streams.
3254     */
3255    String LSCPServer::GetGlobalMaxStreams() {
3256        dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n"));
3257        LSCPResultSet result;
3258        result.Add(pSampler->GetGlobalMaxStreams());
3259        return result.Produce();
3260    }
3261    
3262    /**
3263     * Will be called by the parser to set the sampler global maximum number of
3264     * disk streams.
3265     */
3266    String LSCPServer::SetGlobalMaxStreams(int iStreams) {
3267        dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams));
3268        LSCPResultSet result;
3269        try {
3270            pSampler->SetGlobalMaxStreams(iStreams);
3271            LSCPServer::SendLSCPNotify(
3272                LSCPEvent(LSCPEvent::event_global_info, "STREAMS", pSampler->GetGlobalMaxStreams())
3273            );
3274        } catch (Exception e) {
3275            result.Error(e);
3276        }
3277      return result.Produce();      return result.Produce();
3278  }  }
3279    
# Line 2684  String LSCPServer::GetFileInstrumentInfo Line 3414  String LSCPServer::GetFileInstrumentInfo
3414                  result.Add("FORMAT_VERSION", info.FormatVersion);                  result.Add("FORMAT_VERSION", info.FormatVersion);
3415                  result.Add("PRODUCT", info.Product);                  result.Add("PRODUCT", info.Product);
3416                  result.Add("ARTISTS", info.Artists);                  result.Add("ARTISTS", info.Artists);
3417    
3418                    std::stringstream ss;
3419                    bool b = false;
3420                    for (int i = 0; i < 128; i++) {
3421                        if (info.KeyBindings[i]) {
3422                            if (b) ss << ',';
3423                            ss << i; b = true;
3424                        }
3425                    }
3426                    result.Add("KEY_BINDINGS", ss.str());
3427    
3428                    b = false;
3429                    std::stringstream ss2;
3430                    for (int i = 0; i < 128; i++) {
3431                        if (info.KeySwitchBindings[i]) {
3432                            if (b) ss2 << ',';
3433                            ss2 << i; b = true;
3434                        }
3435                    }
3436                    result.Add("KEYSWITCH_BINDINGS", ss2.str());
3437                  // no more need to ask other engine types                  // no more need to ask other engine types
3438                  bFound = true;                  bFound = true;
3439              } 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 2711  void LSCPServer::VerifyFile(String Filen Line 3461  void LSCPServer::VerifyFile(String Filen
3461          throw Exception("Directory is specified");          throw Exception("Directory is specified");
3462      }      }
3463      #else      #else
3464      struct stat statBuf;      File f(Filename);
3465      int res = stat(Filename.c_str(), &statBuf);      if(!f.Exist()) throw Exception(f.GetErrorMsg());
3466      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");  
     }  
3467      #endif      #endif
3468  }  }
3469    
# Line 2732  void LSCPServer::VerifyFile(String Filen Line 3474  void LSCPServer::VerifyFile(String Filen
3474  String LSCPServer::SubscribeNotification(LSCPEvent::event_t type) {  String LSCPServer::SubscribeNotification(LSCPEvent::event_t type) {
3475      dmsg(2,("LSCPServer: SubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));      dmsg(2,("LSCPServer: SubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
3476      LSCPResultSet result;      LSCPResultSet result;
3477      SubscriptionMutex.Lock();      {
3478      eventSubscriptions[type].push_back(currentSocket);          LockGuard lock(SubscriptionMutex);
3479      SubscriptionMutex.Unlock();          eventSubscriptions[type].push_back(currentSocket);
3480        }
3481      return result.Produce();      return result.Produce();
3482  }  }
3483    
# Line 2745  String LSCPServer::SubscribeNotification Line 3488  String LSCPServer::SubscribeNotification
3488  String LSCPServer::UnsubscribeNotification(LSCPEvent::event_t type) {  String LSCPServer::UnsubscribeNotification(LSCPEvent::event_t type) {
3489      dmsg(2,("LSCPServer: UnsubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));      dmsg(2,("LSCPServer: UnsubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
3490      LSCPResultSet result;      LSCPResultSet result;
3491      SubscriptionMutex.Lock();      {
3492      eventSubscriptions[type].remove(currentSocket);          LockGuard lock(SubscriptionMutex);
3493      SubscriptionMutex.Unlock();          eventSubscriptions[type].remove(currentSocket);
3494        }
3495      return result.Produce();      return result.Produce();
3496  }  }
3497    
# Line 2916  String LSCPServer::AddDbInstruments(Stri Line 3660  String LSCPServer::AddDbInstruments(Stri
3660      return result.Produce();      return result.Produce();
3661  }  }
3662    
3663  String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {  String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground, bool insDir) {
3664      dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground));      dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d,insDir=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground, insDir));
3665      LSCPResultSet result;      LSCPResultSet result;
3666  #if HAVE_SQLITE3  #if HAVE_SQLITE3
3667      try {      try {
3668          int id;          int id;
3669          InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();          InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
3670          if (ScanMode.compare("RECURSIVE") == 0) {          if (ScanMode.compare("RECURSIVE") == 0) {
3671             id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);              id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground, insDir);
3672          } else if (ScanMode.compare("NON_RECURSIVE") == 0) {          } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
3673             id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);              id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground, insDir);
3674          } else if (ScanMode.compare("FLAT") == 0) {          } else if (ScanMode.compare("FLAT") == 0) {
3675             id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);              id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground, insDir);
3676          } else {          } else {
3677              throw Exception("Unknown scan mode: " + ScanMode);              throw Exception("Unknown scan mode: " + ScanMode);
3678          }          }
# Line 3272  String LSCPServer::SetEcho(yyparse_param Line 4016  String LSCPServer::SetEcho(yyparse_param
4016      }      }
4017      return result.Produce();      return result.Produce();
4018  }  }
4019    
4020    String LSCPServer::SetShellInteract(yyparse_param_t* pSession, double boolean_value) {
4021        dmsg(2,("LSCPServer: SetShellInteract(val=%f)\n", boolean_value));
4022        LSCPResultSet result;
4023        try {
4024            if      (boolean_value == 0) pSession->bShellInteract = false;
4025            else if (boolean_value == 1) pSession->bShellInteract = true;
4026            else throw Exception("Not a boolean value, must either be 0 or 1");
4027        } catch (Exception e) {
4028            result.Error(e);
4029        }
4030        return result.Produce();
4031    }
4032    
4033    String LSCPServer::SetShellAutoCorrect(yyparse_param_t* pSession, double boolean_value) {
4034        dmsg(2,("LSCPServer: SetShellAutoCorrect(val=%f)\n", boolean_value));
4035        LSCPResultSet result;
4036        try {
4037            if      (boolean_value == 0) pSession->bShellAutoCorrect = false;
4038            else if (boolean_value == 1) pSession->bShellAutoCorrect = true;
4039            else throw Exception("Not a boolean value, must either be 0 or 1");
4040        } catch (Exception e) {
4041            result.Error(e);
4042        }
4043        return result.Produce();
4044    }
4045    
4046    }

Legend:
Removed from v.1727  
changed lines
  Added in v.2528

  ViewVC Help
Powered by ViewVC