/[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 1005 by schoenebeck, Fri Dec 29 20:06:14 2006 UTC revision 1541 by iliev, Tue Dec 4 18:09:26 2007 UTC
# Line 3  Line 3 
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6   *   Copyright (C) 2005, 2006 Christian Schoenebeck                        *   *   Copyright (C) 2005 - 2007 Christian Schoenebeck                       *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 24  Line 24 
24  #include "lscpserver.h"  #include "lscpserver.h"
25  #include "lscpresultset.h"  #include "lscpresultset.h"
26  #include "lscpevent.h"  #include "lscpevent.h"
 #include "../common/global.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  # include "sqlite3.h"  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."
36  #endif  #endif
37    
38  #include "../engines/EngineFactory.h"  #include "../engines/EngineFactory.h"
# Line 37  Line 40 
40  #include "../drivers/audio/AudioOutputDeviceFactory.h"  #include "../drivers/audio/AudioOutputDeviceFactory.h"
41  #include "../drivers/midi/MidiInputDeviceFactory.h"  #include "../drivers/midi/MidiInputDeviceFactory.h"
42    
43    
44    /**
45     * Returns a copy of the given string where all special characters are
46     * replaced by LSCP escape sequences ("\xHH"). This function shall be used
47     * to escape LSCP response fields in case the respective response field is
48     * actually defined as using escape sequences in the LSCP specs.
49     *
50     * @e Caution: DO NOT use this function for escaping path based responses,
51     * use the Path class (src/common/Path.h) for this instead!
52     */
53    static String _escapeLscpResponse(String txt) {
54        for (int i = 0; i < txt.length(); i++) {
55            const char c = txt.c_str()[i];
56            if (
57                !(c >= '0' && c <= '9') &&
58                !(c >= 'a' && c <= 'z') &&
59                !(c >= 'A' && c <= 'Z') &&
60                !(c == ' ') && !(c == '!') && !(c == '#') && !(c == '$') &&
61                !(c == '%') && !(c == '&') && !(c == '(') && !(c == ')') &&
62                !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&
63                !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&
64                !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&
65                !(c == '@') && !(c == '[') && !(c == ']') &&
66                !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&
67                !(c == '|') && !(c == '}') && !(c == '~')
68            ) {
69                // convert the "special" character into a "\xHH" LSCP escape sequence
70                char buf[5];
71                snprintf(buf, sizeof(buf), "\\x%02x", static_cast<unsigned char>(c));
72                txt.replace(i, 1, buf);
73                i += 3;
74            }
75        }
76        return txt;
77    }
78    
79  /**  /**
80   * Below are a few static members of the LSCPServer class.   * Below are a few static members of the LSCPServer class.
81   * 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 53  Line 92 
92  fd_set LSCPServer::fdSet;  fd_set LSCPServer::fdSet;
93  int LSCPServer::currentSocket = -1;  int LSCPServer::currentSocket = -1;
94  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();
95    std::vector<yyparse_param_t>::iterator itCurrentSession = std::vector<yyparse_param_t>::iterator();
96  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();
97  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();
98  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 75  LSCPServer::LSCPServer(Sampler* pSampler Line 115  LSCPServer::LSCPServer(Sampler* pSampler
115      LSCPEvent::RegisterEvent(LSCPEvent::event_stream_count, "STREAM_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_stream_count, "STREAM_COUNT");
116      LSCPEvent::RegisterEvent(LSCPEvent::event_buffer_fill, "BUFFER_FILL");      LSCPEvent::RegisterEvent(LSCPEvent::event_buffer_fill, "BUFFER_FILL");
117      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_info, "CHANNEL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_info, "CHANNEL_INFO");
118        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_send_count, "FX_SEND_COUNT");
119        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_send_info, "FX_SEND_INFO");
120      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_count, "MIDI_INSTRUMENT_MAP_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_count, "MIDI_INSTRUMENT_MAP_COUNT");
121      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");
122      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");
123      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");
124        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_count, "DB_INSTRUMENT_DIRECTORY_COUNT");
125        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_info, "DB_INSTRUMENT_DIRECTORY_INFO");
126        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_count, "DB_INSTRUMENT_COUNT");
127        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
128        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");
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) {
145        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
146    }
147    
148    void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
149        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
150    }
151    
152    void LSCPServer::EventHandler::MidiDeviceCountChanged(int NewCount) {
153        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));
154    }
155    
156    void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {
157        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));
158    }
159    
160    void LSCPServer::EventHandler::MidiInstrumentInfoChanged(int MapId, int Bank, int Program) {
161        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_info, MapId, Bank, Program));
162    }
163    
164    void LSCPServer::EventHandler::MidiInstrumentMapCountChanged(int NewCount) {
165        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_count, NewCount));
166    }
167    
168    void LSCPServer::EventHandler::MidiInstrumentMapInfoChanged(int MapId) {
169        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_info, MapId));
170    }
171    
172    void LSCPServer::EventHandler::FxSendCountChanged(int ChannelId, int NewCount) {
173        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_count, ChannelId, NewCount));
174    }
175    
176    void LSCPServer::EventHandler::VoiceCountChanged(int ChannelId, int NewCount) {
177        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_voice_count, ChannelId, NewCount));
178  }  }
179    
180    void LSCPServer::EventHandler::StreamCountChanged(int ChannelId, int NewCount) {
181        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_stream_count, ChannelId, NewCount));
182    }
183    
184    void LSCPServer::EventHandler::BufferFillChanged(int ChannelId, String FillData) {
185        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_buffer_fill, ChannelId, FillData));
186    }
187    
188    void LSCPServer::EventHandler::TotalVoiceCountChanged(int NewCount) {
189        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
197    void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
198        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
199    }
200    
201    void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {
202        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, InstrumentsDb::toEscapedPath(Dir)));
203    }
204    
205    void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {
206        Dir = "'" + InstrumentsDb::toEscapedPath(Dir) + "'";
207        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
208        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));
209    }
210    
211    void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {
212        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, InstrumentsDb::toEscapedPath(Dir)));
213    }
214    
215    void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {
216        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, InstrumentsDb::toEscapedPath(Instr)));
217    }
218    
219    void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {
220        Instr = "'" + InstrumentsDb::toEscapedPath(Instr) + "'";
221        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
222        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));
223    }
224    
225    void LSCPServer::DbInstrumentsEventHandler::JobStatusChanged(int JobId) {
226        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instrs_job_info, JobId));
227    }
228    #endif // HAVE_SQLITE3
229    
230    
231  /**  /**
232   * Blocks the calling thread until the LSCP Server is initialized and   * Blocks the calling thread until the LSCP Server is initialized and
233   * accepting socket connections, if the server is already initialized then   * accepting socket connections, if the server is already initialized then
# Line 103  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 116  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 129  int LSCPServer::Main() { Line 282  int LSCPServer::Main() {
282      listen(hSocket, 1);      listen(hSocket, 1);
283      Initialized.Set(true);      Initialized.Set(true);
284    
285        // Registering event listeners
286        pSampler->AddChannelCountListener(&eventHandler);
287        pSampler->AddAudioDeviceCountListener(&eventHandler);
288        pSampler->AddMidiDeviceCountListener(&eventHandler);
289        pSampler->AddVoiceCountListener(&eventHandler);
290        pSampler->AddStreamCountListener(&eventHandler);
291        pSampler->AddBufferFillListener(&eventHandler);
292        pSampler->AddTotalStreamCountListener(&eventHandler);
293        pSampler->AddTotalVoiceCountListener(&eventHandler);
294        pSampler->AddFxSendCountListener(&eventHandler);
295        MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
296        MidiInstrumentMapper::AddMidiInstrumentInfoListener(&eventHandler);
297        MidiInstrumentMapper::AddMidiInstrumentMapCountListener(&eventHandler);
298        MidiInstrumentMapper::AddMidiInstrumentMapInfoListener(&eventHandler);
299    #if HAVE_SQLITE3
300        InstrumentsDb::GetInstrumentsDb()->AddInstrumentsDbListener(&dbInstrumentsEventHandler);
301    #endif
302      // now wait for client connections and handle their requests      // now wait for client connections and handle their requests
303      sockaddr_in client;      sockaddr_in client;
304      int length = sizeof(client);      int length = sizeof(client);
# Line 148  int LSCPServer::Main() { Line 318  int LSCPServer::Main() {
318                  if ((*itEngineChannel)->StatusChanged()) {                  if ((*itEngineChannel)->StatusChanged()) {
319                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));
320                  }                  }
321    
322                    for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
323                        FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
324                        if(fxs != NULL && fxs->IsInfoChanged()) {
325                            int chn = (*itEngineChannel)->iSamplerChannelIndex;
326                            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
327                            fxs->SetInfoChanged(false);
328                        }
329                    }
330              }              }
331          }          }
332    
# Line 173  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 185  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 212  int LSCPServer::Main() { Line 403  int LSCPServer::Main() {
403                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
404                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
405                                  currentSocket = (*iter).hSession;  //a hack                                  currentSocket = (*iter).hSession;  //a hack
406                                    itCurrentSession = iter; // another hack
407                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
408                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
409                                      AnswerClient(bufferedCommands[currentSocket]);                                      AnswerClient(bufferedCommands[currentSocket]);
410                                  }                                  }
411                                  int result = yyparse(&(*iter));                                  int result = yyparse(&(*iter));
412                                  currentSocket = -1;     //continuation of a hack                                  currentSocket = -1;     //continuation of a hack
413                                    itCurrentSession = Sessions.end(); // hack as well
414                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
415                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?
416                                          CloseConnection(iter);                                          CloseConnection(iter);
# Line 245  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 310  extern int GetLSCPCommand( void *buf, in Line 507  extern int GetLSCPCommand( void *buf, in
507          return command.size();          return command.size();
508  }  }
509    
510    extern yyparse_param_t* GetCurrentYaccSession() {
511        return &(*itCurrentSession);
512    }
513    
514  /**  /**
515   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
516   * 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 320  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 335  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 373  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 490  String LSCPServer::DestroyMidiInputDevic Line 706  String LSCPServer::DestroyMidiInputDevic
706      return result.Produce();      return result.Produce();
707  }  }
708    
709    EngineChannel* LSCPServer::GetEngineChannel(uint uiSamplerChannel) {
710        SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
711        if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
712    
713        EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
714        if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
715    
716        return pEngineChannel;
717    }
718    
719  /**  /**
720   * Will be called by the parser to load an instrument.   * Will be called by the parser to load an instrument.
721   */   */
# Line 636  String LSCPServer::GetEngineInfo(String Line 862  String LSCPServer::GetEngineInfo(String
862      LockRTNotify();      LockRTNotify();
863      try {      try {
864          Engine* pEngine = EngineFactory::Create(EngineName);          Engine* pEngine = EngineFactory::Create(EngineName);
865          result.Add("DESCRIPTION", pEngine->Description());          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
866          result.Add("VERSION",     pEngine->Version());          result.Add("VERSION",     pEngine->Version());
867          EngineFactory::Destroy(pEngine);          EngineFactory::Destroy(pEngine);
868      }      }
# Line 670  String LSCPServer::GetChannelInfo(uint u Line 896  String LSCPServer::GetChannelInfo(uint u
896          String AudioRouting;          String AudioRouting;
897          int Mute = 0;          int Mute = 0;
898          bool Solo = false;          bool Solo = false;
899          String MidiInstrumentMap;          String MidiInstrumentMap = "NONE";
900    
901          if (pEngineChannel) {          if (pEngineChannel) {
902              EngineName          = pEngineChannel->EngineName();              EngineName          = pEngineChannel->EngineName();
# Line 709  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            // convert the filename into the correct encoding as defined for LSCP
939            // (especially in terms of special characters -> escape sequences)
940            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
941    #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);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
950          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
951          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
952          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
953          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
954          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
# Line 1502  String LSCPServer::SetChannelSolo(bool b Line 1739  String LSCPServer::SetChannelSolo(bool b
1739    
1740          bool oldSolo = pEngineChannel->GetSolo();          bool oldSolo = pEngineChannel->GetSolo();
1741          bool hadSoloChannel = HasSoloChannel();          bool hadSoloChannel = HasSoloChannel();
1742            
1743          pEngineChannel->SetSolo(bSolo);          pEngineChannel->SetSolo(bSolo);
1744            
1745          if(!oldSolo && bSolo) {          if(!oldSolo && bSolo) {
1746              if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);              if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);
1747              if(!hadSoloChannel) MuteNonSoloChannels();              if(!hadSoloChannel) MuteNonSoloChannels();
1748          }          }
1749            
1750          if(oldSolo && !bSolo) {          if(oldSolo && !bSolo) {
1751              if(!HasSoloChannel()) UnmuteChannels();              if(!HasSoloChannel()) UnmuteChannels();
1752              else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);              else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);
# Line 1567  void  LSCPServer::UnmuteChannels() { Line 1804  void  LSCPServer::UnmuteChannels() {
1804      }      }
1805  }  }
1806    
1807  String LSCPServer::AddOrReplaceMIDIInstrumentMapping(uint MidiMapID, uint MidiBank, uint MidiProg, String EngineType, String InstrumentFile, uint InstrumentIndex, float Volume, MidiInstrumentMapper::mode_t LoadMode, String Name) {  String LSCPServer::AddOrReplaceMIDIInstrumentMapping(uint MidiMapID, uint MidiBank, uint MidiProg, String EngineType, String InstrumentFile, uint InstrumentIndex, float Volume, MidiInstrumentMapper::mode_t LoadMode, String Name, bool bModal) {
1808      dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));      dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));
1809    
1810      midi_prog_index_t idx;      midi_prog_index_t idx;
# Line 1585  String LSCPServer::AddOrReplaceMIDIInstr Line 1822  String LSCPServer::AddOrReplaceMIDIInstr
1822    
1823      LSCPResultSet result;      LSCPResultSet result;
1824      try {      try {
1825          // PERSISTENT mapping commands might bloock for a long time, so in          // PERSISTENT mapping commands might block for a long time, so in
1826          // that case we add/replace the mapping in another thread          // that case we add/replace the mapping in another thread in case
1827          bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT);          // the NON_MODAL argument was supplied, non persistent mappings
1828            // should return immediately, so we don't need to do that for them
1829            bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT && !bModal);
1830          MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);          MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);
1831      } catch (Exception e) {      } catch (Exception e) {
1832          result.Error(e);          result.Error(e);
# Line 1651  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              result.Add("NAME", iter->second.Name);  
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));
1904              result.Add("ENGINE_NAME", iter->second.EngineName);              result.Add("ENGINE_NAME", iter->second.EngineName);
1905              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);              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 1666  String LSCPServer::GetMidiInstrumentMapp Line 1915  String LSCPServer::GetMidiInstrumentMapp
1915                  }                  }
1916                  EngineFactory::Destroy(pEngine);                  EngineFactory::Destroy(pEngine);
1917              }              }
1918              result.Add("INSTRUMENT_NAME", instrumentName);              result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
1919              switch (iter->second.LoadMode) {              switch (iter->second.LoadMode) {
1920                  case MidiInstrumentMapper::ON_DEMAND:                  case MidiInstrumentMapper::ON_DEMAND:
1921                      result.Add("LOAD_MODE", "ON_DEMAND");                      result.Add("LOAD_MODE", "ON_DEMAND");
# Line 1698  String LSCPServer::ListMidiInstrumentMap Line 1947  String LSCPServer::ListMidiInstrumentMap
1947          for (; iter != mappings.end(); iter++) {          for (; iter != mappings.end(); iter++) {
1948              if (s.size()) s += ",";              if (s.size()) s += ",";
1949              s += "{" + ToString(MidiMapID) + ","              s += "{" + ToString(MidiMapID) + ","
1950                       + ToString((int(iter->first.midi_bank_msb) << 7) & int(iter->first.midi_bank_lsb)) + ","                       + ToString((int(iter->first.midi_bank_msb) << 7) | int(iter->first.midi_bank_lsb)) + ","
1951                       + ToString(int(iter->first.midi_prog)) + "}";                       + ToString(int(iter->first.midi_prog)) + "}";
1952          }          }
1953          result.Add(s);          result.Add(s);
# Line 1720  String LSCPServer::ListAllMidiInstrument Line 1969  String LSCPServer::ListAllMidiInstrument
1969              for (; iter != mappings.end(); iter++) {              for (; iter != mappings.end(); iter++) {
1970                  if (s.size()) s += ",";                  if (s.size()) s += ",";
1971                  s += "{" + ToString(maps[i]) + ","                  s += "{" + ToString(maps[i]) + ","
1972                           + ToString((int(iter->first.midi_bank_msb) << 7) & int(iter->first.midi_bank_lsb)) + ","                           + ToString((int(iter->first.midi_bank_msb) << 7) | int(iter->first.midi_bank_lsb)) + ","
1973                           + ToString(int(iter->first.midi_prog)) + "}";                           + ToString(int(iter->first.midi_prog)) + "}";
1974              }              }
1975          }          }
# Line 1821  String LSCPServer::GetMidiInstrumentMap( Line 2070  String LSCPServer::GetMidiInstrumentMap(
2070      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2071      LSCPResultSet result;      LSCPResultSet result;
2072      try {      try {
2073          result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID));          result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2074            result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2075      } catch (Exception e) {      } catch (Exception e) {
2076          result.Error(e);          result.Error(e);
2077      }      }
# Line 1870  String LSCPServer::CreateFxSend(uint uiS Line 2120  String LSCPServer::CreateFxSend(uint uiS
2120      dmsg(2,("LSCPServer: CreateFxSend()\n"));      dmsg(2,("LSCPServer: CreateFxSend()\n"));
2121      LSCPResultSet result;      LSCPResultSet result;
2122      try {      try {
2123          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");  
2124    
2125          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2126          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)");
# Line 1890  String LSCPServer::DestroyFxSend(uint ui Line 2136  String LSCPServer::DestroyFxSend(uint ui
2136      dmsg(2,("LSCPServer: DestroyFxSend()\n"));      dmsg(2,("LSCPServer: DestroyFxSend()\n"));
2137      LSCPResultSet result;      LSCPResultSet result;
2138      try {      try {
2139          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");  
2140    
2141          FxSend* pFxSend = NULL;          FxSend* pFxSend = NULL;
2142          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
# Line 1915  String LSCPServer::GetFxSends(uint uiSam Line 2157  String LSCPServer::GetFxSends(uint uiSam
2157      dmsg(2,("LSCPServer: GetFxSends()\n"));      dmsg(2,("LSCPServer: GetFxSends()\n"));
2158      LSCPResultSet result;      LSCPResultSet result;
2159      try {      try {
2160          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");  
2161    
2162          result.Add(pEngineChannel->GetFxSendCount());          result.Add(pEngineChannel->GetFxSendCount());
2163      } catch (Exception e) {      } catch (Exception e) {
# Line 1933  String LSCPServer::ListFxSends(uint uiSa Line 2171  String LSCPServer::ListFxSends(uint uiSa
2171      LSCPResultSet result;      LSCPResultSet result;
2172      String list;      String list;
2173      try {      try {
2174          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");  
2175    
2176          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2177              FxSend* pFxSend = pEngineChannel->GetFxSend(i);              FxSend* pFxSend = pEngineChannel->GetFxSend(i);
# Line 1951  String LSCPServer::ListFxSends(uint uiSa Line 2185  String LSCPServer::ListFxSends(uint uiSa
2185      return result.Produce();      return result.Produce();
2186  }  }
2187    
2188    FxSend* LSCPServer::GetFxSend(uint uiSamplerChannel, uint FxSendID) {
2189        EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2190    
2191        FxSend* pFxSend = NULL;
2192        for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2193            if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2194                pFxSend = pEngineChannel->GetFxSend(i);
2195                break;
2196            }
2197        }
2198        if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2199        return pFxSend;
2200    }
2201    
2202  String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {  String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {
2203      dmsg(2,("LSCPServer: GetFxSendInfo()\n"));      dmsg(2,("LSCPServer: GetFxSendInfo()\n"));
2204      LSCPResultSet result;      LSCPResultSet result;
2205      try {      try {
2206          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2207          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");  
   
         FxSend* pFxSend = NULL;  
         for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {  
             if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {  
                 pFxSend = pEngineChannel->GetFxSend(i);  
                 break;  
             }  
         }  
         if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");  
2208    
2209          // gather audio routing informations          // gather audio routing informations
2210          String AudioRouting;          String AudioRouting;
# Line 1978  String LSCPServer::GetFxSendInfo(uint ui Line 2214  String LSCPServer::GetFxSendInfo(uint ui
2214          }          }
2215    
2216          // success          // success
2217          result.Add("NAME", pFxSend->Name());          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2218            result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2219            result.Add("LEVEL", ToString(pFxSend->Level()));
2220          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
2221      } catch (Exception e) {      } catch (Exception e) {
2222          result.Error(e);          result.Error(e);
# Line 1986  String LSCPServer::GetFxSendInfo(uint ui Line 2224  String LSCPServer::GetFxSendInfo(uint ui
2224      return result.Produce();      return result.Produce();
2225  }  }
2226    
2227    String LSCPServer::SetFxSendName(uint uiSamplerChannel, uint FxSendID, String Name) {
2228        dmsg(2,("LSCPServer: SetFxSendName()\n"));
2229        LSCPResultSet result;
2230        try {
2231            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2232    
2233            pFxSend->SetName(Name);
2234            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2235        } catch (Exception e) {
2236            result.Error(e);
2237        }
2238        return result.Produce();
2239    }
2240    
2241  String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {  String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {
2242      dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));      dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));
2243      LSCPResultSet result;      LSCPResultSet result;
2244      try {      try {
2245          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
2246    
2247          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();          pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);
2248          if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2249        } catch (Exception e) {
2250            result.Error(e);
2251        }
2252        return result.Produce();
2253    }
2254    
2255          FxSend* pFxSend = NULL;  String LSCPServer::SetFxSendMidiController(uint uiSamplerChannel, uint FxSendID, uint MidiController) {
2256          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {      dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));
2257              if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {      LSCPResultSet result;
2258                  pFxSend = pEngineChannel->GetFxSend(i);      try {
2259                  break;          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
             }  
         }  
         if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");  
