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

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

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

revision 1781 by iliev, Mon Sep 29 18:21:21 2008 UTC revision 2500 by schoenebeck, Fri Jan 10 12:20:05 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 24  Line 24 
24  #include <algorithm>  #include <algorithm>
25  #include <string>  #include <string>
26    
27    #include "../common/File.h"
28  #include "lscpserver.h"  #include "lscpserver.h"
29  #include "lscpresultset.h"  #include "lscpresultset.h"
30  #include "lscpevent.h"  #include "lscpevent.h"
# Line 42  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 {  namespace LinuxSampler {
49    
# Line 95  static String _escapeLscpResponse(String Line 97  static String _escapeLscpResponse(String
97   */   */
98  fd_set LSCPServer::fdSet;  fd_set LSCPServer::fdSet;
99  int LSCPServer::currentSocket = -1;  int LSCPServer::currentSocket = -1;
100  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();  std::vector<yyparse_param_t> LSCPServer::Sessions;
101  std::vector<yyparse_param_t>::iterator itCurrentSession = std::vector<yyparse_param_t>::iterator();  std::vector<yyparse_param_t>::iterator itCurrentSession;
102  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedNotifies;
103  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedCommands;
104  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;
105  Mutex LSCPServer::NotifyMutex = Mutex();  Mutex LSCPServer::NotifyMutex;
106  Mutex LSCPServer::NotifyBufferMutex = Mutex();  Mutex LSCPServer::NotifyBufferMutex;
107  Mutex LSCPServer::SubscriptionMutex = Mutex();  Mutex LSCPServer::SubscriptionMutex;
108  Mutex LSCPServer::RTNotifyMutex = Mutex();  Mutex LSCPServer::RTNotifyMutex;
109    
110  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) {
111      SocketAddress.sin_family      = AF_INET;      SocketAddress.sin_family      = AF_INET;
# Line 136  LSCPServer::LSCPServer(Sampler* pSampler Line 138  LSCPServer::LSCPServer(Sampler* pSampler
138      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
139      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");
140      LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI");      LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI");
141        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_instance_count, "EFFECT_INSTANCE_COUNT");
142        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_instance_info, "EFFECT_INSTANCE_INFO");
143        LSCPEvent::RegisterEvent(LSCPEvent::event_send_fx_chain_count, "SEND_EFFECT_CHAIN_COUNT");
144        LSCPEvent::RegisterEvent(LSCPEvent::event_send_fx_chain_info, "SEND_EFFECT_CHAIN_INFO");
145      hSocket = -1;      hSocket = -1;
146  }  }
147    
148  LSCPServer::~LSCPServer() {  LSCPServer::~LSCPServer() {
149        CloseAllConnections();
150        InstrumentManager::StopBackgroundThread();
151  #if defined(WIN32)  #if defined(WIN32)
152      if (hSocket >= 0) closesocket(hSocket);      if (hSocket >= 0) closesocket(hSocket);
153  #else  #else
# Line 334  void LSCPServer::DbInstrumentsEventHandl Line 342  void LSCPServer::DbInstrumentsEventHandl
342  }  }
343  #endif // HAVE_SQLITE3  #endif // HAVE_SQLITE3
344    
345    void LSCPServer::RemoveListeners() {
346        pSampler->RemoveChannelCountListener(&eventHandler);
347        pSampler->RemoveAudioDeviceCountListener(&eventHandler);
348        pSampler->RemoveMidiDeviceCountListener(&eventHandler);
349        pSampler->RemoveVoiceCountListener(&eventHandler);
350        pSampler->RemoveStreamCountListener(&eventHandler);
351        pSampler->RemoveBufferFillListener(&eventHandler);
352        pSampler->RemoveTotalStreamCountListener(&eventHandler);
353        pSampler->RemoveTotalVoiceCountListener(&eventHandler);
354        pSampler->RemoveFxSendCountListener(&eventHandler);
355        MidiInstrumentMapper::RemoveMidiInstrumentCountListener(&eventHandler);
356        MidiInstrumentMapper::RemoveMidiInstrumentInfoListener(&eventHandler);
357        MidiInstrumentMapper::RemoveMidiInstrumentMapCountListener(&eventHandler);
358        MidiInstrumentMapper::RemoveMidiInstrumentMapInfoListener(&eventHandler);
359    #if HAVE_SQLITE3
360        InstrumentsDb::GetInstrumentsDb()->RemoveInstrumentsDbListener(&dbInstrumentsEventHandler);
361    #endif
362    }
363    
364  /**  /**
365   * Blocks the calling thread until the LSCP Server is initialized and   * Blocks the calling thread until the LSCP Server is initialized and
# Line 421  int LSCPServer::Main() { Line 447  int LSCPServer::Main() {
447          #endif          #endif
448          // 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
449          {          {
450                LockGuard lock(EngineChannelFactory::EngineChannelsMutex);
451              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
452              std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();              std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();
453              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
# Line 489  int LSCPServer::Main() { Line 516  int LSCPServer::Main() {
516              }              }
517          }          }
518    
519          //Now let's deliver late notifies (if any)          //Now let's deliver late notifies (if any)
520          NotifyBufferMutex.Lock();          {
521          for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {              LockGuard lock(NotifyBufferMutex);
522                for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {
523  #ifdef MSG_NOSIGNAL  #ifdef MSG_NOSIGNAL
524                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), MSG_NOSIGNAL);                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), MSG_NOSIGNAL);
525  #else  #else
526                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0);                  send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0);
527  #endif  #endif
528          }              }
529          bufferedNotifies.clear();              bufferedNotifies.clear();
530          NotifyBufferMutex.Unlock();          }
531    
532          fd_set selectSet = fdSet;          fd_set selectSet = fdSet;
533          timeout.tv_sec  = 0;          timeout.tv_sec  = 0;
# Line 507  int LSCPServer::Main() { Line 535  int LSCPServer::Main() {
535    
536          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);
537    
538          if (retval == 0)          if (retval == 0 || (retval == -1 && errno == EINTR))
539                  continue; //Nothing try again                  continue; //Nothing try again
540          if (retval == -1) {          if (retval == -1) {
541                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
# Line 534  int LSCPServer::Main() { Line 562  int LSCPServer::Main() {
562                    exit(EXIT_FAILURE);                    exit(EXIT_FAILURE);
563                  }                  }
564          #else          #else
565                    struct linger linger;
566                    linger.l_onoff = 1;
567                    linger.l_linger = 0;
568                    if(setsockopt(socket, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger))) {
569                        std::cerr << "LSCPServer: Failed to set SO_LINGER\n";
570                    }
571    
572                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
573                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
574                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
# Line 589  void LSCPServer::CloseConnection( std::v Line 624  void LSCPServer::CloseConnection( std::v
624          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection terminated on socket", socket));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection terminated on socket", socket));
625          Sessions.erase(iter);          Sessions.erase(iter);
626          FD_CLR(socket,  &fdSet);          FD_CLR(socket,  &fdSet);
627          SubscriptionMutex.Lock(); //Must unsubscribe this socket from all events (if any)          {
628          for (std::map< LSCPEvent::event_t, std::list<int> >::iterator iter = eventSubscriptions.begin(); iter != eventSubscriptions.end(); iter++) {              LockGuard lock(SubscriptionMutex);
629                  iter->second.remove(socket);              // Must unsubscribe this socket from all events (if any)
630          }              for (std::map< LSCPEvent::event_t, std::list<int> >::iterator iter = eventSubscriptions.begin(); iter != eventSubscriptions.end(); iter++) {
631          SubscriptionMutex.Unlock();                  iter->second.remove(socket);
632          NotifyMutex.Lock();              }
633            }
634            LockGuard lock(NotifyMutex);
635          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
636          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
637          #if defined(WIN32)          #if defined(WIN32)
# Line 602  void LSCPServer::CloseConnection( std::v Line 639  void LSCPServer::CloseConnection( std::v
639          #else          #else
640          close(socket);          close(socket);
641          #endif          #endif
         NotifyMutex.Unlock();  
642  }  }
643    
644  void LSCPServer::LockRTNotify() {  void LSCPServer::CloseAllConnections() {
645      RTNotifyMutex.Lock();      std::vector<yyparse_param_t>::iterator iter = Sessions.begin();
646  }      while(iter != Sessions.end()) {
647            CloseConnection(iter);
648  void LSCPServer::UnlockRTNotify() {          iter = Sessions.begin();
649      RTNotifyMutex.Unlock();      }
650  }  }
651    
652  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
653          int subs = 0;          int subs = 0;
654          SubscriptionMutex.Lock();          LockGuard lock(SubscriptionMutex);
655          for( std::list<LSCPEvent::event_t>::iterator iter = events.begin();          for( std::list<LSCPEvent::event_t>::iterator iter = events.begin();
656                          iter != events.end(); iter++)                          iter != events.end(); iter++)
657          {          {
658                  subs += eventSubscriptions.count(*iter);                  subs += eventSubscriptions.count(*iter);
659          }          }
         SubscriptionMutex.Unlock();  
660          return subs;          return subs;
661  }  }
662    
663  void LSCPServer::SendLSCPNotify( LSCPEvent event ) {  void LSCPServer::SendLSCPNotify( LSCPEvent event ) {
664          SubscriptionMutex.Lock();          LockGuard lock(SubscriptionMutex);
665          if (eventSubscriptions.count(event.GetType()) == 0) {          if (eventSubscriptions.count(event.GetType()) == 0) {
666                  SubscriptionMutex.Unlock();     //Nobody is subscribed to this event                  // Nobody is subscribed to this event
667                  return;                  return;
668          }          }
669          std::list<int>::iterator iter = eventSubscriptions[event.GetType()].begin();          std::list<int>::iterator iter = eventSubscriptions[event.GetType()].begin();
# Line 654  void LSCPServer::SendLSCPNotify( LSCPEve Line 689  void LSCPServer::SendLSCPNotify( LSCPEve
689                          }                          }
690                  }                  }
691          }          }
         SubscriptionMutex.Unlock();  
692  }  }
693    
694  extern int GetLSCPCommand( void *buf, int max_size ) {  extern int GetLSCPCommand( void *buf, int max_size ) {
# Line 769  bool LSCPServer::GetLSCPCommand( std::ve Line 803  bool LSCPServer::GetLSCPCommand( std::ve
803  void LSCPServer::AnswerClient(String ReturnMessage) {  void LSCPServer::AnswerClient(String ReturnMessage) {
804      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str()));      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str()));
805      if (currentSocket != -1) {      if (currentSocket != -1) {
806              NotifyMutex.Lock();              LockGuard lock(NotifyMutex);
807  #ifdef MSG_NOSIGNAL  #ifdef MSG_NOSIGNAL
808              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), MSG_NOSIGNAL);              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), MSG_NOSIGNAL);
809  #else  #else
810              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);
811  #endif  #endif
             NotifyMutex.Unlock();  
812      }      }
813  }  }
814    
# Line 925  String LSCPServer::SetEngineType(String Line 958  String LSCPServer::SetEngineType(String
958      try {      try {
959          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
960          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
961          LockRTNotify();          LockGuard lock(RTNotifyMutex);
962          pSamplerChannel->SetEngineType(EngineName);          pSamplerChannel->SetEngineType(EngineName);
963          if(HasSoloChannel()) pSamplerChannel->GetEngineChannel()->SetMute(-1);          if(HasSoloChannel()) pSamplerChannel->GetEngineChannel()->SetMute(-1);
         UnlockRTNotify();  
964      }      }
965      catch (Exception e) {      catch (Exception e) {
966           result.Error(e);           result.Error(e);
# Line 968  String LSCPServer::ListChannels() { Line 1000  String LSCPServer::ListChannels() {
1000   */   */
1001  String LSCPServer::AddChannel() {  String LSCPServer::AddChannel() {
1002      dmsg(2,("LSCPServer: AddChannel()\n"));      dmsg(2,("LSCPServer: AddChannel()\n"));
1003      LockRTNotify();      SamplerChannel* pSamplerChannel;
1004      SamplerChannel* pSamplerChannel = pSampler->AddSamplerChannel();      {
1005      UnlockRTNotify();          LockGuard lock(RTNotifyMutex);
1006            pSamplerChannel = pSampler->AddSamplerChannel();
1007        }
1008      LSCPResultSet result(pSamplerChannel->Index());      LSCPResultSet result(pSamplerChannel->Index());
1009      return result.Produce();      return result.Produce();
1010  }  }
# Line 981  String LSCPServer::AddChannel() { Line 1015  String LSCPServer::AddChannel() {
1015  String LSCPServer::RemoveChannel(uint uiSamplerChannel) {  String LSCPServer::RemoveChannel(uint uiSamplerChannel) {
1016      dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel));
1017      LSCPResultSet result;      LSCPResultSet result;
1018      LockRTNotify();      {
1019      pSampler->RemoveSamplerChannel(uiSamplerChannel);          LockGuard lock(RTNotifyMutex);
1020      UnlockRTNotify();          pSampler->RemoveSamplerChannel(uiSamplerChannel);
1021        }
1022      return result.Produce();      return result.Produce();
1023  }  }
1024    
# Line 1026  String LSCPServer::ListAvailableEngines( Line 1061  String LSCPServer::ListAvailableEngines(
1061  String LSCPServer::GetEngineInfo(String EngineName) {  String LSCPServer::GetEngineInfo(String EngineName) {
1062      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));
1063      LSCPResultSet result;      LSCPResultSet result;
1064      LockRTNotify();      {
1065      try {          LockGuard lock(RTNotifyMutex);
1066          Engine* pEngine = EngineFactory::Create(EngineName);          try {
1067          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));              Engine* pEngine = EngineFactory::Create(EngineName);
1068          result.Add("VERSION",     pEngine->Version());              result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
1069          EngineFactory::Destroy(pEngine);              result.Add("VERSION",     pEngine->Version());
1070      }              EngineFactory::Destroy(pEngine);
1071      catch (Exception e) {          }
1072           result.Error(e);          catch (Exception e) {
1073                result.Error(e);
1074            }
1075      }      }
     UnlockRTNotify();  
