/[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 1403 by iliev, Fri Oct 12 09:12:22 2007 UTC revision 1541 by iliev, Tue Dec 4 18:09:26 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    #include <windows.h>
30    #else
31  #include <fcntl.h>  #include <fcntl.h>
32    #endif
33    
34  #if ! HAVE_SQLITE3  #if ! HAVE_SQLITE3
35  #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 123  LSCPServer::LSCPServer(Sampler* pSampler Line 127  LSCPServer::LSCPServer(Sampler* pSampler
127      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
128      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
129      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
130        LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT");
131      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
132      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
133      hSocket = -1;      hSocket = -1;
134  }  }
135    
136  LSCPServer::~LSCPServer() {  LSCPServer::~LSCPServer() {
137    #if defined(WIN32)
138        if (hSocket >= 0) closesocket(hSocket);
139    #else
140      if (hSocket >= 0) close(hSocket);      if (hSocket >= 0) close(hSocket);
141    #endif
142  }  }
143    
144  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
# Line 180  void LSCPServer::EventHandler::TotalVoic Line 189  void LSCPServer::EventHandler::TotalVoic
189      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
190  }  }
191    
192    void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
193        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
194    }
195    
196  #if HAVE_SQLITE3  #if HAVE_SQLITE3
197  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {  void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
198      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
# Line 230  int LSCPServer::WaitUntilInitialized(lon Line 243  int LSCPServer::WaitUntilInitialized(lon
243  }  }
244    
245  int LSCPServer::Main() {  int LSCPServer::Main() {
246            #if defined(WIN32)
247            WSADATA wsaData;
248            int iResult;
249            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
250            if (iResult != 0) {
251                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
252                    exit(EXIT_FAILURE);
253            }
254            #endif
255      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
256      if (hSocket < 0) {      if (hSocket < 0) {
257          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 265  int LSCPServer::Main() {
265              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
266                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
267                      std::cerr << "gave up!" << std::endl;                      std::cerr << "gave up!" << std::endl;
268                        #if defined(WIN32)
269                        closesocket(hSocket);
270                        #else
271                      close(hSocket);                      close(hSocket);
272                        #endif
273                      //return -1;                      //return -1;
274                      exit(EXIT_FAILURE);                      exit(EXIT_FAILURE);
275                  }                  }
# Line 263  int LSCPServer::Main() { Line 289  int LSCPServer::Main() {
289      pSampler->AddVoiceCountListener(&eventHandler);      pSampler->AddVoiceCountListener(&eventHandler);
290      pSampler->AddStreamCountListener(&eventHandler);      pSampler->AddStreamCountListener(&eventHandler);
291      pSampler->AddBufferFillListener(&eventHandler);      pSampler->AddBufferFillListener(&eventHandler);
292        pSampler->AddTotalStreamCountListener(&eventHandler);
293      pSampler->AddTotalVoiceCountListener(&eventHandler);      pSampler->AddTotalVoiceCountListener(&eventHandler);
294      pSampler->AddFxSendCountListener(&eventHandler);      pSampler->AddFxSendCountListener(&eventHandler);
295      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
# Line 325  int LSCPServer::Main() { Line 352  int LSCPServer::Main() {
352                  continue; //Nothing try again                  continue; //Nothing try again
353          if (retval == -1) {          if (retval == -1) {
354                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
355                    #if defined(WIN32)
356                    closesocket(hSocket);
357                    #else
358                  close(hSocket);                  close(hSocket);
359                    #endif
360                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
361          }          }
362    
# Line 337  int LSCPServer::Main() { Line 368  int LSCPServer::Main() {
368                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
369                  }                  }
370    
371                    #if defined(WIN32)
372                    u_long nonblock_io = 1;
373                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
374                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
375                      exit(EXIT_FAILURE);
376                    }
377            #else
378                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
379                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
380                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
381                  }                  }
382                    #endif
383    
384                  // Parser initialization                  // Parser initialization
385                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 399  void LSCPServer::CloseConnection( std::v Line 438  void LSCPServer::CloseConnection( std::v
438          NotifyMutex.Lock();          NotifyMutex.Lock();
439          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
440          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
441            #if defined(WIN32)
442            closesocket(socket);
443            #else
444          close(socket);          close(socket);
445            #endif
446          NotifyMutex.Unlock();          NotifyMutex.Unlock();
447  }  }
448    
# Line 478  bool LSCPServer::GetLSCPCommand( std::ve Line 521  bool LSCPServer::GetLSCPCommand( std::ve
521          char c;          char c;
522          int i = 0;          int i = 0;
523          while (true) {          while (true) {
524                    #if defined(WIN32)
525                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
526                    #else
527                  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
528                    #endif
529                  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
530                          CloseConnection(iter);                          CloseConnection(iter);
531                          break;                          break;
# Line 493  bool LSCPServer::GetLSCPCommand( std::ve Line 540  bool LSCPServer::GetLSCPCommand( std::ve
540                          }                          }
541                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
542                  }                  }
543                    #if defined(WIN32)
544                    if (result == SOCKET_ERROR) {
545                        int wsa_lasterror = WSAGetLastError();
546                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
547                                    return false;
548                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
549                            CloseConnection(iter);
550                            break;
551                    }
552                    #else
553                  if (result == -1) {                  if (result == -1) {
554                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
555                                  return false;                                  return false;
# Line 531  bool LSCPServer::GetLSCPCommand( std::ve Line 588  bool LSCPServer::GetLSCPCommand( std::ve
588                          CloseConnection(iter);                          CloseConnection(iter);
589                          break;                          break;
590                  }                  }
591                    #endif
592          }          }
593          return false;          return false;
594  }  }
# Line 877  String LSCPServer::GetChannelInfo(uint u Line 935  String LSCPServer::GetChannelInfo(uint u
935          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
936          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
937    
938          result.Add("INSTRUMENT_FILE",          // convert the filename into the correct encoding as defined for LSCP
939                     (InstrumentFileName != "NONE" && InstrumentFileName != "") ?          // (especially in terms of special characters -> escape sequences)
940                          Path::fromPosix(InstrumentFileName).toLscp() : // TODO: assuming POSIX          if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
941                          InstrumentFileName  #if WIN32
942          );              InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
943    #else
944                // assuming POSIX
945                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
946    #endif
947            }
948    
949            result.Add("INSTRUMENT_FILE", InstrumentFileName);
950          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
951          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
952          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
# Line 1825  String LSCPServer::GetMidiInstrumentMapp Line 1890  String LSCPServer::GetMidiInstrumentMapp
1890          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);
1891          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");
1892          else { // found          else { // found
1893    
1894                // convert the filename into the correct encoding as defined for LSCP
1895                // (especially in terms of special characters -> escape sequences)
1896    #if WIN32
1897                const String instrumentFileName = Path::fromWindows(iter->second.InstrumentFile).toLscp();
1898    #else
1899                // assuming POSIX
1900                const String instrumentFileName = Path::fromPosix(iter->second.InstrumentFile).toLscp();
1901    #endif
1902    
1903              result.Add("NAME", _escapeLscpResponse(iter->second.Name));              result.Add("NAME", _escapeLscpResponse(iter->second.Name));
1904              result.Add("ENGINE_NAME", iter->second.EngineName);              result.Add("ENGINE_NAME", iter->second.EngineName);
1905              result.Add("INSTRUMENT_FILE", Path::fromPosix(iter->second.InstrumentFile).toLscp()); //TODO: assuming POSIX              result.Add("INSTRUMENT_FILE", instrumentFileName);
1906              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);
1907              String instrumentName;              String instrumentName;
1908              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);
# Line 2278  String LSCPServer::GetServerInfo() { Line 2353  String LSCPServer::GetServerInfo() {
2353  }  }
2354    
2355  /**  /**
2356     * Will be called by the parser to return the current number of all active streams.
2357     */
2358    String LSCPServer::GetTotalStreamCount() {
2359        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2360        LSCPResultSet result;
2361        result.Add(pSampler->GetDiskStreamCount());
2362        return result.Produce();
2363    }
2364    
2365    /**
2366   * Will be called by the parser to return the current number of all active voices.   * Will be called by the parser to return the current number of all active voices.
2367   */   */
2368  String LSCPServer::GetTotalVoiceCount() {  String LSCPServer::GetTotalVoiceCount() {
# Line 2315  String LSCPServer::SetGlobalVolume(doubl Line 2400  String LSCPServer::SetGlobalVolume(doubl
2400      return result.Produce();      return result.Produce();
2401  }  }
2402    
2403    String LSCPServer::GetFileInstruments(String Filename) {
2404        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2405        LSCPResultSet result;
2406        try {
2407            VerifyFile(Filename);
2408        } catch (Exception e) {
2409            result.Error(e);
2410            return result.Produce();
2411        }
2412        // try to find a sampler engine that can handle the file
2413        bool bFound = false;
2414        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2415        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2416            Engine* pEngine = NULL;
2417            try {
2418                pEngine = EngineFactory::Create(engineTypes[i]);
2419                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2420                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2421                if (pManager) {
2422                    std::vector<InstrumentManager::instrument_id_t> IDs =
2423                        pManager->GetInstrumentFileContent(Filename);
2424                    // return the amount of instruments in the file
2425                    result.Add(IDs.size());
2426                    // no more need to ask other engine types
2427                    bFound = true;
2428                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2429            } catch (Exception e) {
2430                // NOOP, as exception is thrown if engine doesn't support file
2431            }
2432            if (pEngine) EngineFactory::Destroy(pEngine);
2433        }
2434    
2435        if (!bFound) result.Error("Unknown file format");
2436        return result.Produce();
2437    }
2438    
2439    String LSCPServer::ListFileInstruments(String Filename) {
2440        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2441        LSCPResultSet result;
2442        try {
2443            VerifyFile(Filename);
2444        } catch (Exception e) {
2445            result.Error(e);
2446            return result.Produce();
2447        }
2448        // try to find a sampler engine that can handle the file
2449        bool bFound = false;
2450        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2451        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2452            Engine* pEngine = NULL;
2453            try {
2454                pEngine = EngineFactory::Create(engineTypes[i]);
2455                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2456                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2457                if (pManager) {
2458                    std::vector<InstrumentManager::instrument_id_t> IDs =
2459                        pManager->GetInstrumentFileContent(Filename);
2460                    // return a list of IDs of the instruments in the file
2461                    String s;
2462                    for (int j = 0; j < IDs.size(); j++) {
2463                        if (s.size()) s += ",";
2464                        s += ToString(IDs[j].Index);
2465                    }
2466                    result.Add(s);
2467                    // no more need to ask other engine types
2468                    bFound = true;
2469                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2470            } catch (Exception e) {
2471                // NOOP, as exception is thrown if engine doesn't support file
2472            }
2473            if (pEngine) EngineFactory::Destroy(pEngine);
2474        }
2475    
2476        if (!bFound) result.Error("Unknown file format");
2477        return result.Produce();
2478    }
2479    
2480    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2481        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2482        LSCPResultSet result;
2483        try {
2484            VerifyFile(Filename);
2485        } catch (Exception e) {
2486            result.Error(e);
2487            return result.Produce();
2488        }
2489        InstrumentManager::instrument_id_t id;
2490        id.FileName = Filename;
2491        id.Index    = InstrumentID;
2492        // try to find a sampler engine that can handle the file
2493        bool bFound = false;
2494        bool bFatalErr = false;
2495        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2496        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2497            Engine* pEngine = NULL;
2498            try {
2499                pEngine = EngineFactory::Create(engineTypes[i]);
2500                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2501                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2502                if (pManager) {
2503                    // check if the instrument index is valid
2504                    // FIXME: this won't work if an engine only supports parts of the instrument file
2505                    std::vector<InstrumentManager::instrument_id_t> IDs =
2506                        pManager->GetInstrumentFileContent(Filename);
2507                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2508                        std::stringstream ss;
2509                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2510                        bFatalErr = true;
2511                        throw Exception(ss.str());
2512                    }
2513                    // get the info of the requested instrument
2514                    InstrumentManager::instrument_info_t info =
2515                        pManager->GetInstrumentInfo(id);
2516                    // return detailed informations about the file
2517                    result.Add("NAME", info.InstrumentName);
2518                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2519                    result.Add("FORMAT_VERSION", info.FormatVersion);
2520                    result.Add("PRODUCT", info.Product);
2521                    result.Add("ARTISTS", info.Artists);
2522                    // no more need to ask other engine types
2523                    bFound = true;
2524                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2525            } catch (Exception e) {
2526                // usually NOOP, as exception is thrown if engine doesn't support file
2527                if (bFatalErr) result.Error(e);
2528            }
2529            if (pEngine) EngineFactory::Destroy(pEngine);
2530        }
2531    
2532        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2533        return result.Produce();
2534    }
2535    
2536    void LSCPServer::VerifyFile(String Filename) {
2537        #if WIN32
2538        WIN32_FIND_DATA win32FileAttributeData;
2539        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2540        if (!res) {
2541            std::stringstream ss;
2542            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2543            throw Exception(ss.str());
2544        }
2545        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2546            throw Exception("Directory is specified");
2547        }
2548        #else    
2549        struct stat statBuf;
2550        int res = stat(Filename.c_str(), &statBuf);
2551        if (res) {
2552            std::stringstream ss;
2553            ss << "Fail to stat `" << Filename << "`: " << strerror(errno);
2554            throw Exception(ss.str());
2555        }
2556    
2557        if (S_ISDIR(statBuf.st_mode)) {
2558            throw Exception("Directory is specified");
2559        }
2560        #endif
2561    }
2562    
2563  /**  /**
2564   * 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
2565   * server for receiving event messages.   * server for receiving event messages.

Legend:
Removed from v.1403  
changed lines
  Added in v.1541

  ViewVC Help
Powered by ViewVC