/[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 1187 by iliev, Wed May 16 14:22:26 2007 UTC revision 1535 by iliev, Mon Dec 3 13:59:03 2007 UTC
# Line 25  Line 25 
25  #include "lscpresultset.h"  #include "lscpresultset.h"
26  #include "lscpevent.h"  #include "lscpevent.h"
27    
28    #if defined(WIN32)
29    #else
30  #include <fcntl.h>  #include <fcntl.h>
31    #endif
32    
33  #if ! HAVE_SQLITE3  #if ! HAVE_SQLITE3
34  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."
# Line 36  Line 39 
39  #include "../drivers/audio/AudioOutputDeviceFactory.h"  #include "../drivers/audio/AudioOutputDeviceFactory.h"
40  #include "../drivers/midi/MidiInputDeviceFactory.h"  #include "../drivers/midi/MidiInputDeviceFactory.h"
41    
42    
43    /**
44     * Returns a copy of the given string where all special characters are
45     * replaced by LSCP escape sequences ("\xHH"). This function shall be used
46     * to escape LSCP response fields in case the respective response field is
47     * actually defined as using escape sequences in the LSCP specs.
48     *
49     * @e Caution: DO NOT use this function for escaping path based responses,
50     * use the Path class (src/common/Path.h) for this instead!
51     */
52    static String _escapeLscpResponse(String txt) {
53        for (int i = 0; i < txt.length(); i++) {
54            const char c = txt.c_str()[i];
55            if (
56                !(c >= '0' && c <= '9') &&
57                !(c >= 'a' && c <= 'z') &&
58                !(c >= 'A' && c <= 'Z') &&
59                !(c == ' ') && !(c == '!') && !(c == '#') && !(c == '$') &&
60                !(c == '%') && !(c == '&') && !(c == '(') && !(c == ')') &&
61                !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&
62                !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&
63                !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&
64                !(c == '@') && !(c == '[') && !(c == ']') &&
65                !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&
66                !(c == '|') && !(c == '}') && !(c == '~')
67            ) {
68                // convert the "special" character into a "\xHH" LSCP escape sequence
69                char buf[5];
70                snprintf(buf, sizeof(buf), "\\x%02x", static_cast<unsigned char>(c));
71                txt.replace(i, 1, buf);
72                i += 3;
73            }
74        }
75        return txt;
76    }
77    
78  /**  /**
79   * Below are a few static members of the LSCPServer class.   * Below are a few static members of the LSCPServer class.
80   * The big assumption here is that LSCPServer is going to remain a singleton.   * The big assumption here is that LSCPServer is going to remain a singleton.
# Line 52  Line 91 
91  fd_set LSCPServer::fdSet;  fd_set LSCPServer::fdSet;
92  int LSCPServer::currentSocket = -1;  int LSCPServer::currentSocket = -1;
93  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();
94    std::vector<yyparse_param_t>::iterator itCurrentSession = std::vector<yyparse_param_t>::iterator();
95  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();
96  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();
97  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 = std::map< LSCPEvent::event_t, std::list<int> >();
# Line 84  LSCPServer::LSCPServer(Sampler* pSampler Line 124  LSCPServer::LSCPServer(Sampler* pSampler
124      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_info, "DB_INSTRUMENT_DIRECTORY_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_info, "DB_INSTRUMENT_DIRECTORY_INFO");
125      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_count, "DB_INSTRUMENT_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_count, "DB_INSTRUMENT_COUNT");
126      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
127        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
128      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
129      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
130      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
# Line 91  LSCPServer::LSCPServer(Sampler* pSampler Line 132  LSCPServer::LSCPServer(Sampler* pSampler
132  }  }
133    
134  LSCPServer::~LSCPServer() {  LSCPServer::~LSCPServer() {
135    #if defined(WIN32)
136        if (hSocket >= 0) closesocket(hSocket);
137    #else
138      if (hSocket >= 0) close(hSocket);      if (hSocket >= 0) close(hSocket);
139    #endif
140  }  }
141    
142  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
# Line 144  void LSCPServer::EventHandler::TotalVoic Line 189  void LSCPServer::EventHandler::TotalVoic
189    
190  #if HAVE_SQLITE3  #if HAVE_SQLITE3
191  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
192      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, Dir));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
193  }  }
194    
195  void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {  void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {
196      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, Dir));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, InstrumentsDb::toEscapedPath(Dir)));
197  }  }
198    
199  void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {  void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {
200      Dir = "'" + Dir + "'";      Dir = "'" + InstrumentsDb::toEscapedPath(Dir) + "'";
201      NewName = "'" + NewName + "'";      NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
202      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));
203  }  }
204    
205  void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {  void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {
206      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, Dir));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, InstrumentsDb::toEscapedPath(Dir)));
207  }  }
208    
209  void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {  void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {
210      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, Instr));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, InstrumentsDb::toEscapedPath(Instr)));
211  }  }
212    
213  void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {  void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {
214      Instr = "'" + Instr + "'";      Instr = "'" + InstrumentsDb::toEscapedPath(Instr) + "'";
215      NewName = "'" + NewName + "'";      NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
216      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));
217  }  }
218    
219    void LSCPServer::DbInstrumentsEventHandler::JobStatusChanged(int JobId) {
220        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instrs_job_info, JobId));
221    }
222  #endif // HAVE_SQLITE3  #endif // HAVE_SQLITE3
223    
224    
# Line 187  int LSCPServer::WaitUntilInitialized(lon Line 237  int LSCPServer::WaitUntilInitialized(lon
237  }  }
238    
239  int LSCPServer::Main() {  int LSCPServer::Main() {
240            #if defined(WIN32)
241            WSADATA wsaData;
242            int iResult;
243            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
244            if (iResult != 0) {
245                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
246                    exit(EXIT_FAILURE);
247            }
248            #endif
249      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
250      if (hSocket < 0) {      if (hSocket < 0) {
251          std::cerr << "LSCPServer: Could not create server socket." << std::endl;          std::cerr << "LSCPServer: Could not create server socket." << std::endl;
# Line 200  int LSCPServer::Main() { Line 259  int LSCPServer::Main() {
259              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
260                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
261                      std::cerr << "gave up!" << std::endl;                      std::cerr << "gave up!" << std::endl;
262                        #if defined(WIN32)
263                        closesocket(hSocket);
264                        #else
265                      close(hSocket);                      close(hSocket);
266                        #endif
267                      //return -1;                      //return -1;
268                      exit(EXIT_FAILURE);                      exit(EXIT_FAILURE);
269                  }                  }
# Line 212  int LSCPServer::Main() { Line 275  int LSCPServer::Main() {
275    
276      listen(hSocket, 1);      listen(hSocket, 1);
277      Initialized.Set(true);      Initialized.Set(true);
278        
279      // Registering event listeners      // Registering event listeners
280      pSampler->AddChannelCountListener(&eventHandler);      pSampler->AddChannelCountListener(&eventHandler);
281      pSampler->AddAudioDeviceCountListener(&eventHandler);      pSampler->AddAudioDeviceCountListener(&eventHandler);
# Line 282  int LSCPServer::Main() { Line 345  int LSCPServer::Main() {
345                  continue; //Nothing try again                  continue; //Nothing try again
346          if (retval == -1) {          if (retval == -1) {
347                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
348                    #if defined(WIN32)
349                    closesocket(hSocket);
350                    #else
351                  close(hSocket);                  close(hSocket);
352                    #endif
353                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
354          }          }
355    
# Line 294  int LSCPServer::Main() { Line 361  int LSCPServer::Main() {
361                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
362                  }                  }
363    
364                    #if defined(WIN32)
365                    u_long nonblock_io = 1;
366                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
367                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
368                      exit(EXIT_FAILURE);
369                    }
370            #else          
371                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
372                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
373                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
374                  }                  }
375                    #endif
376    
377                  // Parser initialization                  // Parser initialization
378                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 321  int LSCPServer::Main() { Line 396  int LSCPServer::Main() {
396                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
397                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
398                                  currentSocket = (*iter).hSession;  //a hack                                  currentSocket = (*iter).hSession;  //a hack
399                                    itCurrentSession = iter; // another hack
400                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
401                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
402                                      AnswerClient(bufferedCommands[currentSocket]);                                      AnswerClient(bufferedCommands[currentSocket]);
403                                  }                                  }
404                                  int result = yyparse(&(*iter));                                  int result = yyparse(&(*iter));
405                                  currentSocket = -1;     //continuation of a hack                                  currentSocket = -1;     //continuation of a hack
406                                    itCurrentSession = Sessions.end(); // hack as well
407                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
408                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?
409                                          CloseConnection(iter);                                          CloseConnection(iter);
# Line 354  void LSCPServer::CloseConnection( std::v Line 431  void LSCPServer::CloseConnection( std::v
431          NotifyMutex.Lock();          NotifyMutex.Lock();
432          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
433          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
434            #if defined(WIN32)
435            closesocket(socket);
436            #else
437          close(socket);          close(socket);
438            #endif
439          NotifyMutex.Unlock();          NotifyMutex.Unlock();
440  }  }
441    
# Line 419  extern int GetLSCPCommand( void *buf, in Line 500  extern int GetLSCPCommand( void *buf, in
500          return command.size();          return command.size();
501  }  }
502    
503    extern yyparse_param_t* GetCurrentYaccSession() {
504        return &(*itCurrentSession);
505    }
506    
507  /**  /**
508   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
509   * If command is read, it will return true. Otherwise false is returned.   * If command is read, it will return true. Otherwise false is returned.
# Line 429  bool LSCPServer::GetLSCPCommand( std::ve Line 514  bool LSCPServer::GetLSCPCommand( std::ve
514          char c;          char c;
515          int i = 0;          int i = 0;
516          while (true) {          while (true) {
517                    #if defined(WIN32)
518                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
519                    #else
520                  int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now                  int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now
521                    #endif
522                  if (result == 0) { //socket was selected, so 0 here means client has closed the connection                  if (result == 0) { //socket was selected, so 0 here means client has closed the connection
523                          CloseConnection(iter);                          CloseConnection(iter);
524                          break;                          break;
# Line 444  bool LSCPServer::GetLSCPCommand( std::ve Line 533  bool LSCPServer::GetLSCPCommand( std::ve
533                          }                          }
534                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
535                  }                  }
536                    #if defined(WIN32)
537                    if (result == SOCKET_ERROR) {
538                        int wsa_lasterror = WSAGetLastError();
539                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
540                                    return false;
541                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));  
542                            CloseConnection(iter);
543                            break;
544                    }
545                    #else
546                  if (result == -1) {                  if (result == -1) {
547                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
548                                  return false;                                  return false;
# Line 482  bool LSCPServer::GetLSCPCommand( std::ve Line 581  bool LSCPServer::GetLSCPCommand( std::ve
581                          CloseConnection(iter);                          CloseConnection(iter);
582                          break;                          break;
583                  }                  }
584                    #endif
585          }          }
586          return false;          return false;
587  }  }
# Line 606  EngineChannel* LSCPServer::GetEngineChan Line 706  EngineChannel* LSCPServer::GetEngineChan
706      EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();      EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
707      if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");      if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
708    
709      return pEngineChannel;              return pEngineChannel;
710  }  }
711    
712  /**  /**
# Line 755  String LSCPServer::GetEngineInfo(String Line 855  String LSCPServer::GetEngineInfo(String
855      LockRTNotify();      LockRTNotify();
856      try {      try {
857          Engine* pEngine = EngineFactory::Create(EngineName);          Engine* pEngine = EngineFactory::Create(EngineName);
858          result.Add("DESCRIPTION", pEngine->Description());          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
859          result.Add("VERSION",     pEngine->Version());          result.Add("VERSION",     pEngine->Version());
860          EngineFactory::Destroy(pEngine);          EngineFactory::Destroy(pEngine);
861      }      }
# Line 828  String LSCPServer::GetChannelInfo(uint u Line 928  String LSCPServer::GetChannelInfo(uint u
928          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
929          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
930    
931            // convert the filename into the correct encoding as defined for LSCP
932            // (especially in terms of special characters -> escape sequences)
933            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
934    #if WIN32
935                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
936    #else
937                // assuming POSIX
938                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
939    #endif
940            }
941    
942          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
943          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
944          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
945          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
946          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
947          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
# Line 1772  String LSCPServer::GetMidiInstrumentMapp Line 1883  String LSCPServer::GetMidiInstrumentMapp
1883          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);
1884          if (iter == mappings.end()) result.Error("there is no map entry with that index");          if (iter == mappings.end()) result.Error("there is no map entry with that index");
1885          else { // found          else { // found
1886              result.Add("NAME", iter->second.Name);  
1887                // convert the filename into the correct encoding as defined for LSCP
1888                // (especially in terms of special characters -> escape sequences)
1889    #if WIN32
1890                const String instrumentFileName = Path::fromWindows(iter->second.InstrumentFile).toLscp();
1891    #else
1892                // assuming POSIX
1893                const String instrumentFileName = Path::fromPosix(iter->second.InstrumentFile).toLscp();
1894    #endif
1895    
1896                result.Add("NAME", _escapeLscpResponse(iter->second.Name));
1897              result.Add("ENGINE_NAME", iter->second.EngineName);              result.Add("ENGINE_NAME", iter->second.EngineName);
1898              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);              result.Add("INSTRUMENT_FILE", instrumentFileName);
1899              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);
1900              String instrumentName;              String instrumentName;
1901              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);
# Line 1787  String LSCPServer::GetMidiInstrumentMapp Line 1908  String LSCPServer::GetMidiInstrumentMapp
1908                  }                  }
1909                  EngineFactory::Destroy(pEngine);                  EngineFactory::Destroy(pEngine);
1910              }              }
1911              result.Add("INSTRUMENT_NAME", instrumentName);              result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
1912              switch (iter->second.LoadMode) {              switch (iter->second.LoadMode) {
1913                  case MidiInstrumentMapper::ON_DEMAND:                  case MidiInstrumentMapper::ON_DEMAND:
1914                      result.Add("LOAD_MODE", "ON_DEMAND");                      result.Add("LOAD_MODE", "ON_DEMAND");
# Line 1942  String LSCPServer::GetMidiInstrumentMap( Line 2063  String LSCPServer::GetMidiInstrumentMap(
2063      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2064      LSCPResultSet result;      LSCPResultSet result;
2065      try {      try {
2066          result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID));          result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2067          result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);          result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2068      } catch (Exception e) {      } catch (Exception e) {
2069          result.Error(e);          result.Error(e);
# Line 1993  String LSCPServer::CreateFxSend(uint uiS Line 2114  String LSCPServer::CreateFxSend(uint uiS
2114      LSCPResultSet result;      LSCPResultSet result;
2115      try {      try {
2116          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2117            
2118          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2119          if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");          if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");
2120    
# Line 2077  String LSCPServer::GetFxSendInfo(uint ui Line 2198  String LSCPServer::GetFxSendInfo(uint ui
2198      try {      try {
2199          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2200          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2201            
2202          // gather audio routing informations          // gather audio routing informations
2203          String AudioRouting;          String AudioRouting;
2204          for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {          for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {
# Line 2086  String LSCPServer::GetFxSendInfo(uint ui Line 2207  String LSCPServer::GetFxSendInfo(uint ui
2207          }          }
2208    
2209          // success          // success
2210          result.Add("NAME", pFxSend->Name());          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2211          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2212          result.Add("LEVEL", ToString(pFxSend->Level()));          result.Add("LEVEL", ToString(pFxSend->Level()));
2213          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
# Line 2152  String LSCPServer::SetFxSendLevel(uint u Line 2273  String LSCPServer::SetFxSendLevel(uint u
2273      return result.Produce();      return result.Produce();
2274  }  }
2275    
2276    String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2277        dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2278        LSCPResultSet result;
2279        try {
2280            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
2281            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
2282            EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
2283            if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
2284            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2285            Engine* pEngine = pEngineChannel->GetEngine();
2286            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2287            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2288            InstrumentManager::instrument_id_t instrumentID;
2289            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2290            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2291            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2292        } catch (Exception e) {
2293            result.Error(e);
2294        }
2295        return result.Produce();
2296    }
2297    
2298  /**  /**
2299   * Will be called by the parser to reset a particular sampler channel.   * Will be called by the parser to reset a particular sampler channel.
2300   */   */
# Line 2187  String LSCPServer::ResetSampler() { Line 2330  String LSCPServer::ResetSampler() {
2330   */   */
2331  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
2332      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
2333        const std::string description =
2334            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2335      LSCPResultSet result;      LSCPResultSet result;
2336      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
2337      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
2338      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2339  #if HAVE_SQLITE3  #if HAVE_SQLITE3
# Line 2196  String LSCPServer::GetServerInfo() { Line 2341  String LSCPServer::GetServerInfo() {
2341  #else  #else
2342      result.Add("INSTRUMENTS_DB_SUPPORT", "no");      result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2343  #endif  #endif
2344        
2345      return result.Produce();      return result.Produce();
2346  }  }
2347    
# Line 2238  String LSCPServer::SetGlobalVolume(doubl Line 2383  String LSCPServer::SetGlobalVolume(doubl
2383      return result.Produce();      return result.Produce();
2384  }  }
2385    
2386    String LSCPServer::GetFileInstruments(String Filename) {
2387        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2388        LSCPResultSet result;
2389        try {
2390            VerifyFile(Filename);
2391        } catch (Exception e) {
2392            result.Error(e);
2393            return result.Produce();
2394        }
2395        // try to find a sampler engine that can handle the file
2396        bool bFound = false;
2397        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2398        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2399            Engine* pEngine = NULL;
2400            try {
2401                pEngine = EngineFactory::Create(engineTypes[i]);
2402                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2403                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2404                if (pManager) {
2405                    std::vector<InstrumentManager::instrument_id_t> IDs =
2406                        pManager->GetInstrumentFileContent(Filename);
2407                    // return the amount of instruments in the file
2408                    result.Add(IDs.size());
2409                    // no more need to ask other engine types
2410                    bFound = true;
2411                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2412            } catch (Exception e) {
2413                // NOOP, as exception is thrown if engine doesn't support file
2414            }
2415            if (pEngine) EngineFactory::Destroy(pEngine);
2416        }
2417    
2418        if (!bFound) result.Error("Unknown file format");
2419        return result.Produce();
2420    }
2421    
2422    String LSCPServer::ListFileInstruments(String Filename) {
2423        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2424        LSCPResultSet result;
2425        try {
2426            VerifyFile(Filename);
2427        } catch (Exception e) {
2428            result.Error(e);
2429            return result.Produce();
2430        }
2431        // try to find a sampler engine that can handle the file
2432        bool bFound = false;
2433        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2434        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2435            Engine* pEngine = NULL;
2436            try {
2437                pEngine = EngineFactory::Create(engineTypes[i]);
2438                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2439                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2440                if (pManager) {
2441                    std::vector<InstrumentManager::instrument_id_t> IDs =
2442                        pManager->GetInstrumentFileContent(Filename);
2443                    // return a list of IDs of the instruments in the file
2444                    String s;
2445                    for (int j = 0; j < IDs.size(); j++) {
2446                        if (s.size()) s += ",";
2447                        s += ToString(IDs[j].Index);
2448                    }
2449                    result.Add(s);
2450                    // no more need to ask other engine types
2451                    bFound = true;
2452                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2453            } catch (Exception e) {
2454                // NOOP, as exception is thrown if engine doesn't support file
2455            }
2456            if (pEngine) EngineFactory::Destroy(pEngine);
2457        }
2458    
2459        if (!bFound) result.Error("Unknown file format");
2460        return result.Produce();
2461    }
2462    
2463    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2464        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2465        LSCPResultSet result;
2466        try {
2467            VerifyFile(Filename);
2468        } catch (Exception e) {
2469            result.Error(e);
2470            return result.Produce();
2471        }
2472        InstrumentManager::instrument_id_t id;
2473        id.FileName = Filename;
2474        id.Index    = InstrumentID;
2475        // try to find a sampler engine that can handle the file
2476        bool bFound = false;
2477        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2478        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2479            Engine* pEngine = NULL;
2480            try {
2481                pEngine = EngineFactory::Create(engineTypes[i]);
2482                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2483                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2484                if (pManager) {
2485                    InstrumentManager::instrument_info_t info =
2486                        pManager->GetInstrumentInfo(id);
2487                    // return detailed informations about the file
2488                    result.Add("NAME", info.InstrumentName);
2489                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2490                    result.Add("FORMAT_VERSION", info.FormatVersion);
2491                    result.Add("PRODUCT", info.Product);
2492                    result.Add("ARTISTS", info.Artists);
2493                    // no more need to ask other engine types
2494                    bFound = true;
2495                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2496            } catch (Exception e) {
2497                // NOOP, as exception is thrown if engine doesn't support file
2498            }
2499            if (pEngine) EngineFactory::Destroy(pEngine);
2500        }
2501    
2502        if (!bFound) result.Error("Unknown file format");
2503        return result.Produce();
2504    }
2505    
2506    void LSCPServer::VerifyFile(String Filename) {
2507        struct stat statBuf;
2508        int res = stat(Filename.c_str(), &statBuf);
2509        if (res) {
2510            std::stringstream ss;
2511            ss << "Fail to stat `" << Filename << "`: " << strerror(errno);
2512            throw Exception(ss.str());
2513        }
2514    
2515        if (S_ISDIR(statBuf.st_mode)) {
2516            throw Exception("Directory is specified");
2517        }
2518    }
2519    
2520  /**  /**
2521   * Will be called by the parser to subscribe a client (frontend) on the   * Will be called by the parser to subscribe a client (frontend) on the
2522   * server for receiving event messages.   * server for receiving event messages.
# Line 2319  String LSCPServer::GetDbInstrumentDirect Line 2598  String LSCPServer::GetDbInstrumentDirect
2598    
2599          for (int i = 0; i < dirs->size(); i++) {          for (int i = 0; i < dirs->size(); i++) {
2600              if (list != "") list += ",";              if (list != "") list += ",";
2601              list += "'" + dirs->at(i) + "'";              list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2602          }          }
2603    
2604          result.Add(list);          result.Add(list);
# Line 2339  String LSCPServer::GetDbInstrumentDirect Line 2618  String LSCPServer::GetDbInstrumentDirect
2618      try {      try {
2619          DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);          DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2620    
2621          result.Add("DESCRIPTION", info.Description);          result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2622          result.Add("CREATED", info.Created);          result.Add("CREATED", info.Created);
2623          result.Add("MODIFIED", info.Modified);          result.Add("MODIFIED", info.Modified);
2624      } catch (Exception e) {      } catch (Exception e) {
# Line 2411  String LSCPServer::SetDbInstrumentDirect Line 2690  String LSCPServer::SetDbInstrumentDirect
2690      return result.Produce();      return result.Produce();
2691  }  }
2692    
2693  String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index) {  String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
2694      dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d)\n", DbDir.c_str(), FilePath.c_str(), Index));      dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
2695      LSCPResultSet result;      LSCPResultSet result;
2696  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2697      try {      try {
2698          InstrumentsDb::GetInstrumentsDb()->AddInstruments(DbDir, FilePath, Index);          int id;
2699            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2700            id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
2701            if (bBackground) result = id;
2702      } catch (Exception e) {      } catch (Exception e) {
2703           result.Error(e);           result.Error(e);
2704      }      }
# Line 2426  String LSCPServer::AddDbInstruments(Stri Line 2708  String LSCPServer::AddDbInstruments(Stri
2708      return result.Produce();      return result.Produce();
2709  }  }
2710    
2711  String LSCPServer::AddDbInstrumentsFlat(String DbDir, String FsDir) {  String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {
2712      dmsg(2,("LSCPServer: AddDbInstrumentsFlat(DbDir=%s,FilePath=%s)\n", DbDir.c_str(), FsDir.c_str()));      dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground));
2713      LSCPResultSet result;      LSCPResultSet result;
2714  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2715      try {      try {
2716          InstrumentsDb::GetInstrumentsDb()->AddInstrumentsRecursive(DbDir, FsDir, true);          int id;
2717      } catch (Exception e) {          InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2718           result.Error(e);          if (ScanMode.compare("RECURSIVE") == 0) {
2719      }             id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);
2720  #else          } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
2721      result.Error(String(DOESNT_HAVE_SQLITE3), 0);             id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);
2722  #endif          } else if (ScanMode.compare("FLAT") == 0) {
2723      return result.Produce();             id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);
2724  }          } else {
2725                throw Exception("Unknown scan mode: " + ScanMode);
2726            }
2727    
2728  String LSCPServer::AddDbInstrumentsNonrecursive(String DbDir, String FsDir) {          if (bBackground) result = id;
     dmsg(2,("LSCPServer: AddDbInstrumentsNonrecursive(DbDir=%s,FilePath=%s)\n", DbDir.c_str(), FsDir.c_str()));  
     LSCPResultSet result;  
 #if HAVE_SQLITE3  
     try {  
         InstrumentsDb::GetInstrumentsDb()->AddInstrumentsNonrecursive(DbDir, FsDir);  
2729      } catch (Exception e) {      } catch (Exception e) {
2730           result.Error(e);           result.Error(e);
2731      }      }
# Line 2496  String LSCPServer::GetDbInstruments(Stri Line 2775  String LSCPServer::GetDbInstruments(Stri
2775    
2776          for (int i = 0; i < instrs->size(); i++) {          for (int i = 0; i < instrs->size(); i++) {
2777              if (list != "") list += ",";              if (list != "") list += ",";
2778              list += "'" + instrs->at(i) + "'";              list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
2779          }          }
2780    
2781          result.Add(list);          result.Add(list);
# Line 2523  String LSCPServer::GetDbInstrumentInfo(S Line 2802  String LSCPServer::GetDbInstrumentInfo(S
2802          result.Add("SIZE", (int)info.Size);          result.Add("SIZE", (int)info.Size);
2803          result.Add("CREATED", info.Created);          result.Add("CREATED", info.Created);
2804          result.Add("MODIFIED", info.Modified);          result.Add("MODIFIED", info.Modified);
2805          result.Add("DESCRIPTION", FilterEndlines(info.Description));          result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2806          result.Add("IS_DRUM", info.IsDrum);          result.Add("IS_DRUM", info.IsDrum);
2807          result.Add("PRODUCT", FilterEndlines(info.Product));          result.Add("PRODUCT", _escapeLscpResponse(info.Product));
2808          result.Add("ARTISTS", FilterEndlines(info.Artists));          result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
2809          result.Add("KEYWORDS", FilterEndlines(info.Keywords));          result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
2810        } catch (Exception e) {
2811             result.Error(e);
2812        }
2813    #else
2814        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2815    #endif
2816        return result.Produce();
2817    }
2818    
2819    String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
2820        dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
2821        LSCPResultSet result;
2822    #if HAVE_SQLITE3
2823        try {
2824            ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
2825    
2826            result.Add("FILES_TOTAL", job.FilesTotal);
2827            result.Add("FILES_SCANNED", job.FilesScanned);
2828            result.Add("SCANNING", job.Scanning);
2829            result.Add("STATUS", job.Status);
2830      } catch (Exception e) {      } catch (Exception e) {
2831           result.Error(e);           result.Error(e);
2832      }      }
# Line 2624  String LSCPServer::FindDbInstrumentDirec Line 2923  String LSCPServer::FindDbInstrumentDirec
2923    
2924          for (int i = 0; i < pDirectories->size(); i++) {          for (int i = 0; i < pDirectories->size(); i++) {
2925              if (list != "") list += ",";              if (list != "") list += ",";
2926              list += "'" + pDirectories->at(i) + "'";              list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
2927          }          }
2928    
2929          result.Add(list);          result.Add(list);
# Line 2680  String LSCPServer::FindDbInstruments(Str Line 2979  String LSCPServer::FindDbInstruments(Str
2979    
2980          for (int i = 0; i < pInstruments->size(); i++) {          for (int i = 0; i < pInstruments->size(); i++) {
2981              if (list != "") list += ",";              if (list != "") list += ",";
2982              list += "'" + pInstruments->at(i) + "'";              list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
2983          }          }
2984    
2985          result.Add(list);          result.Add(list);
# Line 2693  String LSCPServer::FindDbInstruments(Str Line 2992  String LSCPServer::FindDbInstruments(Str
2992      return result.Produce();      return result.Produce();
2993  }  }
2994    
2995    String LSCPServer::FormatInstrumentsDb() {
2996        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
2997        LSCPResultSet result;
2998    #if HAVE_SQLITE3
2999        try {
3000            InstrumentsDb::GetInstrumentsDb()->Format();
3001        } catch (Exception e) {
3002             result.Error(e);
3003        }
3004    #else
3005        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3006    #endif
3007        return result.Produce();
3008    }
3009    
3010    
3011  /**  /**
3012   * Will be called by the parser to enable or disable echo mode; if echo   * Will be called by the parser to enable or disable echo mode; if echo
# Line 2712  String LSCPServer::SetEcho(yyparse_param Line 3026  String LSCPServer::SetEcho(yyparse_param
3026      }      }
3027      return result.Produce();      return result.Produce();
3028  }  }
   
 String LSCPServer::FilterEndlines(String s) {  
     String s2 = s;  
     for (int i = 0; i < s2.length(); i++) {  
         if (s2.at(i) == '\r') s2.at(i) = ' ';  
         else if (s2.at(i) == '\n') s2.at(i) = ' ';  
     }  
       
     return s2;  
 }  

Legend:
Removed from v.1187  
changed lines
  Added in v.1535

  ViewVC Help
Powered by ViewVC