/[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 1551 by schoenebeck, Wed Dec 5 22:05:28 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    
449    void LSCPServer::LockRTNotify() {
450        RTNotifyMutex.Lock();
451    }
452    
453    void LSCPServer::UnlockRTNotify() {
454        RTNotifyMutex.Unlock();
455    }
456    
457  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
458          int subs = 0;          int subs = 0;
459          SubscriptionMutex.Lock();          SubscriptionMutex.Lock();
# Line 310  extern int GetLSCPCommand( void *buf, in Line 515  extern int GetLSCPCommand( void *buf, in
515          return command.size();          return command.size();
516  }  }
517    
518    extern yyparse_param_t* GetCurrentYaccSession() {
519        return &(*itCurrentSession);
520    }
521    
522  /**  /**
523   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
524   * 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 529  bool LSCPServer::GetLSCPCommand( std::ve
529          char c;          char c;
530          int i = 0;          int i = 0;
531          while (true) {          while (true) {
532                    #if defined(WIN32)
533                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
534                    #else
535                  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
536                    #endif
537                  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
538                          CloseConnection(iter);                          CloseConnection(iter);
539                          break;                          break;
# Line 335  bool LSCPServer::GetLSCPCommand( std::ve Line 548  bool LSCPServer::GetLSCPCommand( std::ve
548                          }                          }
549                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
550                  }                  }
551                    #if defined(WIN32)
552                    if (result == SOCKET_ERROR) {
553                        int wsa_lasterror = WSAGetLastError();
554                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
555                                    return false;
556                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
557                            CloseConnection(iter);
558                            break;
559                    }
560                    #else
561                  if (result == -1) {                  if (result == -1) {
562                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
563                                  return false;                                  return false;
# Line 373  bool LSCPServer::GetLSCPCommand( std::ve Line 596  bool LSCPServer::GetLSCPCommand( std::ve
596                          CloseConnection(iter);                          CloseConnection(iter);
597                          break;                          break;
598                  }                  }
599                    #endif
600          }          }
601          return false;          return false;
602  }  }
# Line 490  String LSCPServer::DestroyMidiInputDevic Line 714  String LSCPServer::DestroyMidiInputDevic
714      return result.Produce();      return result.Produce();
715  }  }
716    
717    EngineChannel* LSCPServer::GetEngineChannel(uint uiSamplerChannel) {
718        SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
719        if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
720    
721        EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
722        if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
723    
724        return pEngineChannel;
725    }
726    
727  /**  /**
728   * Will be called by the parser to load an instrument.   * Will be called by the parser to load an instrument.
729   */   */
# Line 636  String LSCPServer::GetEngineInfo(String Line 870  String LSCPServer::GetEngineInfo(String
870      LockRTNotify();      LockRTNotify();
871      try {      try {
872          Engine* pEngine = EngineFactory::Create(EngineName);          Engine* pEngine = EngineFactory::Create(EngineName);
873          result.Add("DESCRIPTION", pEngine->Description());          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
874          result.Add("VERSION",     pEngine->Version());          result.Add("VERSION",     pEngine->Version());
875          EngineFactory::Destroy(pEngine);          EngineFactory::Destroy(pEngine);
876      }      }
# Line 670  String LSCPServer::GetChannelInfo(uint u Line 904  String LSCPServer::GetChannelInfo(uint u
904          String AudioRouting;          String AudioRouting;
905          int Mute = 0;          int Mute = 0;
906          bool Solo = false;          bool Solo = false;
907          String MidiInstrumentMap;          String MidiInstrumentMap = "NONE";
908    
909          if (pEngineChannel) {          if (pEngineChannel) {
910              EngineName          = pEngineChannel->EngineName();              EngineName          = pEngineChannel->EngineName();
# Line 709  String LSCPServer::GetChannelInfo(uint u Line 943  String LSCPServer::GetChannelInfo(uint u
943          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
944          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
945    
946            // convert the filename into the correct encoding as defined for LSCP
947            // (especially in terms of special characters -> escape sequences)
948            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
949    #if WIN32
950                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
951    #else
952                // assuming POSIX
953                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
954    #endif
955            }
956    
957          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
958          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
959          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
960          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
961          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
962          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
# Line 1502  String LSCPServer::SetChannelSolo(bool b Line 1747  String LSCPServer::SetChannelSolo(bool b
1747    
1748          bool oldSolo = pEngineChannel->GetSolo();          bool oldSolo = pEngineChannel->GetSolo();
1749          bool hadSoloChannel = HasSoloChannel();          bool hadSoloChannel = HasSoloChannel();
1750            
1751          pEngineChannel->SetSolo(bSolo);          pEngineChannel->SetSolo(bSolo);
1752            
1753          if(!oldSolo && bSolo) {          if(!oldSolo && bSolo) {
1754              if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);              if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);
1755              if(!hadSoloChannel) MuteNonSoloChannels();              if(!hadSoloChannel) MuteNonSoloChannels();
1756          }          }
1757            
1758          if(oldSolo && !bSolo) {          if(oldSolo && !bSolo) {
1759              if(!HasSoloChannel()) UnmuteChannels();              if(!HasSoloChannel()) UnmuteChannels();
1760              else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);              else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);
# Line 1567  void  LSCPServer::UnmuteChannels() { Line 1812  void  LSCPServer::UnmuteChannels() {
1812      }      }
1813  }  }
1814    
1815  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) {
1816      dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));      dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));
1817    
1818      midi_prog_index_t idx;      midi_prog_index_t idx;
# Line 1585  String LSCPServer::AddOrReplaceMIDIInstr Line 1830  String LSCPServer::AddOrReplaceMIDIInstr
1830    
1831      LSCPResultSet result;      LSCPResultSet result;
1832      try {      try {
1833          // PERSISTENT mapping commands might bloock for a long time, so in          // PERSISTENT mapping commands might block for a long time, so in
1834          // that case we add/replace the mapping in another thread          // that case we add/replace the mapping in another thread in case
1835          bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT);          // the NON_MODAL argument was supplied, non persistent mappings
1836            // should return immediately, so we don't need to do that for them
1837            bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT && !bModal);
1838          MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);          MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);
1839      } catch (Exception e) {      } catch (Exception e) {
1840          result.Error(e);          result.Error(e);
# Line 1651  String LSCPServer::GetMidiInstrumentMapp Line 1898  String LSCPServer::GetMidiInstrumentMapp
1898          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);
1899          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");
1900          else { // found          else { // found
1901              result.Add("NAME", iter->second.Name);  
1902                // convert the filename into the correct encoding as defined for LSCP
1903                // (especially in terms of special characters -> escape sequences)
1904    #if WIN32
1905                const String instrumentFileName = Path::fromWindows(iter->second.InstrumentFile).toLscp();
1906    #else
1907                // assuming POSIX
1908                const String instrumentFileName = Path::fromPosix(iter->second.InstrumentFile).toLscp();
1909    #endif
1910    
1911                result.Add("NAME", _escapeLscpResponse(iter->second.Name));
1912              result.Add("ENGINE_NAME", iter->second.EngineName);              result.Add("ENGINE_NAME", iter->second.EngineName);
1913              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);              result.Add("INSTRUMENT_FILE", instrumentFileName);
1914              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);
1915              String instrumentName;              String instrumentName;
1916              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);
# Line 1666  String LSCPServer::GetMidiInstrumentMapp Line 1923  String LSCPServer::GetMidiInstrumentMapp
1923                  }                  }
1924                  EngineFactory::Destroy(pEngine);                  EngineFactory::Destroy(pEngine);
1925              }              }
1926              result.Add("INSTRUMENT_NAME", instrumentName);              result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
1927              switch (iter->second.LoadMode) {              switch (iter->second.LoadMode) {
1928                  case MidiInstrumentMapper::ON_DEMAND:                  case MidiInstrumentMapper::ON_DEMAND:
1929                      result.Add("LOAD_MODE", "ON_DEMAND");                      result.Add("LOAD_MODE", "ON_DEMAND");
# Line 1698  String LSCPServer::ListMidiInstrumentMap Line 1955  String LSCPServer::ListMidiInstrumentMap
1955          for (; iter != mappings.end(); iter++) {          for (; iter != mappings.end(); iter++) {
1956              if (s.size()) s += ",";              if (s.size()) s += ",";
1957              s += "{" + ToString(MidiMapID) + ","              s += "{" + ToString(MidiMapID) + ","
1958                       + 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)) + ","
1959                       + ToString(int(iter->first.midi_prog)) + "}";                       + ToString(int(iter->first.midi_prog)) + "}";
1960          }          }
1961          result.Add(s);          result.Add(s);
# Line 1720  String LSCPServer::ListAllMidiInstrument Line 1977  String LSCPServer::ListAllMidiInstrument
1977              for (; iter != mappings.end(); iter++) {              for (; iter != mappings.end(); iter++) {
1978                  if (s.size()) s += ",";                  if (s.size()) s += ",";
1979                  s += "{" + ToString(maps[i]) + ","                  s += "{" + ToString(maps[i]) + ","
1980                           + 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)) + ","
1981                           + ToString(int(iter->first.midi_prog)) + "}";                           + ToString(int(iter->first.midi_prog)) + "}";
1982              }              }
1983          }          }
# Line 1821  String LSCPServer::GetMidiInstrumentMap( Line 2078  String LSCPServer::GetMidiInstrumentMap(
2078      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2079      LSCPResultSet result;      LSCPResultSet result;
2080      try {      try {
2081          result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID));          result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2082            result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2083      } catch (Exception e) {      } catch (Exception e) {
2084          result.Error(e);          result.Error(e);
2085      }      }
# Line 1870  String LSCPServer::CreateFxSend(uint uiS Line 2128  String LSCPServer::CreateFxSend(uint uiS
2128      dmsg(2,("LSCPServer: CreateFxSend()\n"));      dmsg(2,("LSCPServer: CreateFxSend()\n"));
2129      LSCPResultSet result;      LSCPResultSet result;
2130      try {      try {
2131          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");  
2132    
2133          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2134          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 2144  String LSCPServer::DestroyFxSend(uint ui
2144      dmsg(2,("LSCPServer: DestroyFxSend()\n"));      dmsg(2,("LSCPServer: DestroyFxSend()\n"));
2145      LSCPResultSet result;      LSCPResultSet result;
2146      try {      try {
2147          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");  
2148    
2149          FxSend* pFxSend = NULL;          FxSend* pFxSend = NULL;
2150          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
# Line 1915  String LSCPServer::GetFxSends(uint uiSam Line 2165  String LSCPServer::GetFxSends(uint uiSam
2165      dmsg(2,("LSCPServer: GetFxSends()\n"));      dmsg(2,("LSCPServer: GetFxSends()\n"));
2166      LSCPResultSet result;      LSCPResultSet result;
2167      try {      try {
2168          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");  
2169    
2170          result.Add(pEngineChannel->GetFxSendCount());          result.Add(pEngineChannel->GetFxSendCount());
2171      } catch (Exception e) {      } catch (Exception e) {
# Line 1933  String LSCPServer::ListFxSends(uint uiSa Line 2179  String LSCPServer::ListFxSends(uint uiSa
2179      LSCPResultSet result;      LSCPResultSet result;
2180      String list;      String list;
2181      try {      try {
2182          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");  
2183    
2184          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2185              FxSend* pFxSend = pEngineChannel->GetFxSend(i);              FxSend* pFxSend = pEngineChannel->GetFxSend(i);
# Line 1951  String LSCPServer::ListFxSends(uint uiSa Line 2193  String LSCPServer::ListFxSends(uint uiSa
2193      return result.Produce();      return result.Produce();
2194  }  }
2195    
2196    FxSend* LSCPServer::GetFxSend(uint uiSamplerChannel, uint FxSendID) {
2197        EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2198    
2199        FxSend* pFxSend = NULL;
2200        for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2201            if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2202                pFxSend = pEngineChannel->GetFxSend(i);
2203                break;
2204            }
2205        }
2206        if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2207        return pFxSend;
2208    }
2209    
2210  String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {  String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {
2211      dmsg(2,("LSCPServer: GetFxSendInfo()\n"));      dmsg(2,("LSCPServer: GetFxSendInfo()\n"));
2212      LSCPResultSet result;      LSCPResultSet result;
2213      try {      try {
2214          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2215          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");  
2216    
2217          // gather audio routing informations          // gather audio routing informations
2218          String AudioRouting;          String AudioRouting;
# Line 1978  String LSCPServer::GetFxSendInfo(uint ui Line 2222  String LSCPServer::GetFxSendInfo(uint ui
2222          }          }
2223    
2224          // success          // success
2225          result.Add("NAME", pFxSend->Name());          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2226            result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2227            result.Add("LEVEL", ToString(pFxSend->Level()));
2228          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
2229      } catch (Exception e) {      } catch (Exception e) {
2230          result.Error(e);          result.Error(e);
# Line 1986  String LSCPServer::GetFxSendInfo(uint ui Line 2232  String LSCPServer::GetFxSendInfo(uint ui
2232      return result.Produce();      return result.Produce();
2233  }  }
2234    
2235    String LSCPServer::SetFxSendName(uint uiSamplerChannel, uint FxSendID, String Name) {
2236        dmsg(2,("LSCPServer: SetFxSendName()\n"));
2237        LSCPResultSet result;
2238        try {
2239            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2240    
2241            pFxSend->SetName(Name);
2242            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2243        } catch (Exception e) {
2244            result.Error(e);
2245        }
2246        return result.Produce();
2247    }
2248    
2249  String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {  String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {
2250      dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));      dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));
2251      LSCPResultSet result;      LSCPResultSet result;
2252      try {      try {
2253          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
2254    
2255          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();          pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);
2256          if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2257        } catch (Exception e) {
2258            result.Error(e);
2259        }
2260        return result.Produce();
2261    }
2262    
2263          FxSend* pFxSend = NULL;  String LSCPServer::SetFxSendMidiController(uint uiSamplerChannel, uint FxSendID, uint MidiController) {
2264          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {      dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));
2265              if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {      LSCPResultSet result;
2266                  pFxSend = pEngineChannel->GetFxSend(i);      try {
2267                  break;          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
             }  
         }  
         if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");  
2268    
2269          pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);          pFxSend->SetMidiController(MidiController);
2270            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2271        } catch (Exception e) {
2272            result.Error(e);
2273        }
2274        return result.Produce();
2275    }
2276    
2277    String LSCPServer::SetFxSendLevel(uint uiSamplerChannel, uint FxSendID, double dLevel) {
2278        dmsg(2,("LSCPServer: SetFxSendLevel()\n"));
2279        LSCPResultSet result;
2280        try {
2281            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2282    
2283            pFxSend->SetLevel((float)dLevel);
2284            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2285        } catch (Exception e) {
2286            result.Error(e);
2287        }
2288        return result.Produce();
2289    }
2290    
2291    String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2292        dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2293        LSCPResultSet result;
2294        try {
2295            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
2296            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
2297            EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
2298            if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
2299            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2300            Engine* pEngine = pEngineChannel->GetEngine();
2301            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2302            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2303            InstrumentManager::instrument_id_t instrumentID;
2304            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2305            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2306            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2307      } catch (Exception e) {      } catch (Exception e) {
2308          result.Error(e);          result.Error(e);
2309      }      }
# Line 2047  String LSCPServer::ResetSampler() { Line 2345  String LSCPServer::ResetSampler() {
2345   */   */
2346  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
2347      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
2348        const std::string description =
2349            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2350      LSCPResultSet result;      LSCPResultSet result;
2351      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
2352      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
2353      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2354    #if HAVE_SQLITE3
2355        result.Add("INSTRUMENTS_DB_SUPPORT", "yes");
2356    #else
2357        result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2358    #endif
2359    
2360        return result.Produce();
2361    }
2362    
2363    /**
2364     * Will be called by the parser to return the current number of all active streams.
2365     */
2366    String LSCPServer::GetTotalStreamCount() {
2367        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2368        LSCPResultSet result;
2369        result.Add(pSampler->GetDiskStreamCount());
2370      return result.Produce();      return result.Produce();
2371  }  }
2372    
# Line 2085  String LSCPServer::SetGlobalVolume(doubl Line 2401  String LSCPServer::SetGlobalVolume(doubl
2401      try {      try {
2402          if (dVolume < 0) throw Exception("Volume may not be negative");          if (dVolume < 0) throw Exception("Volume may not be negative");
2403          GLOBAL_VOLUME = dVolume; // see common/global.cpp          GLOBAL_VOLUME = dVolume; // see common/global.cpp
2404            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
2405      } catch (Exception e) {      } catch (Exception e) {
2406          result.Error(e);          result.Error(e);
2407      }      }
2408      return result.Produce();      return result.Produce();
2409  }  }
2410    
2411    String LSCPServer::GetFileInstruments(String Filename) {
2412        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2413        LSCPResultSet result;
2414        try {
2415            VerifyFile(Filename);
2416        } catch (Exception e) {
2417            result.Error(e);
2418            return result.Produce();
2419        }
2420        // try to find a sampler engine that can handle the file
2421        bool bFound = false;
2422        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2423        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2424            Engine* pEngine = NULL;
2425            try {
2426                pEngine = EngineFactory::Create(engineTypes[i]);
2427                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2428                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2429                if (pManager) {
2430                    std::vector<InstrumentManager::instrument_id_t> IDs =
2431                        pManager->GetInstrumentFileContent(Filename);
2432                    // return the amount of instruments in the file
2433                    result.Add(IDs.size());
2434                    // no more need to ask other engine types
2435                    bFound = true;
2436                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2437            } catch (Exception e) {
2438                // NOOP, as exception is thrown if engine doesn't support file
2439            }
2440            if (pEngine) EngineFactory::Destroy(pEngine);
2441        }
2442    
2443        if (!bFound) result.Error("Unknown file format");
2444        return result.Produce();
2445    }
2446    
2447    String LSCPServer::ListFileInstruments(String Filename) {
2448        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2449        LSCPResultSet result;
2450        try {
2451            VerifyFile(Filename);
2452        } catch (Exception e) {
2453            result.Error(e);
2454            return result.Produce();
2455        }
2456        // try to find a sampler engine that can handle the file
2457        bool bFound = false;
2458        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2459        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2460            Engine* pEngine = NULL;
2461            try {
2462                pEngine = EngineFactory::Create(engineTypes[i]);
2463                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2464                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2465                if (pManager) {
2466                    std::vector<InstrumentManager::instrument_id_t> IDs =
2467                        pManager->GetInstrumentFileContent(Filename);
2468                    // return a list of IDs of the instruments in the file
2469                    String s;
2470                    for (int j = 0; j < IDs.size(); j++) {
2471                        if (s.size()) s += ",";
2472                        s += ToString(IDs[j].Index);
2473                    }
2474                    result.Add(s);
2475                    // no more need to ask other engine types
2476                    bFound = true;
2477                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2478            } catch (Exception e) {
2479                // NOOP, as exception is thrown if engine doesn't support file
2480            }
2481            if (pEngine) EngineFactory::Destroy(pEngine);
2482        }
2483    
2484        if (!bFound) result.Error("Unknown file format");
2485        return result.Produce();
2486    }
2487    
2488    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2489        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2490        LSCPResultSet result;
2491        try {
2492            VerifyFile(Filename);
2493        } catch (Exception e) {
2494            result.Error(e);
2495            return result.Produce();
2496        }
2497        InstrumentManager::instrument_id_t id;
2498        id.FileName = Filename;
2499        id.Index    = InstrumentID;
2500        // try to find a sampler engine that can handle the file
2501        bool bFound = false;
2502        bool bFatalErr = false;
2503        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2504        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2505            Engine* pEngine = NULL;
2506            try {
2507                pEngine = EngineFactory::Create(engineTypes[i]);
2508                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2509                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2510                if (pManager) {
2511                    // check if the instrument index is valid
2512                    // FIXME: this won't work if an engine only supports parts of the instrument file
2513                    std::vector<InstrumentManager::instrument_id_t> IDs =
2514                        pManager->GetInstrumentFileContent(Filename);
2515                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2516                        std::stringstream ss;
2517                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2518                        bFatalErr = true;
2519                        throw Exception(ss.str());
2520                    }
2521                    // get the info of the requested instrument
2522                    InstrumentManager::instrument_info_t info =
2523                        pManager->GetInstrumentInfo(id);
2524                    // return detailed informations about the file
2525                    result.Add("NAME", info.InstrumentName);
2526                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2527                    result.Add("FORMAT_VERSION", info.FormatVersion);
2528                    result.Add("PRODUCT", info.Product);
2529                    result.Add("ARTISTS", info.Artists);
2530                    // no more need to ask other engine types
2531                    bFound = true;
2532                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2533            } catch (Exception e) {
2534                // usually NOOP, as exception is thrown if engine doesn't support file
2535                if (bFatalErr) result.Error(e);
2536            }
2537            if (pEngine) EngineFactory::Destroy(pEngine);
2538        }
2539    
2540        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2541        return result.Produce();
2542    }
2543    
2544    void LSCPServer::VerifyFile(String Filename) {
2545        #if WIN32
2546        WIN32_FIND_DATA win32FileAttributeData;
2547        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2548        if (!res) {
2549            std::stringstream ss;
2550            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2551            throw Exception(ss.str());
2552        }
2553        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2554            throw Exception("Directory is specified");
2555        }
2556        #else
2557        struct stat statBuf;
2558        int res = stat(Filename.c_str(), &statBuf);
2559        if (res) {
2560            std::stringstream ss;
2561            ss << "Fail to stat `" << Filename << "`: " << strerror(errno);
2562            throw Exception(ss.str());
2563        }
2564    
2565        if (S_ISDIR(statBuf.st_mode)) {
2566            throw Exception("Directory is specified");
2567        }
2568        #endif
2569    }
2570    
2571  /**  /**
2572   * 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
2573   * server for receiving event messages.   * server for receiving event messages.
# Line 2117  String LSCPServer::UnsubscribeNotificati Line 2594  String LSCPServer::UnsubscribeNotificati
2594      return result.Produce();      return result.Produce();
2595  }  }
2596    
2597  static int select_callback(void * lscpResultSet, int argc,  String LSCPServer::AddDbInstrumentDirectory(String Dir) {
2598                          char **argv, char **azColName)      dmsg(2,("LSCPServer: AddDbInstrumentDirectory(Dir=%s)\n", Dir.c_str()));
2599  {      LSCPResultSet result;
2600      LSCPResultSet* resultSet = (LSCPResultSet*) lscpResultSet;  #if HAVE_SQLITE3
2601      resultSet->Add(argc, argv);      try {
2602      return 0;          InstrumentsDb::GetInstrumentsDb()->AddDirectory(Dir);
2603        } catch (Exception e) {
2604             result.Error(e);
2605        }
2606    #else
2607        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2608    #endif
2609        return result.Produce();
2610    }
2611    
2612    String LSCPServer::RemoveDbInstrumentDirectory(String Dir, bool Force) {
2613        dmsg(2,("LSCPServer: RemoveDbInstrumentDirectory(Dir=%s,Force=%d)\n", Dir.c_str(), Force));
2614        LSCPResultSet result;
2615    #if HAVE_SQLITE3
2616        try {
2617            InstrumentsDb::GetInstrumentsDb()->RemoveDirectory(Dir, Force);
2618        } catch (Exception e) {
2619             result.Error(e);
2620        }
2621    #else
2622        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2623    #endif
2624        return result.Produce();
2625    }
2626    
2627    String LSCPServer::GetDbInstrumentDirectoryCount(String Dir, bool Recursive) {
2628        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2629        LSCPResultSet result;
2630    #if HAVE_SQLITE3
2631        try {
2632            result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir, Recursive));
2633        } catch (Exception e) {
2634             result.Error(e);
2635        }
2636    #else
2637        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2638    #endif
2639        return result.Produce();
2640    }
2641    
2642    String LSCPServer::GetDbInstrumentDirectories(String Dir, bool Recursive) {
2643        dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2644        LSCPResultSet result;
2645    #if HAVE_SQLITE3
2646        try {
2647            String list;
2648            StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir, Recursive);
2649    
2650            for (int i = 0; i < dirs->size(); i++) {
2651                if (list != "") list += ",";
2652                list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2653            }
2654    
2655            result.Add(list);
2656        } catch (Exception e) {
2657             result.Error(e);
2658        }
2659    #else
2660        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2661    #endif
2662        return result.Produce();
2663    }
2664    
2665    String LSCPServer::GetDbInstrumentDirectoryInfo(String Dir) {
2666        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryInfo(Dir=%s)\n", Dir.c_str()));
2667        LSCPResultSet result;
2668    #if HAVE_SQLITE3
2669        try {
2670            DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2671    
2672            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2673            result.Add("CREATED", info.Created);
2674            result.Add("MODIFIED", info.Modified);
2675        } catch (Exception e) {
2676             result.Error(e);
2677        }
2678    #else
2679        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2680    #endif
2681        return result.Produce();
2682    }
2683    
2684    String LSCPServer::SetDbInstrumentDirectoryName(String Dir, String Name) {
2685        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryName(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
2686        LSCPResultSet result;
2687    #if HAVE_SQLITE3
2688        try {
2689            InstrumentsDb::GetInstrumentsDb()->RenameDirectory(Dir, Name);
2690        } catch (Exception e) {
2691             result.Error(e);
2692        }
2693    #else
2694        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2695    #endif
2696        return result.Produce();
2697    }
2698    
2699    String LSCPServer::MoveDbInstrumentDirectory(String Dir, String Dst) {
2700        dmsg(2,("LSCPServer: MoveDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2701        LSCPResultSet result;
2702    #if HAVE_SQLITE3
2703        try {
2704            InstrumentsDb::GetInstrumentsDb()->MoveDirectory(Dir, Dst);
2705        } catch (Exception e) {
2706             result.Error(e);
2707        }
2708    #else
2709        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2710    #endif
2711        return result.Produce();
2712    }
2713    
2714    String LSCPServer::CopyDbInstrumentDirectory(String Dir, String Dst) {
2715        dmsg(2,("LSCPServer: CopyDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2716        LSCPResultSet result;
2717    #if HAVE_SQLITE3
2718        try {
2719            InstrumentsDb::GetInstrumentsDb()->CopyDirectory(Dir, Dst);
2720        } catch (Exception e) {
2721             result.Error(e);
2722        }
2723    #else
2724        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2725    #endif
2726        return result.Produce();
2727  }  }
2728    
2729  String LSCPServer::QueryDatabase(String query) {  String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {
2730        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
2731      LSCPResultSet result;      LSCPResultSet result;
2732  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2733      char* zErrMsg = NULL;      try {
2734      sqlite3 *db;          InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);
2735      String selectStr = "SELECT " + query;      } catch (Exception e) {
2736             result.Error(e);
2737        }
2738    #else
2739        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2740    #endif
2741        return result.Produce();
2742    }
2743    
2744      int rc = sqlite3_open("linuxsampler.db", &db);  String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
2745      if (rc == SQLITE_OK)      dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
2746      {      LSCPResultSet result;
2747              rc = sqlite3_exec(db, selectStr.c_str(), select_callback, &result, &zErrMsg);  #if HAVE_SQLITE3
2748        try {
2749            int id;
2750            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2751            id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
2752            if (bBackground) result = id;
2753        } catch (Exception e) {
2754             result.Error(e);
2755      }      }
2756      if ( rc != SQLITE_OK )  #else
2757      {      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2758              result.Error(String(zErrMsg), rc);  #endif
2759        return result.Produce();
2760    }
2761    
2762    String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {
2763        dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground));
2764        LSCPResultSet result;
2765    #if HAVE_SQLITE3
2766        try {
2767            int id;
2768            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2769            if (ScanMode.compare("RECURSIVE") == 0) {
2770               id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);
2771            } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
2772               id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);
2773            } else if (ScanMode.compare("FLAT") == 0) {
2774               id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);
2775            } else {
2776                throw Exception("Unknown scan mode: " + ScanMode);
2777            }
2778    
2779            if (bBackground) result = id;
2780        } catch (Exception e) {
2781             result.Error(e);
2782      }      }
     sqlite3_close(db);  
2783  #else  #else
2784      result.Error(String("SQLITE3 was not installed when linuxsampler was built. SELECT statement is not available."), 0);      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2785  #endif  #endif
2786      return result.Produce();      return result.Produce();
2787  }  }
2788    
2789    String LSCPServer::RemoveDbInstrument(String Instr) {
2790        dmsg(2,("LSCPServer: RemoveDbInstrument(Instr=%s)\n", Instr.c_str()));
2791        LSCPResultSet result;
2792    #if HAVE_SQLITE3
2793        try {
2794            InstrumentsDb::GetInstrumentsDb()->RemoveInstrument(Instr);
2795        } catch (Exception e) {
2796             result.Error(e);
2797        }
2798    #else
2799        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2800    #endif
2801        return result.Produce();
2802    }
2803    
2804    String LSCPServer::GetDbInstrumentCount(String Dir, bool Recursive) {
2805        dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2806        LSCPResultSet result;
2807    #if HAVE_SQLITE3
2808        try {
2809            result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir, Recursive));
2810        } catch (Exception e) {
2811             result.Error(e);
2812        }
2813    #else
2814        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2815    #endif
2816        return result.Produce();
2817    }
2818    
2819    String LSCPServer::GetDbInstruments(String Dir, bool Recursive) {
2820        dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2821        LSCPResultSet result;
2822    #if HAVE_SQLITE3
2823        try {
2824            String list;
2825            StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir, Recursive);
2826    
2827            for (int i = 0; i < instrs->size(); i++) {
2828                if (list != "") list += ",";
2829                list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
2830            }
2831    
2832            result.Add(list);
2833        } catch (Exception e) {
2834             result.Error(e);
2835        }
2836    #else
2837        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2838    #endif
2839        return result.Produce();
2840    }
2841    
2842    String LSCPServer::GetDbInstrumentInfo(String Instr) {
2843        dmsg(2,("LSCPServer: GetDbInstrumentInfo(Instr=%s)\n", Instr.c_str()));
2844        LSCPResultSet result;
2845    #if HAVE_SQLITE3
2846        try {
2847            DbInstrument info = InstrumentsDb::GetInstrumentsDb()->GetInstrumentInfo(Instr);
2848    
2849            result.Add("INSTRUMENT_FILE", info.InstrFile);
2850            result.Add("INSTRUMENT_NR", info.InstrNr);
2851            result.Add("FORMAT_FAMILY", info.FormatFamily);
2852            result.Add("FORMAT_VERSION", info.FormatVersion);
2853            result.Add("SIZE", (int)info.Size);
2854            result.Add("CREATED", info.Created);
2855            result.Add("MODIFIED", info.Modified);
2856            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2857            result.Add("IS_DRUM", info.IsDrum);
2858            result.Add("PRODUCT", _escapeLscpResponse(info.Product));
2859            result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
2860            result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
2861        } catch (Exception e) {
2862             result.Error(e);
2863        }
2864    #else
2865        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2866    #endif
2867        return result.Produce();
2868    }
2869    
2870    String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
2871        dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
2872        LSCPResultSet result;
2873    #if HAVE_SQLITE3
2874        try {
2875            ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
2876    
2877            result.Add("FILES_TOTAL", job.FilesTotal);
2878            result.Add("FILES_SCANNED", job.FilesScanned);
2879            result.Add("SCANNING", job.Scanning);
2880            result.Add("STATUS", job.Status);
2881        } catch (Exception e) {
2882             result.Error(e);
2883        }
2884    #else
2885        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2886    #endif
2887        return result.Produce();
2888    }
2889    
2890    String LSCPServer::SetDbInstrumentName(String Instr, String Name) {
2891        dmsg(2,("LSCPServer: SetDbInstrumentName(Instr=%s,Name=%s)\n", Instr.c_str(), Name.c_str()));
2892        LSCPResultSet result;
2893    #if HAVE_SQLITE3
2894        try {
2895            InstrumentsDb::GetInstrumentsDb()->RenameInstrument(Instr, Name);
2896        } catch (Exception e) {
2897             result.Error(e);
2898        }
2899    #else
2900        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2901    #endif
2902        return result.Produce();
2903    }
2904    
2905    String LSCPServer::MoveDbInstrument(String Instr, String Dst) {
2906        dmsg(2,("LSCPServer: MoveDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
2907        LSCPResultSet result;
2908    #if HAVE_SQLITE3
2909        try {
2910            InstrumentsDb::GetInstrumentsDb()->MoveInstrument(Instr, Dst);
2911        } catch (Exception e) {
2912             result.Error(e);
2913        }
2914    #else
2915        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2916    #endif
2917        return result.Produce();
2918    }
2919    
2920    String LSCPServer::CopyDbInstrument(String Instr, String Dst) {
2921        dmsg(2,("LSCPServer: CopyDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
2922        LSCPResultSet result;
2923    #if HAVE_SQLITE3
2924        try {
2925            InstrumentsDb::GetInstrumentsDb()->CopyInstrument(Instr, Dst);
2926        } catch (Exception e) {
2927             result.Error(e);
2928        }
2929    #else
2930        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2931    #endif
2932        return result.Produce();
2933    }
2934    
2935    String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {
2936        dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
2937        LSCPResultSet result;
2938    #if HAVE_SQLITE3
2939        try {
2940            InstrumentsDb::GetInstrumentsDb()->SetInstrumentDescription(Instr, Desc);
2941        } catch (Exception e) {
2942             result.Error(e);
2943        }
2944    #else
2945        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2946    #endif
2947        return result.Produce();
2948    }
2949    
2950    String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
2951        dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
2952        LSCPResultSet result;
2953    #if HAVE_SQLITE3
2954        try {
2955            SearchQuery Query;
2956            std::map<String,String>::iterator iter;
2957            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
2958                if (iter->first.compare("NAME") == 0) {
2959                    Query.Name = iter->second;
2960                } else if (iter->first.compare("CREATED") == 0) {
2961                    Query.SetCreated(iter->second);
2962                } else if (iter->first.compare("MODIFIED") == 0) {
2963                    Query.SetModified(iter->second);
2964                } else if (iter->first.compare("DESCRIPTION") == 0) {
2965                    Query.Description = iter->second;
2966                } else {
2967                    throw Exception("Unknown search criteria: " + iter->first);
2968                }
2969            }
2970    
2971            String list;
2972            StringListPtr pDirectories =
2973                InstrumentsDb::GetInstrumentsDb()->FindDirectories(Dir, &Query, Recursive);
2974    
2975            for (int i = 0; i < pDirectories->size(); i++) {
2976                if (list != "") list += ",";
2977                list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
2978            }
2979    
2980            result.Add(list);
2981        } catch (Exception e) {
2982             result.Error(e);
2983        }
2984    #else
2985        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2986    #endif
2987        return result.Produce();
2988    }
2989    
2990    String LSCPServer::FindDbInstruments(String Dir, std::map<String,String> Parameters, bool Recursive) {
2991        dmsg(2,("LSCPServer: FindDbInstruments(Dir=%s)\n", Dir.c_str()));
2992        LSCPResultSet result;
2993    #if HAVE_SQLITE3
2994        try {
2995            SearchQuery Query;
2996            std::map<String,String>::iterator iter;
2997            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
2998                if (iter->first.compare("NAME") == 0) {
2999                    Query.Name = iter->second;
3000                } else if (iter->first.compare("FORMAT_FAMILIES") == 0) {
3001                    Query.SetFormatFamilies(iter->second);
3002                } else if (iter->first.compare("SIZE") == 0) {
3003                    Query.SetSize(iter->second);
3004                } else if (iter->first.compare("CREATED") == 0) {
3005                    Query.SetCreated(iter->second);
3006                } else if (iter->first.compare("MODIFIED") == 0) {
3007                    Query.SetModified(iter->second);
3008                } else if (iter->first.compare("DESCRIPTION") == 0) {
3009                    Query.Description = iter->second;
3010                } else if (iter->first.compare("IS_DRUM") == 0) {
3011                    if (!strcasecmp(iter->second.c_str(), "true")) {
3012                        Query.InstrType = SearchQuery::DRUM;
3013                    } else {
3014                        Query.InstrType = SearchQuery::CHROMATIC;
3015                    }
3016                } else if (iter->first.compare("PRODUCT") == 0) {
3017                     Query.Product = iter->second;
3018                } else if (iter->first.compare("ARTISTS") == 0) {
3019                     Query.Artists = iter->second;
3020                } else if (iter->first.compare("KEYWORDS") == 0) {
3021                     Query.Keywords = iter->second;
3022                } else {
3023                    throw Exception("Unknown search criteria: " + iter->first);
3024                }
3025            }
3026    
3027            String list;
3028            StringListPtr pInstruments =
3029                InstrumentsDb::GetInstrumentsDb()->FindInstruments(Dir, &Query, Recursive);
3030    
3031            for (int i = 0; i < pInstruments->size(); i++) {
3032                if (list != "") list += ",";
3033                list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
3034            }
3035    
3036            result.Add(list);
3037        } catch (Exception e) {
3038             result.Error(e);
3039        }
3040    #else
3041        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3042    #endif
3043        return result.Produce();
3044    }
3045    
3046    String LSCPServer::FormatInstrumentsDb() {
3047        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3048        LSCPResultSet result;
3049    #if HAVE_SQLITE3
3050        try {
3051            InstrumentsDb::GetInstrumentsDb()->Format();
3052        } catch (Exception e) {
3053             result.Error(e);
3054        }
3055    #else
3056        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3057    #endif
3058        return result.Produce();
3059    }
3060    
3061    
3062  /**  /**
3063   * 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
3064   * 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.1551

  ViewVC Help
Powered by ViewVC