1076      return result.Produce();      return result.Produce();
1077  }  }
1078    
# Line 1259  String LSCPServer::GetMidiInputDriverInf Line 1295  String LSCPServer::GetMidiInputDriverInf
1295              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1296                  if (s != "") s += ",";                  if (s != "") s += ",";
1297                  s += iter->first;                  s += iter->first;
1298                    delete iter->second;
1299              }              }
1300              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1301          }          }
# Line 1283  String LSCPServer::GetAudioOutputDriverI Line 1320  String LSCPServer::GetAudioOutputDriverI
1320              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1321                  if (s != "") s += ",";                  if (s != "") s += ",";
1322                  s += iter->first;                  s += iter->first;
1323                    delete iter->second;
1324              }              }
1325              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1326          }          }
# Line 1313  String LSCPServer::GetMidiInputDriverPar Line 1351  String LSCPServer::GetMidiInputDriverPar
1351          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1352          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1353          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1354            delete pParameter;
1355      }      }
1356      catch (Exception e) {      catch (Exception e) {
1357          result.Error(e);          result.Error(e);
# Line 1340  String LSCPServer::GetAudioOutputDriverP Line 1379  String LSCPServer::GetAudioOutputDriverP
1379          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1380          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1381          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1382            delete pParameter;
1383      }      }
1384      catch (Exception e) {      catch (Exception e) {
1385          result.Error(e);          result.Error(e);
# Line 1681  String LSCPServer::SetAudioOutputChannel Line 1721  String LSCPServer::SetAudioOutputChannel
1721  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {
1722      dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));      dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));
1723      LSCPResultSet result;      LSCPResultSet result;
1724      LockRTNotify();      {
1725            LockGuard lock(RTNotifyMutex);
1726            try {
1727                SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1728                if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1729                std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1730                if (!devices.count(AudioDeviceId)) throw Exception("There is no audio output device with index " + ToString(AudioDeviceId));
1731                AudioOutputDevice* pDevice = devices[AudioDeviceId];
1732                pSamplerChannel->SetAudioOutputDevice(pDevice);
1733            }
1734            catch (Exception e) {
1735                result.Error(e);
1736            }
1737        }
1738        return result.Produce();
1739    }
1740    
1741    String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {
1742        dmsg(2,("LSCPServer: SetAudioOutputType(String AudioOutputDriver=%s, SamplerChannel=%d)\n",AudioOutputDriver.c_str(),uiSamplerChannel));
1743        LSCPResultSet result;
1744        {
1745            LockGuard lock(RTNotifyMutex);
1746            try {
1747                SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1748                if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1749                // Driver type name aliasing...
1750                if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA";
1751                if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK";
1752                // Check if there's one audio output device already created
1753                // for the intended audio driver type (AudioOutputDriver)...
1754                AudioOutputDevice *pDevice = NULL;
1755                std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1756                std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();
1757                for (; iter != devices.end(); iter++) {
1758                    if ((iter->second)->Driver() == AudioOutputDriver) {
1759                        pDevice = iter->second;
1760                        break;
1761                    }
1762                }
1763                // If it doesn't exist, create a new one with default parameters...
1764                if (pDevice == NULL) {
1765                    std::map<String,String> params;
1766                    pDevice = pSampler->CreateAudioOutputDevice(AudioOutputDriver, params);
1767                }
1768                // Must have a device...
1769                if (pDevice == NULL)
1770                    throw Exception("Internal error: could not create audio output device.");
1771                // Set it as the current channel device...
1772                pSamplerChannel->SetAudioOutputDevice(pDevice);
1773            }
1774            catch (Exception e) {
1775                result.Error(e);
1776            }
1777        }
1778        return result.Produce();
1779    }
1780    
1781    String LSCPServer::AddChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId, uint MIDIPort) {
1782        dmsg(2,("LSCPServer: AddChannelMidiInput(uiSamplerChannel=%d, MIDIDeviceId=%d, MIDIPort=%d)\n",uiSamplerChannel,MIDIDeviceId,MIDIPort));
1783        LSCPResultSet result;
1784      try {      try {
1785          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1786          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1787          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();  
1788          if (!devices.count(AudioDeviceId)) throw Exception("There is no audio output device with index " + ToString(AudioDeviceId));          std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1789          AudioOutputDevice* pDevice = devices[AudioDeviceId];          if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1790          pSamplerChannel->SetAudioOutputDevice(pDevice);          MidiInputDevice* pDevice = devices[MIDIDeviceId];
1791    
1792            MidiInputPort* pPort = pDevice->GetPort(MIDIPort);
1793            if (!pPort) throw Exception("There is no MIDI input port with index " + ToString(MIDIPort) + " on MIDI input device with index " + ToString(MIDIDeviceId));
1794    
1795            pSamplerChannel->Connect(pPort);
1796        } catch (Exception e) {
1797            result.Error(e);
1798      }      }
1799      catch (Exception e) {      return result.Produce();
1800           result.Error(e);  }
1801    
1802    String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel) {
1803        dmsg(2,("LSCPServer: RemoveChannelMidiInput(uiSamplerChannel=%d)\n",uiSamplerChannel));
1804        LSCPResultSet result;
1805        try {
1806            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1807            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1808            pSamplerChannel->DisconnectAllMidiInputPorts();
1809        } catch (Exception e) {
1810            result.Error(e);
1811      }      }
     UnlockRTNotify();  