2260    
2261          pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);          pFxSend->SetMidiController(MidiController);
2262            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2263        } catch (Exception e) {
2264            result.Error(e);
2265        }
2266        return result.Produce();
2267    }
2268    
2269    String LSCPServer::SetFxSendLevel(uint uiSamplerChannel, uint FxSendID, double dLevel) {
2270        dmsg(2,("LSCPServer: SetFxSendLevel()\n"));
2271        LSCPResultSet result;
2272        try {
2273            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2274    
2275            pFxSend->SetLevel((float)dLevel);
2276            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2277        } catch (Exception e) {
2278            result.Error(e);
2279        }
2280        return result.Produce();
2281    }
2282    
2283    String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2284        dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2285        LSCPResultSet result;
2286        try {
2287            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
2288            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
2289            EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
2290            if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
2291            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2292            Engine* pEngine = pEngineChannel->GetEngine();
2293            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2294            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2295            InstrumentManager::instrument_id_t instrumentID;
2296            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2297            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2298            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2299      } catch (Exception e) {      } catch (Exception e) {
2300          result.Error(e);          result.Error(e);
2301      }      }
# Line 2047  String LSCPServer::ResetSampler() { Line 2337  String LSCPServer::ResetSampler() {
2337   */   */
2338  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
2339      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
2340        const std::string description =
2341            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2342      LSCPResultSet result;      LSCPResultSet result;
2343      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
2344      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
2345      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2346    #if HAVE_SQLITE3
2347        result.Add("INSTRUMENTS_DB_SUPPORT", "yes");
2348    #else
2349        result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2350    #endif
2351    
2352        return result.Produce();
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();      return result.Produce();
2363  }  }
2364    
# Line 2085  String LSCPServer::SetGlobalVolume(doubl Line 2393  String LSCPServer::SetGlobalVolume(doubl
2393      try {      try {
2394          if (dVolume < 0) throw Exception("Volume may not be negative");          if (dVolume < 0) throw Exception("Volume may not be negative");
2395          GLOBAL_VOLUME = dVolume; // see common/global.cpp          GLOBAL_VOLUME = dVolume; // see common/global.cpp
2396            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
2397        } catch (Exception e) {
2398            result.Error(e);
2399        }
2400        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) {      } catch (Exception e) {
2445          result.Error(e);          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();      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.
# Line 2117  String LSCPServer::UnsubscribeNotificati Line 2586  String LSCPServer::UnsubscribeNotificati
2586      return result.Produce();      return result.Produce();
2587  }  }
2588    
2589  static int select_callback(void * lscpResultSet, int argc,  String LSCPServer::AddDbInstrumentDirectory(String Dir) {
2590                          char **argv, char **azColName)      dmsg(2,("LSCPServer: AddDbInstrumentDirectory(Dir=%s)\n", Dir.c_str()));
2591  {      LSCPResultSet result;
2592      LSCPResultSet* resultSet = (LSCPResultSet*) lscpResultSet;  #if HAVE_SQLITE3
2593      resultSet->Add(argc, argv);      try {
2594      return 0;          InstrumentsDb::GetInstrumentsDb()->AddDirectory(Dir);
2595        } catch (Exception e) {
2596             result.Error(e);
2597        }
2598    #else
2599        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2600    #endif
2601        return result.Produce();
2602    }
2603    
2604    String LSCPServer::RemoveDbInstrumentDirectory(String Dir, bool Force) {
2605        dmsg(2,("LSCPServer: RemoveDbInstrumentDirectory(Dir=%s,Force=%d)\n", Dir.c_str(), Force));
2606        LSCPResultSet result;
2607    #if HAVE_SQLITE3
2608        try {
2609            InstrumentsDb::GetInstrumentsDb()->RemoveDirectory(Dir, Force);
2610        } catch (Exception e) {
2611             result.Error(e);
2612        }
2613    #else
2614        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2615    #endif
2616        return result.Produce();
2617    }
2618    
2619    String LSCPServer::GetDbInstrumentDirectoryCount(String Dir, bool Recursive) {
2620        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2621        LSCPResultSet result;
2622    #if HAVE_SQLITE3
2623        try {
2624            result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir, Recursive));
2625        } catch (Exception e) {
2626             result.Error(e);
2627        }
2628    #else
2629        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2630    #endif
2631        return result.Produce();
2632  }  }
2633    
2634  String LSCPServer::QueryDatabase(String query) {  String LSCPServer::GetDbInstrumentDirectories(String Dir, bool Recursive) {
2635        dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2636      LSCPResultSet result;      LSCPResultSet result;
2637  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2638      char* zErrMsg = NULL;      try {
2639      sqlite3 *db;          String list;
2640      String selectStr = "SELECT " + query;          StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir, Recursive);
2641    
2642            for (int i = 0; i < dirs->size(); i++) {
2643                if (list != "") list += ",";
2644                list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2645            }
2646    
2647      int rc = sqlite3_open("linuxsampler.db", &db);          result.Add(list);
2648      if (rc == SQLITE_OK)      } catch (Exception e) {
2649      {           result.Error(e);
             rc = sqlite3_exec(db, selectStr.c_str(), select_callback, &result, &zErrMsg);  
2650      }      }
2651      if ( rc != SQLITE_OK )  #else
2652      {      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2653              result.Error(String(zErrMsg), rc);  #endif
2654        return result.Produce();
2655    }
2656    
2657    String LSCPServer::GetDbInstrumentDirectoryInfo(String Dir) {
2658        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryInfo(Dir=%s)\n", Dir.c_str()));
2659        LSCPResultSet result;
2660    #if HAVE_SQLITE3
2661        try {
2662            DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2663    
2664            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2665            result.Add("CREATED", info.Created);
2666            result.Add("MODIFIED", info.Modified);
2667        } catch (Exception e) {
2668             result.Error(e);
2669      }      }
     sqlite3_close(db);  
2670  #else  #else
2671      result.Error(String("SQLITE3 was not installed when linuxsampler was built. SELECT statement is not available."), 0);      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2672  #endif  #endif
2673      return result.Produce();      return result.Produce();
2674  }  }
2675    
2676    String LSCPServer::SetDbInstrumentDirectoryName(String Dir, String Name) {
2677        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryName(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
2678        LSCPResultSet result;
2679    #if HAVE_SQLITE3
2680        try {
2681            InstrumentsDb::GetInstrumentsDb()->RenameDirectory(Dir, Name);
2682        } catch (Exception e) {
2683             result.Error(e);
2684        }
2685    #else
2686        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2687    #endif
2688        return result.Produce();
2689    }
2690    
2691    String LSCPServer::MoveDbInstrumentDirectory(String Dir, String Dst) {
2692        dmsg(2,("LSCPServer: MoveDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2693        LSCPResultSet result;
2694    #if HAVE_SQLITE3
2695        try {
2696            InstrumentsDb::GetInstrumentsDb()->MoveDirectory(Dir, Dst);
2697        } catch (Exception e) {
2698             result.Error(e);
2699        }
2700    #else
2701        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2702    #endif
2703        return result.Produce();
2704    }
2705    
2706    String LSCPServer::CopyDbInstrumentDirectory(String Dir, String Dst) {
2707        dmsg(2,("LSCPServer: CopyDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2708        LSCPResultSet result;
2709    #if HAVE_SQLITE3
2710        try {
2711            InstrumentsDb::GetInstrumentsDb()->CopyDirectory(Dir, Dst);
2712        } catch (Exception e) {
2713             result.Error(e);
2714        }
2715    #else
2716        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2717    #endif
2718        return result.Produce();
2719    }
2720    
2721    String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {
2722        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
2723        LSCPResultSet result;
2724    #if HAVE_SQLITE3
2725        try {
2726            InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);
2727        } catch (Exception e) {
2728             result.Error(e);
2729        }
2730    #else
2731        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2732    #endif
2733        return result.Produce();
2734    }
2735    
2736    String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
2737        dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
2738        LSCPResultSet result;
2739    #if HAVE_SQLITE3
2740        try {
2741            int id;
2742            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2743            id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
2744            if (bBackground) result = id;
2745        } catch (Exception e) {
2746             result.Error(e);
2747        }
2748    #else
2749        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2750    #endif
2751        return result.Produce();
2752    }
2753    
2754    String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {
2755        dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground));
2756        LSCPResultSet result;
2757    #if HAVE_SQLITE3
2758        try {
2759            int id;
2760            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2761            if (ScanMode.compare("RECURSIVE") == 0) {
2762               id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);
2763            } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
2764               id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);
2765            } else if (ScanMode.compare("FLAT") == 0) {
2766               id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);
2767            } else {
2768                throw Exception("Unknown scan mode: " + ScanMode);
2769            }
2770    
2771            if (bBackground) result = id;
2772        } catch (Exception e) {
2773             result.Error(e);
2774        }
2775    #else
2776        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2777    #endif
2778        return result.Produce();
2779    }
2780    
2781    String LSCPServer::RemoveDbInstrument(String Instr) {
2782        dmsg(2,("LSCPServer: RemoveDbInstrument(Instr=%s)\n", Instr.c_str()));
2783        LSCPResultSet result;
2784    #if HAVE_SQLITE3
2785        try {
2786            InstrumentsDb::GetInstrumentsDb()->RemoveInstrument(Instr);
2787        } catch (Exception e) {
2788             result.Error(e);
2789        }
2790    #else
2791        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2792    #endif
2793        return result.Produce();
2794    }
2795    
2796    String LSCPServer::GetDbInstrumentCount(String Dir, bool Recursive) {
2797        dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2798        LSCPResultSet result;
2799    #if HAVE_SQLITE3
2800        try {
2801            result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir, Recursive));
2802        } catch (Exception e) {
2803             result.Error(e);
2804        }
2805    #else
2806        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2807    #endif
2808        return result.Produce();
2809    }
2810    
2811    String LSCPServer::GetDbInstruments(String Dir, bool Recursive) {
2812        dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2813        LSCPResultSet result;
2814    #if HAVE_SQLITE3
2815        try {
2816            String list;
2817            StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir, Recursive);
2818    
2819            for (int i = 0; i < instrs->size(); i++) {
2820                if (list != "") list += ",";
2821                list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
2822            }
2823    
2824            result.Add(list);
2825        } catch (Exception e) {
2826             result.Error(e);
2827        }
2828    #else
2829        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2830    #endif
2831        return result.Produce();
2832    }
2833    
2834    String LSCPServer::GetDbInstrumentInfo(String Instr) {
2835        dmsg(2,("LSCPServer: GetDbInstrumentInfo(Instr=%s)\n", Instr.c_str()));
2836        LSCPResultSet result;
2837    #if HAVE_SQLITE3
2838        try {
2839            DbInstrument info = InstrumentsDb::GetInstrumentsDb()->GetInstrumentInfo(Instr);
2840    
2841            result.Add("INSTRUMENT_FILE", info.InstrFile);
2842            result.Add("INSTRUMENT_NR", info.InstrNr);
2843            result.Add("FORMAT_FAMILY", info.FormatFamily);
2844            result.Add("FORMAT_VERSION", info.FormatVersion);
2845            result.Add("SIZE", (int)info.Size);
2846            result.Add("CREATED", info.Created);
2847            result.Add("MODIFIED", info.Modified);
2848            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2849            result.Add("IS_DRUM", info.IsDrum);
2850            result.Add("PRODUCT", _escapeLscpResponse(info.Product));
2851            result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
2852            result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
2853        } catch (Exception e) {
2854             result.Error(e);
2855        }
2856    #else
2857        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2858    #endif
2859        return result.Produce();
2860    }
2861    
2862    String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
2863        dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
2864        LSCPResultSet result;
2865    #if HAVE_SQLITE3
2866        try {
2867            ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
2868    
2869            result.Add("FILES_TOTAL", job.FilesTotal);
2870            result.Add("FILES_SCANNED", job.FilesScanned);
2871            result.Add("SCANNING", job.Scanning);
2872            result.Add("STATUS", job.Status);
2873        } catch (Exception e) {
2874             result.Error(e);
2875        }
2876    #else
2877        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2878    #endif
2879        return result.Produce();
2880    }
2881    
2882    String LSCPServer::SetDbInstrumentName(String Instr, String Name) {
2883        dmsg(2,("LSCPServer: SetDbInstrumentName(Instr=%s,Name=%s)\n", Instr.c_str(), Name.c_str()));
2884        LSCPResultSet result;
2885    #if HAVE_SQLITE3
2886        try {
2887            InstrumentsDb::GetInstrumentsDb()->RenameInstrument(Instr, Name);
2888        } catch (Exception e) {
2889             result.Error(e);
2890        }
2891    #else
2892        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2893    #endif
2894        return result.Produce();
2895    }
2896    
2897    String LSCPServer::MoveDbInstrument(String Instr, String Dst) {
2898        dmsg(2,("LSCPServer: MoveDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
2899        LSCPResultSet result;
2900    #if HAVE_SQLITE3
2901        try {
2902            InstrumentsDb::GetInstrumentsDb()->MoveInstrument(Instr, Dst);
2903        } catch (Exception e) {
2904             result.Error(e);
2905        }
2906    #else
2907        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2908    #endif
2909        return result.Produce();
2910    }
2911    
2912    String LSCPServer::CopyDbInstrument(String Instr, String Dst) {
2913        dmsg(2,("LSCPServer: CopyDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
2914        LSCPResultSet result;
2915    #if HAVE_SQLITE3
2916        try {
2917            InstrumentsDb::GetInstrumentsDb()->CopyInstrument(Instr, Dst);
2918        } catch (Exception e) {
2919             result.Error(e);
2920        }
2921    #else
2922        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2923    #endif
2924        return result.Produce();
2925    }
2926    
2927    String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {
2928        dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
2929        LSCPResultSet result;
2930    #if HAVE_SQLITE3
2931        try {
2932            InstrumentsDb::GetInstrumentsDb()->SetInstrumentDescription(Instr, Desc);
2933        } catch (Exception e) {
2934             result.Error(e);
2935        }
2936    #else
2937        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2938    #endif
2939        return result.Produce();
2940    }
2941    
2942    String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
2943        dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
2944        LSCPResultSet result;
2945    #if HAVE_SQLITE3
2946        try {
2947            SearchQuery Query;
2948            std::map<String,String>::iterator iter;
2949            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
2950                if (iter->first.compare("NAME") == 0) {
2951                    Query.Name = iter->second;
2952                } else if (iter->first.compare("CREATED") == 0) {
2953                    Query.SetCreated(iter->second);
2954                } else if (iter->first.compare("MODIFIED") == 0) {
2955                    Query.SetModified(iter->second);
2956                } else if (iter->first.compare("DESCRIPTION") == 0) {
2957                    Query.Description = iter->second;
2958                } else {
2959                    throw Exception("Unknown search criteria: " + iter->first);
2960                }
2961            }
2962    
2963            String list;
2964            StringListPtr pDirectories =
2965                InstrumentsDb::GetInstrumentsDb()->FindDirectories(Dir, &Query, Recursive);
2966    
2967            for (int i = 0; i < pDirectories->size(); i++) {
2968                if (list != "") list += ",";
2969                list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
2970            }
2971    
2972            result.Add(list);
2973        } catch (Exception e) {
2974             result.Error(e);
2975        }
2976    #else
2977        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2978    #endif
2979        return result.Produce();
2980    }
2981    
2982    String LSCPServer::FindDbInstruments(String Dir, std::map<String,String> Parameters, bool Recursive) {
2983        dmsg(2,("LSCPServer: FindDbInstruments(Dir=%s)\n", Dir.c_str()));
2984        LSCPResultSet result;
2985    #if HAVE_SQLITE3
2986        try {
2987            SearchQuery Query;
2988            std::map<String,String>::iterator iter;
2989            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
2990                if (iter->first.compare("NAME") == 0) {
2991                    Query.Name = iter->second;
2992                } else if (iter->first.compare("FORMAT_FAMILIES") == 0) {
2993                    Query.SetFormatFamilies(iter->second);
2994                } else if (iter->first.compare("SIZE") == 0) {
2995                    Query.SetSize(iter->second);
2996                } else if (iter->first.compare("CREATED") == 0) {
2997                    Query.SetCreated(iter->second);
2998                } else if (iter->first.compare("MODIFIED") == 0) {
2999                    Query.SetModified(iter->second);
3000                } else if (iter->first.compare("DESCRIPTION") == 0) {
3001                    Query.Description = iter->second;
3002                } else if (iter->first.compare("IS_DRUM") == 0) {
3003                    if (!strcasecmp(iter->second.c_str(), "true")) {
3004                        Query.InstrType = SearchQuery::DRUM;
3005                    } else {
3006                        Query.InstrType = SearchQuery::CHROMATIC;
3007                    }
3008                } else if (iter->first.compare("PRODUCT") == 0) {
3009                     Query.Product = iter->second;
3010                } else if (iter->first.compare("ARTISTS") == 0) {
3011                     Query.Artists = iter->second;
3012                } else if (iter->first.compare("KEYWORDS") == 0) {
3013                     Query.Keywords = iter->second;
3014                } else {
3015                    throw Exception("Unknown search criteria: " + iter->first);
3016                }
3017            }
3018    
3019            String list;
3020            StringListPtr pInstruments =
3021                InstrumentsDb::GetInstrumentsDb()->FindInstruments(Dir, &Query, Recursive);
3022    
3023            for (int i = 0; i < pInstruments->size(); i++) {
3024                if (list != "") list += ",";
3025                list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
3026            }
3027    
3028            result.Add(list);
3029        } catch (Exception e) {
3030             result.Error(e);
3031        }
3032    #else
3033        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3034    #endif
3035        return result.Produce();
3036    }
3037    
3038    String LSCPServer::FormatInstrumentsDb() {
3039        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3040        LSCPResultSet result;
3041    #if HAVE_SQLITE3
3042        try {
3043            InstrumentsDb::GetInstrumentsDb()->Format();
3044        } catch (Exception e) {
3045             result.Error(e);
3046        }
3047    #else
3048        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3049    #endif
3050        return result.Produce();
3051    }
3052    
3053    
3054  /**  /**
3055   * 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
3056   * mode is enabled, all commands from the client will (immediately) be   * mode is enabled, all commands from the client will (immediately) be

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

  ViewVC Help
Powered by ViewVC