/[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 1399 by schoenebeck, Thu Oct 11 18:53:29 2007 UTC revision 1536 by schoenebeck, Mon Dec 3 16:41:17 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 58  static String _escapeLscpResponse(String Line 61  static String _escapeLscpResponse(String
61              !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&              !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&
62              !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&              !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&
63              !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&              !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&
64              !(c == '@') && !(c == '[') && !(c == '\\') && !(c == ']') &&              !(c == '@') && !(c == '[') && !(c == ']') &&
65              !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&              !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&
66              !(c == '|') && !(c == '}') && !(c == '~')              !(c == '|') && !(c == '}') && !(c == '~')
67          ) {          ) {
# Line 129  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 230  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 243  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 325  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 337  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 399  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 478  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 493  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 531  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 877  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          result.Add("INSTRUMENT_FILE",          // convert the filename into the correct encoding as defined for LSCP
932                     (InstrumentFileName != "NONE" && InstrumentFileName != "") ?          // (especially in terms of special characters -> escape sequences)
933                          Path::fromPosix(InstrumentFileName).toLscp() : // TODO: assuming POSIX          if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
934                          InstrumentFileName  #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);
943          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
944          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
945          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
# Line 1825  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    
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));              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", Path::fromPosix(iter->second.InstrumentFile).toLscp()); //TODO: assuming POSIX              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 2315  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        bool bFatalErr = false;
2478        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2479        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2480            Engine* pEngine = NULL;
2481            try {
2482                pEngine = EngineFactory::Create(engineTypes[i]);
2483                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2484                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2485                if (pManager) {
2486                    // check if the instrument index is valid
2487                    // FIXME: this won't work if an engine only supports parts of the instrument file
2488                    std::vector<InstrumentManager::instrument_id_t> IDs =
2489                        pManager->GetInstrumentFileContent(Filename);
2490                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2491                        std::stringstream ss;
2492                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2493                        bFatalErr = true;
2494                        throw Exception(ss.str());
2495                    }
2496                    // get the info of the requested instrument
2497                    InstrumentManager::instrument_info_t info =
2498                        pManager->GetInstrumentInfo(id);
2499                    // return detailed informations about the file
2500                    result.Add("NAME", info.InstrumentName);
2501                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2502                    result.Add("FORMAT_VERSION", info.FormatVersion);
2503                    result.Add("PRODUCT", info.Product);
2504                    result.Add("ARTISTS", info.Artists);
2505                    // no more need to ask other engine types
2506                    bFound = true;
2507                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2508            } catch (Exception e) {
2509                // usually NOOP, as exception is thrown if engine doesn't support file
2510                if (bFatalErr) result.Error(e);
2511            }
2512            if (pEngine) EngineFactory::Destroy(pEngine);
2513        }
2514    
2515        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2516        return result.Produce();
2517    }
2518    
2519    void LSCPServer::VerifyFile(String Filename) {
2520        struct stat statBuf;
2521        int res = stat(Filename.c_str(), &statBuf);
2522        if (res) {
2523            std::stringstream ss;
2524            ss << "Fail to stat `" << Filename << "`: " << strerror(errno);
2525            throw Exception(ss.str());
2526        }
2527    
2528        if (S_ISDIR(statBuf.st_mode)) {
2529            throw Exception("Directory is specified");
2530        }
2531    }
2532    
2533  /**  /**
2534   * 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
2535   * server for receiving event messages.   * server for receiving event messages.
# Line 2416  String LSCPServer::GetDbInstrumentDirect Line 2631  String LSCPServer::GetDbInstrumentDirect
2631      try {      try {
2632          DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);          DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2633    
2634          result.Add("DESCRIPTION", InstrumentsDb::toEscapedText(info.Description));          result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2635          result.Add("CREATED", info.Created);          result.Add("CREATED", info.Created);
2636          result.Add("MODIFIED", info.Modified);          result.Add("MODIFIED", info.Modified);
2637      } catch (Exception e) {      } catch (Exception e) {
# Line 2600  String LSCPServer::GetDbInstrumentInfo(S Line 2815  String LSCPServer::GetDbInstrumentInfo(S
2815          result.Add("SIZE", (int)info.Size);          result.Add("SIZE", (int)info.Size);
2816          result.Add("CREATED", info.Created);          result.Add("CREATED", info.Created);
2817          result.Add("MODIFIED", info.Modified);          result.Add("MODIFIED", info.Modified);
2818          result.Add("DESCRIPTION", InstrumentsDb::toEscapedText(info.Description));          result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2819          result.Add("IS_DRUM", info.IsDrum);          result.Add("IS_DRUM", info.IsDrum);
2820          result.Add("PRODUCT", InstrumentsDb::toEscapedText(info.Product));          result.Add("PRODUCT", _escapeLscpResponse(info.Product));
2821          result.Add("ARTISTS", InstrumentsDb::toEscapedText(info.Artists));          result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
2822          result.Add("KEYWORDS", InstrumentsDb::toEscapedText(info.Keywords));          result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
2823      } catch (Exception e) {      } catch (Exception e) {
2824           result.Error(e);           result.Error(e);
2825      }      }

Legend:
Removed from v.1399  
changed lines
  Added in v.1536

  ViewVC Help
Powered by ViewVC