1812      return result.Produce();      return result.Produce();
1813  }  }
1814    
1815  String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {  String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId) {
1816      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));
1817      LSCPResultSet result;      LSCPResultSet result;
     LockRTNotify();  
1818      try {      try {
1819          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1820          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1821          // Driver type name aliasing...  
1822          if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA";          std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1823          if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK";          if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1824          // Check if there's one audio output device already created          MidiInputDevice* pDevice = devices[MIDIDeviceId];
1825          // for the intended audio driver type (AudioOutputDriver)...          
1826          AudioOutputDevice *pDevice = NULL;          std::vector<MidiInputPort*> vPorts = pSamplerChannel->GetMidiInputPorts();
1827          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          for (int i = 0; i < vPorts.size(); ++i)
1828          std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();              if (vPorts[i]->GetDevice() == pDevice)
1829          for (; iter != devices.end(); iter++) {                  pSamplerChannel->Disconnect(vPorts[i]);
1830              if ((iter->second)->Driver() == AudioOutputDriver) {  
1831                  pDevice = iter->second;      } catch (Exception e) {
1832                  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);  
1833      }      }
1834      catch (Exception e) {      return result.Produce();
1835           result.Error(e);  }
1836    
1837    String LSCPServer::RemoveChannelMidiInput(uint uiSamplerChannel, uint MIDIDeviceId, uint MIDIPort) {
1838        dmsg(2,("LSCPServer: RemoveChannelMidiInput(uiSamplerChannel=%d, MIDIDeviceId=%d, MIDIPort=%d)\n",uiSamplerChannel,MIDIDeviceId,MIDIPort));
1839        LSCPResultSet result;
1840        try {
1841            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1842            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1843    
1844            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1845            if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1846            MidiInputDevice* pDevice = devices[MIDIDeviceId];
1847    
1848            MidiInputPort* pPort = pDevice->GetPort(MIDIPort);
1849            if (!pPort) throw Exception("There is no MIDI input port with index " + ToString(MIDIPort) + " on MIDI input device with index " + ToString(MIDIDeviceId));
1850    
1851            pSamplerChannel->Disconnect(pPort);
1852        } catch (Exception e) {
1853            result.Error(e);
1854        }
1855        return result.Produce();
1856    }
1857    
1858    String LSCPServer::ListChannelMidiInputs(uint uiSamplerChannel) {
1859        dmsg(2,("LSCPServer: ListChannelMidiInputs(uiSamplerChannel=%d)\n",uiSamplerChannel));
1860        LSCPResultSet result;
1861        try {
1862            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1863            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1864            std::vector<MidiInputPort*> vPorts = pSamplerChannel->GetMidiInputPorts();
1865    
1866            String s;
1867            for (int i = 0; i < vPorts.size(); ++i) {
1868                const int iDeviceID = vPorts[i]->GetDevice()->MidiInputDeviceID();
1869                const int iPortNr   = vPorts[i]->GetPortNumber();
1870                if (s.size()) s += ",";
1871                s += "{" + ToString(iDeviceID) + ","
1872                         + ToString(iPortNr) + "}";
1873            }
1874            result.Add(s);
1875        } catch (Exception e) {
1876            result.Error(e);
1877      }      }
     UnlockRTNotify();  
1878      return result.Produce();      return result.Produce();
1879  }  }
1880    
# Line 1806  String LSCPServer::SetMIDIInputType(Stri Line 1948  String LSCPServer::SetMIDIInputType(Stri
1948              pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);              pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);
1949              // Make it with at least one initial port.              // Make it with at least one initial port.
1950              std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();              std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
             parameters["PORTS"]->SetValue("1");  
1951          }          }
1952          // Must have a device...          // Must have a device...
1953          if (pDevice == NULL)          if (pDevice == NULL)
# Line 2343  String LSCPServer::GetFxSendInfo(uint ui Line 2484  String LSCPServer::GetFxSendInfo(uint ui
2484              AudioRouting += ToString(pFxSend->DestinationChannel(chan));              AudioRouting += ToString(pFxSend->DestinationChannel(chan));
2485          }          }
2486    
2487            const String sEffectRouting =
2488                (pFxSend->DestinationEffectChain() >= 0 && pFxSend->DestinationEffectChainPosition() >= 0)
2489                    ? ToString(pFxSend->DestinationEffectChain()) + "," + ToString(pFxSend->DestinationEffectChainPosition())
2490                    : "NONE";
2491    
2492          // success          // success
2493          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2494          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2495          result.Add("LEVEL", ToString(pFxSend->Level()));          result.Add("LEVEL", ToString(pFxSend->Level()));
2496          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
2497            result.Add("EFFECT", sEffectRouting);
2498      } catch (Exception e) {      } catch (Exception e) {
2499          result.Error(e);          result.Error(e);
2500      }      }
# Line 2410  String LSCPServer::SetFxSendLevel(uint u Line 2557  String LSCPServer::SetFxSendLevel(uint u
2557      return result.Produce();      return result.Produce();
2558  }  }
2559    
2560    String LSCPServer::SetFxSendEffect(uint uiSamplerChannel, uint FxSendID, int iSendEffectChain, int iEffectChainPosition) {
2561        dmsg(2,("LSCPServer: SetFxSendEffect(%d,%d)\n", iSendEffectChain, iEffectChainPosition));
2562        LSCPResultSet result;
2563        try {
2564            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2565    
2566            pFxSend->SetDestinationEffect(iSendEffectChain, iEffectChainPosition);
2567            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2568        } catch (Exception e) {
2569            result.Error(e);
2570        }
2571        return result.Produce();
2572    }
2573    
2574    String LSCPServer::GetAvailableEffects() {
2575        dmsg(2,("LSCPServer: GetAvailableEffects()\n"));
2576        LSCPResultSet result;
2577        try {
2578            int n = EffectFactory::AvailableEffectsCount();
2579            result.Add(n);
2580        }
2581        catch (Exception e) {
2582            result.Error(e);
2583        }
2584        return result.Produce();
2585    }
2586    
2587    String LSCPServer::ListAvailableEffects() {
2588        dmsg(2,("LSCPServer: ListAvailableEffects()\n"));
2589        LSCPResultSet result;
2590        String list;
2591        try {
2592            //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
2593            int n = EffectFactory::AvailableEffectsCount();
2594            for (int i = 0; i < n; i++) {
2595                if (i) list += ",";
2596                list += ToString(i);
2597            }
2598        }
2599        catch (Exception e) {
2600            result.Error(e);
2601        }
2602        result.Add(list);
2603        return result.Produce();
2604    }
2605    
2606    String LSCPServer::GetEffectInfo(int iEffectIndex) {
2607        dmsg(2,("LSCPServer: GetEffectInfo(%d)\n", iEffectIndex));
2608        LSCPResultSet result;
2609        try {
2610            EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(iEffectIndex);
2611            if (!pEffectInfo)
2612                throw Exception("There is no effect with index " + ToString(iEffectIndex));
2613    
2614            // convert the filename into the correct encoding as defined for LSCP
2615            // (especially in terms of special characters -> escape sequences)
2616    #if WIN32
2617            const String dllFileName = Path::fromWindows(pEffectInfo->Module()).toLscp();
2618    #else
2619            // assuming POSIX
2620            const String dllFileName = Path::fromPosix(pEffectInfo->Module()).toLscp();
2621    #endif
2622    
2623            result.Add("SYSTEM", pEffectInfo->EffectSystem());
2624            result.Add("MODULE", dllFileName);
2625            result.Add("NAME", _escapeLscpResponse(pEffectInfo->Name()));
2626            result.Add("DESCRIPTION", _escapeLscpResponse(pEffectInfo->Description()));
2627        }
2628        catch (Exception e) {
2629            result.Error(e);
2630        }
2631        return result.Produce();    
2632    }
2633    
2634    String LSCPServer::GetEffectInstanceInfo(int iEffectInstance) {
2635        dmsg(2,("LSCPServer: GetEffectInstanceInfo(%d)\n", iEffectInstance));
2636        LSCPResultSet result;
2637        try {
2638            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2639            if (!pEffect)
2640                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2641    
2642            EffectInfo* pEffectInfo = pEffect->GetEffectInfo();
2643    
2644            // convert the filename into the correct encoding as defined for LSCP
2645            // (especially in terms of special characters -> escape sequences)
2646    #if WIN32
2647            const String dllFileName = Path::fromWindows(pEffectInfo->Module()).toLscp();
2648    #else
2649            // assuming POSIX
2650            const String dllFileName = Path::fromPosix(pEffectInfo->Module()).toLscp();
2651    #endif
2652    
2653            result.Add("SYSTEM", pEffectInfo->EffectSystem());
2654            result.Add("MODULE", dllFileName);
2655            result.Add("NAME", _escapeLscpResponse(pEffectInfo->Name()));
2656            result.Add("DESCRIPTION", _escapeLscpResponse(pEffectInfo->Description()));
2657            result.Add("INPUT_CONTROLS", ToString(pEffect->InputControlCount()));
2658        }
2659        catch (Exception e) {
2660            result.Error(e);
2661        }
2662        return result.Produce();
2663    }
2664    
2665    String LSCPServer::GetEffectInstanceInputControlInfo(int iEffectInstance, int iInputControlIndex) {
2666        dmsg(2,("LSCPServer: GetEffectInstanceInputControlInfo(%d,%d)\n", iEffectInstance, iInputControlIndex));
2667        LSCPResultSet result;
2668        try {
2669            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2670            if (!pEffect)
2671                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2672    
2673            EffectControl* pEffectControl = pEffect->InputControl(iInputControlIndex);
2674            if (!pEffectControl)
2675                throw Exception(
2676                    "Effect instance " + ToString(iEffectInstance) +
2677                    " does not have an input control with index " +
2678                    ToString(iInputControlIndex)
2679                );
2680    
2681            result.Add("DESCRIPTION", _escapeLscpResponse(pEffectControl->Description()));
2682            result.Add("VALUE", pEffectControl->Value());
2683            if (pEffectControl->MinValue())
2684                 result.Add("RANGE_MIN", *pEffectControl->MinValue());
2685            if (pEffectControl->MaxValue())
2686                 result.Add("RANGE_MAX", *pEffectControl->MaxValue());
2687            if (!pEffectControl->Possibilities().empty())
2688                 result.Add("POSSIBILITIES", pEffectControl->Possibilities());
2689            if (pEffectControl->DefaultValue())
2690                 result.Add("DEFAULT", *pEffectControl->DefaultValue());
2691        } catch (Exception e) {
2692            result.Error(e);
2693        }
2694        return result.Produce();
2695    }
2696    
2697    String LSCPServer::SetEffectInstanceInputControlValue(int iEffectInstance, int iInputControlIndex, double dValue) {
2698        dmsg(2,("LSCPServer: SetEffectInstanceInputControlValue(%d,%d,%f)\n", iEffectInstance, iInputControlIndex, dValue));
2699        LSCPResultSet result;
2700        try {
2701            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2702            if (!pEffect)
2703                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2704    
2705            EffectControl* pEffectControl = pEffect->InputControl(iInputControlIndex);
2706            if (!pEffectControl)
2707                throw Exception(
2708                    "Effect instance " + ToString(iEffectInstance) +
2709                    " does not have an input control with index " +
2710                    ToString(iInputControlIndex)
2711                );
2712    
2713            pEffectControl->SetValue(dValue);
2714            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_info, iEffectInstance));
2715        } catch (Exception e) {
2716            result.Error(e);
2717        }
2718        return result.Produce();
2719    }
2720    
2721    String LSCPServer::CreateEffectInstance(int iEffectIndex) {
2722        dmsg(2,("LSCPServer: CreateEffectInstance(%d)\n", iEffectIndex));
2723        LSCPResultSet result;
2724        try {
2725            EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(iEffectIndex);
2726            if (!pEffectInfo)
2727                throw Exception("There is no effect with index " + ToString(iEffectIndex));
2728            Effect* pEffect = EffectFactory::Create(pEffectInfo);
2729            result = pEffect->ID(); // success
2730            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_count, EffectFactory::EffectInstancesCount()));
2731        } catch (Exception e) {
2732            result.Error(e);
2733        }
2734        return result.Produce();
2735    }
2736    
2737    String LSCPServer::CreateEffectInstance(String effectSystem, String module, String effectName) {
2738        dmsg(2,("LSCPServer: CreateEffectInstance('%s','%s','%s')\n", effectSystem.c_str(), module.c_str(), effectName.c_str()));
2739        LSCPResultSet result;
2740        try {
2741            // to allow loading the same LSCP session file on different systems
2742            // successfully, probably with different effect plugin DLL paths or even
2743            // running completely different operating systems, we do the following
2744            // for finding the right effect:
2745            //
2746            // first try to search for an exact match of the effect plugin DLL
2747            // (a.k.a 'module'), to avoid picking the wrong DLL with the same
2748            // effect name ...
2749            EffectInfo* pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_MATCH_EXACTLY);
2750            // ... if no effect with exactly matchin DLL filename was found, then
2751            // try to lower the restrictions of matching the effect plugin DLL
2752            // filename and try again and again ...
2753            if (!pEffectInfo) {
2754                dmsg(2,("no exact module match, trying MODULE_IGNORE_PATH\n"));
2755                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH);
2756            }
2757            if (!pEffectInfo) {
2758                dmsg(2,("no module match, trying MODULE_IGNORE_PATH | MODULE_IGNORE_CASE\n"));
2759                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH | EffectFactory::MODULE_IGNORE_CASE);
2760            }
2761            if (!pEffectInfo) {
2762                dmsg(2,("no module match, trying MODULE_IGNORE_PATH | MODULE_IGNORE_CASE | MODULE_IGNORE_EXTENSION\n"));
2763                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_PATH | EffectFactory::MODULE_IGNORE_CASE | EffectFactory::MODULE_IGNORE_EXTENSION);
2764            }
2765            // ... if there was still no effect found, then completely ignore the
2766            // DLL plugin filename argument and just search for the matching effect
2767            // system type and effect name
2768            if (!pEffectInfo) {
2769                dmsg(2,("no module match, trying MODULE_IGNORE_ALL\n"));
2770                pEffectInfo = EffectFactory::GetEffectInfo(effectSystem, module, effectName, EffectFactory::MODULE_IGNORE_ALL);
2771            }
2772            if (!pEffectInfo)
2773                throw Exception("There is no such effect '" + effectSystem + "' '" + module + "' '" + effectName + "'");
2774    
2775            Effect* pEffect = EffectFactory::Create(pEffectInfo);
2776            result = LSCPResultSet(pEffect->ID());
2777            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_count, EffectFactory::EffectInstancesCount()));
2778        } catch (Exception e) {
2779            result.Error(e);
2780        }
2781        return result.Produce();
2782    }
2783    
2784    String LSCPServer::DestroyEffectInstance(int iEffectInstance) {
2785        dmsg(2,("LSCPServer: DestroyEffectInstance(%d)\n", iEffectInstance));
2786        LSCPResultSet result;
2787        try {
2788            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2789            if (!pEffect)
2790                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2791            EffectFactory::Destroy(pEffect);
2792            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_instance_count, EffectFactory::EffectInstancesCount()));
2793        } catch (Exception e) {
2794            result.Error(e);
2795        }
2796        return result.Produce();
2797    }
2798    
2799    String LSCPServer::GetEffectInstances() {
2800        dmsg(2,("LSCPServer: GetEffectInstances()\n"));
2801        LSCPResultSet result;
2802        try {
2803            int n = EffectFactory::EffectInstancesCount();
2804            result.Add(n);
2805        } catch (Exception e) {
2806            result.Error(e);
2807        }
2808        return result.Produce();
2809    }
2810    
2811    String LSCPServer::ListEffectInstances() {
2812        dmsg(2,("LSCPServer: ListEffectInstances()\n"));
2813        LSCPResultSet result;
2814        String list;
2815        try {
2816            int n = EffectFactory::EffectInstancesCount();
2817            for (int i = 0; i < n; i++) {
2818                Effect* pEffect = EffectFactory::GetEffectInstance(i);
2819                if (i) list += ",";
2820                list += ToString(pEffect->ID());
2821            }
2822        } catch (Exception e) {
2823            result.Error(e);
2824        }
2825        result.Add(list);
2826        return result.Produce();
2827    }
2828    
2829    String LSCPServer::GetSendEffectChains(int iAudioOutputDevice) {
2830        dmsg(2,("LSCPServer: GetSendEffectChains(%d)\n", iAudioOutputDevice));
2831        LSCPResultSet result;
2832        try {
2833            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2834            if (!devices.count(iAudioOutputDevice))
2835                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2836            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2837            int n = pDevice->SendEffectChainCount();
2838            result.Add(n);
2839        } catch (Exception e) {
2840            result.Error(e);
2841        }
2842        return result.Produce();
2843    }
2844    
2845    String LSCPServer::ListSendEffectChains(int iAudioOutputDevice) {
2846        dmsg(2,("LSCPServer: ListSendEffectChains(%d)\n", iAudioOutputDevice));
2847        LSCPResultSet result;
2848        String list;
2849        try {
2850            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2851            if (!devices.count(iAudioOutputDevice))
2852                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2853            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2854            int n = pDevice->SendEffectChainCount();
2855            for (int i = 0; i < n; i++) {
2856                EffectChain* pEffectChain = pDevice->SendEffectChain(i);
2857                if (i) list += ",";
2858                list += ToString(pEffectChain->ID());
2859            }
2860        } catch (Exception e) {
2861            result.Error(e);
2862        }
2863        result.Add(list);
2864        return result.Produce();
2865    }
2866    
2867    String LSCPServer::AddSendEffectChain(int iAudioOutputDevice) {
2868        dmsg(2,("LSCPServer: AddSendEffectChain(%d)\n", iAudioOutputDevice));
2869        LSCPResultSet result;
2870        try {
2871            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2872            if (!devices.count(iAudioOutputDevice))
2873                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2874            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2875            EffectChain* pEffectChain = pDevice->AddSendEffectChain();
2876            result = pEffectChain->ID();
2877            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_count, iAudioOutputDevice, pDevice->SendEffectChainCount()));
2878        } catch (Exception e) {
2879            result.Error(e);
2880        }
2881        return result.Produce();
2882    }
2883    
2884    String LSCPServer::RemoveSendEffectChain(int iAudioOutputDevice, int iSendEffectChain) {
2885        dmsg(2,("LSCPServer: RemoveSendEffectChain(%d,%d)\n", iAudioOutputDevice, iSendEffectChain));
2886        LSCPResultSet result;
2887        try {
2888            std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2889            if (!devices.count(iAudioOutputDevice))
2890                throw Exception("There is no audio output device with index " + ToString(iAudioOutputDevice) + ".");
2891    
2892            std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
2893            std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();
2894            std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
2895            for (; itEngineChannel != itEnd; ++itEngineChannel) {
2896                AudioOutputDevice* pDev = (*itEngineChannel)->GetAudioOutputDevice();
2897                if (pDev != NULL && pDev->deviceId() == iAudioOutputDevice) {
2898                    for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
2899                        FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
2900                        if(fxs != NULL && fxs->DestinationEffectChain() == iSendEffectChain) {
2901                            throw Exception("The effect chain is still in use by channel " + ToString((*itEngineChannel)->GetSamplerChannel()->Index()));
2902                        }
2903                    }
2904                }
2905            }
2906    
2907            AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2908            for (int i = 0; i < pDevice->SendEffectChainCount(); i++) {
2909                EffectChain* pEffectChain = pDevice->SendEffectChain(i);
2910                if (pEffectChain->ID() == iSendEffectChain) {
2911                    pDevice->RemoveSendEffectChain(i);
2912                    LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_count, iAudioOutputDevice, pDevice->SendEffectChainCount()));
2913                    return result.Produce();
2914                }
2915            }
2916            throw Exception(
2917                "There is no send effect chain with ID " +
2918                ToString(iSendEffectChain) + " for audio output device " +
2919                ToString(iAudioOutputDevice) + "."
2920            );
2921        } catch (Exception e) {
2922            result.Error(e);
2923        }
2924        return result.Produce();
2925    }
2926    
2927    static EffectChain* _getSendEffectChain(Sampler* pSampler, int iAudioOutputDevice, int iSendEffectChain) throw (Exception) {
2928        std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
2929        if (!devices.count(iAudioOutputDevice))
2930            throw Exception(
2931                "There is no audio output device with index " +
2932                ToString(iAudioOutputDevice) + "."
2933            );
2934        AudioOutputDevice* pDevice = devices[iAudioOutputDevice];
2935        EffectChain* pEffectChain = pDevice->SendEffectChainByID(iSendEffectChain);
2936        if(pEffectChain != NULL) return pEffectChain;
2937        throw Exception(
2938            "There is no send effect chain with ID " +
2939            ToString(iSendEffectChain) + " for audio output device " +
2940            ToString(iAudioOutputDevice) + "."
2941        );
2942    }
2943    
2944    String LSCPServer::GetSendEffectChainInfo(int iAudioOutputDevice, int iSendEffectChain) {
2945        dmsg(2,("LSCPServer: GetSendEffectChainInfo(%d,%d)\n", iAudioOutputDevice, iSendEffectChain));
2946        LSCPResultSet result;
2947        try {
2948            EffectChain* pEffectChain =
2949                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
2950            String sEffectSequence;
2951            for (int i = 0; i < pEffectChain->EffectCount(); i++) {
2952                if (i) sEffectSequence += ",";
2953                sEffectSequence += ToString(pEffectChain->GetEffect(i)->ID());
2954            }
2955            result.Add("EFFECT_COUNT", pEffectChain->EffectCount());
2956            result.Add("EFFECT_SEQUENCE", sEffectSequence);
2957        } catch (Exception e) {
2958            result.Error(e);
2959        }
2960        return result.Produce();
2961    }
2962    
2963    String LSCPServer::AppendSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectInstance) {
2964        dmsg(2,("LSCPServer: AppendSendEffectChainEffect(%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectInstance));
2965        LSCPResultSet result;
2966        try {
2967            EffectChain* pEffectChain =
2968                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
2969            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2970            if (!pEffect)
2971                throw Exception("There is no effect instance with ID " + ToString(iEffectInstance));
2972            pEffectChain->AppendEffect(pEffect);
2973            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_info, iAudioOutputDevice, iSendEffectChain, pEffectChain->EffectCount()));
2974        } catch (Exception e) {
2975            result.Error(e);
2976        }
2977        return result.Produce();
2978    }
2979    
2980    String LSCPServer::InsertSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectChainPosition, int iEffectInstance) {
2981        dmsg(2,("LSCPServer: InsertSendEffectChainEffect(%d,%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectChainPosition, iEffectInstance));
2982        LSCPResultSet result;
2983        try {
2984            EffectChain* pEffectChain =
2985                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
2986            Effect* pEffect = EffectFactory::GetEffectInstanceByID(iEffectInstance);
2987            if (!pEffect)
2988                throw Exception("There is no effect instance with index " + ToString(iEffectInstance));
2989            pEffectChain->InsertEffect(pEffect, iEffectChainPosition);
2990            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_info, iAudioOutputDevice, iSendEffectChain, pEffectChain->EffectCount()));
2991        } catch (Exception e) {
2992            result.Error(e);
2993        }
2994        return result.Produce();
2995    }
2996    
2997    String LSCPServer::RemoveSendEffectChainEffect(int iAudioOutputDevice, int iSendEffectChain, int iEffectChainPosition) {
2998        dmsg(2,("LSCPServer: RemoveSendEffectChainEffect(%d,%d,%d)\n", iAudioOutputDevice, iSendEffectChain, iEffectChainPosition));
2999        LSCPResultSet result;
3000        try {
3001            EffectChain* pEffectChain =
3002                _getSendEffectChain(pSampler, iAudioOutputDevice, iSendEffectChain);
3003    
3004            std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
3005            std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();
3006            std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
3007            for (; itEngineChannel != itEnd; ++itEngineChannel) {
3008                AudioOutputDevice* pDev = (*itEngineChannel)->GetAudioOutputDevice();
3009                if (pDev != NULL && pDev->deviceId() == iAudioOutputDevice) {
3010                    for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
3011                        FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
3012                        if(fxs != NULL && fxs->DestinationEffectChain() == iSendEffectChain && fxs->DestinationEffectChainPosition() == iEffectChainPosition) {
3013                            throw Exception("The effect instance is still in use by channel " + ToString((*itEngineChannel)->GetSamplerChannel()->Index()));
3014                        }
3015                    }
3016                }
3017            }
3018    
3019            pEffectChain->RemoveEffect(iEffectChainPosition);
3020            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_send_fx_chain_info, iAudioOutputDevice, iSendEffectChain, pEffectChain->EffectCount()));
3021        } catch (Exception e) {
3022            result.Error(e);
3023        }
3024        return result.Produce();
3025    }
3026    
3027  String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {  String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
3028      dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
3029      LSCPResultSet result;      LSCPResultSet result;
# Line 2458  String LSCPServer::SendChannelMidiData(S Line 3072  String LSCPServer::SendChannelMidiData(S
3072              pMidiDevice->SendNoteOffToDevice(Arg1, Arg2);              pMidiDevice->SendNoteOffToDevice(Arg1, Arg2);
3073              bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2);              bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2);
3074              if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));              if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
3075            } else if (MidiMsg == "CC") {
3076                pMidiDevice->SendCCToDevice(Arg1, Arg2);
3077                bool b = pMidiDevice->SendCCToSampler(Arg1, Arg2);
3078                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
3079          } else {          } else {
3080              throw Exception("Unknown MIDI message type: " + MidiMsg);              throw Exception("Unknown MIDI message type: " + MidiMsg);
3081          }          }
# Line 2540  String LSCPServer::GetTotalVoiceCount() Line 3158  String LSCPServer::GetTotalVoiceCount()
3158  String LSCPServer::GetTotalVoiceCountMax() {  String LSCPServer::GetTotalVoiceCountMax() {
3159      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));
3160      LSCPResultSet result;      LSCPResultSet result;
3161      result.Add(EngineFactory::EngineInstances().size() * CONFIG_MAX_VOICES);      result.Add(EngineFactory::EngineInstances().size() * pSampler->GetGlobalMaxVoices());
3162        return result.Produce();
3163    }
3164    
3165    /**
3166     * Will be called by the parser to return the sampler global maximum
3167     * allowed number of voices.
3168     */
3169    String LSCPServer::GetGlobalMaxVoices() {
3170        dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n"));
3171        LSCPResultSet result;
3172        result.Add(pSampler->GetGlobalMaxVoices());
3173        return result.Produce();
3174    }
3175    
3176    /**
3177     * Will be called by the parser to set the sampler global maximum number of
3178     * voices.
3179     */
3180    String LSCPServer::SetGlobalMaxVoices(int iVoices) {
3181        dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices));
3182        LSCPResultSet result;
3183        try {
3184            pSampler->SetGlobalMaxVoices(iVoices);
3185            LSCPServer::SendLSCPNotify(
3186                LSCPEvent(LSCPEvent::event_global_info, "VOICES", pSampler->GetGlobalMaxVoices())
3187            );
3188        } catch (Exception e) {
3189            result.Error(e);
3190        }
3191        return result.Produce();
3192    }
3193    
3194    /**
3195     * Will be called by the parser to return the sampler global maximum
3196     * allowed number of disk streams.
3197     */
3198    String LSCPServer::GetGlobalMaxStreams() {
3199        dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n"));
3200        LSCPResultSet result;
3201        result.Add(pSampler->GetGlobalMaxStreams());
3202        return result.Produce();
3203    }
3204    
3205    /**
3206     * Will be called by the parser to set the sampler global maximum number of
3207     * disk streams.
3208     */
3209    String LSCPServer::SetGlobalMaxStreams(int iStreams) {
3210        dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams));
3211        LSCPResultSet result;
3212        try {
3213            pSampler->SetGlobalMaxStreams(iStreams);
3214            LSCPServer::SendLSCPNotify(
3215                LSCPEvent(LSCPEvent::event_global_info, "STREAMS", pSampler->GetGlobalMaxStreams())
3216            );
3217        } catch (Exception e) {
3218            result.Error(e);
3219        }
3220      return result.Produce();      return result.Produce();
3221  }  }
3222    
# Line 2728  void LSCPServer::VerifyFile(String Filen Line 3404  void LSCPServer::VerifyFile(String Filen
3404          throw Exception("Directory is specified");          throw Exception("Directory is specified");
3405      }      }
3406      #else      #else
3407      struct stat statBuf;      File f(Filename);
3408      int res = stat(Filename.c_str(), &statBuf);      if(!f.Exist()) throw Exception(f.GetErrorMsg());
3409      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");  
     }  
3410      #endif      #endif
3411  }  }
3412    
# Line 2749  void LSCPServer::VerifyFile(String Filen Line 3417  void LSCPServer::VerifyFile(String Filen
3417  String LSCPServer::SubscribeNotification(LSCPEvent::event_t type) {  String LSCPServer::SubscribeNotification(LSCPEvent::event_t type) {
3418      dmsg(2,("LSCPServer: SubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));      dmsg(2,("LSCPServer: SubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
3419      LSCPResultSet result;      LSCPResultSet result;
3420      SubscriptionMutex.Lock();      {
3421      eventSubscriptions[type].push_back(currentSocket);          LockGuard lock(SubscriptionMutex);
3422      SubscriptionMutex.Unlock();          eventSubscriptions[type].push_back(currentSocket);
3423        }
3424      return result.Produce();      return result.Produce();
3425  }  }
3426    
# Line 2762  String LSCPServer::SubscribeNotification Line 3431  String LSCPServer::SubscribeNotification
3431  String LSCPServer::UnsubscribeNotification(LSCPEvent::event_t type) {  String LSCPServer::UnsubscribeNotification(LSCPEvent::event_t type) {
3432      dmsg(2,("LSCPServer: UnsubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));      dmsg(2,("LSCPServer: UnsubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
3433      LSCPResultSet result;      LSCPResultSet result;
3434      SubscriptionMutex.Lock();      {
3435      eventSubscriptions[type].remove(currentSocket);          LockGuard lock(SubscriptionMutex);
3436      SubscriptionMutex.Unlock();          eventSubscriptions[type].remove(currentSocket);
3437        }
3438      return result.Produce();      return result.Produce();
3439  }  }
3440    

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

  ViewVC Help
Powered by ViewVC