/[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 1535 by iliev, Mon Dec 3 13:59:03 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    #else
30  #include <fcntl.h>  #include <fcntl.h>
31    #endif
32    
33  #if HAVE_SQLITE3  #if ! HAVE_SQLITE3
34  # include "sqlite3.h"  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."
35  #endif  #endif
36    
37  #include "../engines/EngineFactory.h"  #include "../engines/EngineFactory.h"
# Line 37  Line 39 
39  #include "../drivers/audio/AudioOutputDeviceFactory.h"  #include "../drivers/audio/AudioOutputDeviceFactory.h"
40  #include "../drivers/midi/MidiInputDeviceFactory.h"  #include "../drivers/midi/MidiInputDeviceFactory.h"
41    
42    
43    /**
44     * Returns a copy of the given string where all special characters are
45     * replaced by LSCP escape sequences ("\xHH"). This function shall be used
46     * to escape LSCP response fields in case the respective response field is
47     * actually defined as using escape sequences in the LSCP specs.
48     *
49     * @e Caution: DO NOT use this function for escaping path based responses,
50     * use the Path class (src/common/Path.h) for this instead!
51     */
52    static String _escapeLscpResponse(String txt) {
53        for (int i = 0; i < txt.length(); i++) {
54            const char c = txt.c_str()[i];
55            if (
56                !(c >= '0' && c <= '9') &&
57                !(c >= 'a' && c <= 'z') &&
58                !(c >= 'A' && c <= 'Z') &&
59                !(c == ' ') && !(c == '!') && !(c == '#') && !(c == '$') &&
60                !(c == '%') && !(c == '&') && !(c == '(') && !(c == ')') &&
61                !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&
62                !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&
63                !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&
64                !(c == '@') && !(c == '[') && !(c == ']') &&
65                !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&
66                !(c == '|') && !(c == '}') && !(c == '~')
67            ) {
68                // convert the "special" character into a "\xHH" LSCP escape sequence
69                char buf[5];
70                snprintf(buf, sizeof(buf), "\\x%02x", static_cast<unsigned char>(c));
71                txt.replace(i, 1, buf);
72                i += 3;
73            }
74        }
75        return txt;
76    }
77    
78  /**  /**
79   * Below are a few static members of the LSCPServer class.   * Below are a few static members of the LSCPServer class.
80   * The big assumption here is that LSCPServer is going to remain a singleton.   * The big assumption here is that LSCPServer is going to remain a singleton.
# Line 53  Line 91 
91  fd_set LSCPServer::fdSet;  fd_set LSCPServer::fdSet;
92  int LSCPServer::currentSocket = -1;  int LSCPServer::currentSocket = -1;
93  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();
94    std::vector<yyparse_param_t>::iterator itCurrentSession = std::vector<yyparse_param_t>::iterator();
95  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();
96  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();
97  std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions = std::map< LSCPEvent::event_t, std::list<int> >();  std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions = std::map< LSCPEvent::event_t, std::list<int> >();
# Line 75  LSCPServer::LSCPServer(Sampler* pSampler Line 114  LSCPServer::LSCPServer(Sampler* pSampler
114      LSCPEvent::RegisterEvent(LSCPEvent::event_stream_count, "STREAM_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_stream_count, "STREAM_COUNT");
115      LSCPEvent::RegisterEvent(LSCPEvent::event_buffer_fill, "BUFFER_FILL");      LSCPEvent::RegisterEvent(LSCPEvent::event_buffer_fill, "BUFFER_FILL");
116      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_info, "CHANNEL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_info, "CHANNEL_INFO");
117        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_send_count, "FX_SEND_COUNT");
118        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_send_info, "FX_SEND_INFO");
119      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_count, "MIDI_INSTRUMENT_MAP_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_count, "MIDI_INSTRUMENT_MAP_COUNT");
120      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");
121      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");
122      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");
123        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_count, "DB_INSTRUMENT_DIRECTORY_COUNT");
124        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_info, "DB_INSTRUMENT_DIRECTORY_INFO");
125        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_count, "DB_INSTRUMENT_COUNT");
126        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
127        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
128      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
129      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
130        LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
131      hSocket = -1;      hSocket = -1;
132  }  }
133    
134  LSCPServer::~LSCPServer() {  LSCPServer::~LSCPServer() {
135    #if defined(WIN32)
136        if (hSocket >= 0) closesocket(hSocket);
137    #else
138      if (hSocket >= 0) close(hSocket);      if (hSocket >= 0) close(hSocket);
139    #endif
140    }
141    
142    void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
143        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
144    }
145    
146    void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
147        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
148    }
149    
150    void LSCPServer::EventHandler::MidiDeviceCountChanged(int NewCount) {
151        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));
152    }
153    
154    void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {
155        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));
156    }
157    
158    void LSCPServer::EventHandler::MidiInstrumentInfoChanged(int MapId, int Bank, int Program) {
159        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_info, MapId, Bank, Program));
160    }
161    
162    void LSCPServer::EventHandler::MidiInstrumentMapCountChanged(int NewCount) {
163        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_count, NewCount));
164    }
165    
166    void LSCPServer::EventHandler::MidiInstrumentMapInfoChanged(int MapId) {
167        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_info, MapId));
168    }
169    
170    void LSCPServer::EventHandler::FxSendCountChanged(int ChannelId, int NewCount) {
171        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_count, ChannelId, NewCount));
172    }
173    
174    void LSCPServer::EventHandler::VoiceCountChanged(int ChannelId, int NewCount) {
175        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_voice_count, ChannelId, NewCount));
176  }  }
177    
178    void LSCPServer::EventHandler::StreamCountChanged(int ChannelId, int NewCount) {
179        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_stream_count, ChannelId, NewCount));
180    }
181    
182    void LSCPServer::EventHandler::BufferFillChanged(int ChannelId, String FillData) {
183        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_buffer_fill, ChannelId, FillData));
184    }
185    
186    void LSCPServer::EventHandler::TotalVoiceCountChanged(int NewCount) {
187        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
188    }
189    
190    #if HAVE_SQLITE3
191    void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
192        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
193    }
194    
195    void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {
196        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, InstrumentsDb::toEscapedPath(Dir)));
197    }
198    
199    void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {
200        Dir = "'" + InstrumentsDb::toEscapedPath(Dir) + "'";
201        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
202        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));
203    }
204    
205    void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {
206        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, InstrumentsDb::toEscapedPath(Dir)));
207    }
208    
209    void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {
210        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, InstrumentsDb::toEscapedPath(Instr)));
211    }
212    
213    void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {
214        Instr = "'" + InstrumentsDb::toEscapedPath(Instr) + "'";
215        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
216        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));
217    }
218    
219    void LSCPServer::DbInstrumentsEventHandler::JobStatusChanged(int JobId) {
220        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instrs_job_info, JobId));
221    }
222    #endif // HAVE_SQLITE3
223    
224    
225  /**  /**
226   * Blocks the calling thread until the LSCP Server is initialized and   * Blocks the calling thread until the LSCP Server is initialized and
227   * 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 237  int LSCPServer::WaitUntilInitialized(lon
237  }  }
238    
239  int LSCPServer::Main() {  int LSCPServer::Main() {
240            #if defined(WIN32)
241            WSADATA wsaData;
242            int iResult;
243            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
244            if (iResult != 0) {
245                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
246                    exit(EXIT_FAILURE);
247            }
248            #endif
249      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
250      if (hSocket < 0) {      if (hSocket < 0) {
251          std::cerr << "LSCPServer: Could not create server socket." << std::endl;          std::cerr << "LSCPServer: Could not create server socket." << std::endl;
# Line 116  int LSCPServer::Main() { Line 259  int LSCPServer::Main() {
259              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
260                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
261                      std::cerr << "gave up!" << std::endl;                      std::cerr << "gave up!" << std::endl;
262                        #if defined(WIN32)
263                        closesocket(hSocket);
264                        #else
265                      close(hSocket);                      close(hSocket);
266                        #endif
267                      //return -1;                      //return -1;
268                      exit(EXIT_FAILURE);                      exit(EXIT_FAILURE);
269                  }                  }
# Line 129  int LSCPServer::Main() { Line 276  int LSCPServer::Main() {
276      listen(hSocket, 1);      listen(hSocket, 1);
277      Initialized.Set(true);      Initialized.Set(true);
278    
279        // Registering event listeners
280        pSampler->AddChannelCountListener(&eventHandler);
281        pSampler->AddAudioDeviceCountListener(&eventHandler);
282        pSampler->AddMidiDeviceCountListener(&eventHandler);
283        pSampler->AddVoiceCountListener(&eventHandler);
284        pSampler->AddStreamCountListener(&eventHandler);
285        pSampler->AddBufferFillListener(&eventHandler);
286        pSampler->AddTotalVoiceCountListener(&eventHandler);
287        pSampler->AddFxSendCountListener(&eventHandler);
288        MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
289        MidiInstrumentMapper::AddMidiInstrumentInfoListener(&eventHandler);
290        MidiInstrumentMapper::AddMidiInstrumentMapCountListener(&eventHandler);
291        MidiInstrumentMapper::AddMidiInstrumentMapInfoListener(&eventHandler);
292    #if HAVE_SQLITE3
293        InstrumentsDb::GetInstrumentsDb()->AddInstrumentsDbListener(&dbInstrumentsEventHandler);
294    #endif
295      // now wait for client connections and handle their requests      // now wait for client connections and handle their requests
296      sockaddr_in client;      sockaddr_in client;
297      int length = sizeof(client);      int length = sizeof(client);
# Line 148  int LSCPServer::Main() { Line 311  int LSCPServer::Main() {
311                  if ((*itEngineChannel)->StatusChanged()) {                  if ((*itEngineChannel)->StatusChanged()) {
312                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));
313                  }                  }
314    
315                    for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
316                        FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
317                        if(fxs != NULL && fxs->IsInfoChanged()) {
318                            int chn = (*itEngineChannel)->iSamplerChannelIndex;
319                            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
320                            fxs->SetInfoChanged(false);
321                        }
322                    }
323              }              }
324          }          }
325    
# Line 173  int LSCPServer::Main() { Line 345  int LSCPServer::Main() {
345                  continue; //Nothing try again                  continue; //Nothing try again
346          if (retval == -1) {          if (retval == -1) {
347                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
348                    #if defined(WIN32)
349                    closesocket(hSocket);
350                    #else
351                  close(hSocket);                  close(hSocket);
352                    #endif
353                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
354          }          }
355    
# Line 185  int LSCPServer::Main() { Line 361  int LSCPServer::Main() {
361                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
362                  }                  }
363    
364                    #if defined(WIN32)
365                    u_long nonblock_io = 1;
366                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
367                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
368                      exit(EXIT_FAILURE);
369                    }
370            #else          
371                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
372                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
373                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
374                  }                  }
375                    #endif
376    
377                  // Parser initialization                  // Parser initialization
378                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 212  int LSCPServer::Main() { Line 396  int LSCPServer::Main() {
396                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
397                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
398                                  currentSocket = (*iter).hSession;  //a hack                                  currentSocket = (*iter).hSession;  //a hack
399                                    itCurrentSession = iter; // another hack
400                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
401                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
402                                      AnswerClient(bufferedCommands[currentSocket]);                                      AnswerClient(bufferedCommands[currentSocket]);
403                                  }                                  }
404                                  int result = yyparse(&(*iter));                                  int result = yyparse(&(*iter));
405                                  currentSocket = -1;     //continuation of a hack                                  currentSocket = -1;     //continuation of a hack
406                                    itCurrentSession = Sessions.end(); // hack as well
407                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
408                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?
409                                          CloseConnection(iter);                                          CloseConnection(iter);
# Line 245  void LSCPServer::CloseConnection( std::v Line 431  void LSCPServer::CloseConnection( std::v
431          NotifyMutex.Lock();          NotifyMutex.Lock();
432          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
433          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
434            #if defined(WIN32)
435            closesocket(socket);
436            #else
437          close(socket);          close(socket);
438            #endif
439          NotifyMutex.Unlock();          NotifyMutex.Unlock();
440  }  }
441    
# Line 310  extern int GetLSCPCommand( void *buf, in Line 500  extern int GetLSCPCommand( void *buf, in
500          return command.size();          return command.size();
501  }  }
502    
503    extern yyparse_param_t* GetCurrentYaccSession() {
504        return &(*itCurrentSession);
505    }
506    
507  /**  /**
508   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
509   * If command is read, it will return true. Otherwise false is returned.   * If command is read, it will return true. Otherwise false is returned.
# Line 320  bool LSCPServer::GetLSCPCommand( std::ve Line 514  bool LSCPServer::GetLSCPCommand( std::ve
514          char c;          char c;
515          int i = 0;          int i = 0;
516          while (true) {          while (true) {
517                    #if defined(WIN32)
518                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
519                    #else
520                  int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now                  int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now
521                    #endif
522                  if (result == 0) { //socket was selected, so 0 here means client has closed the connection                  if (result == 0) { //socket was selected, so 0 here means client has closed the connection
523                          CloseConnection(iter);                          CloseConnection(iter);
524                          break;                          break;
# Line 335  bool LSCPServer::GetLSCPCommand( std::ve Line 533  bool LSCPServer::GetLSCPCommand( std::ve
533                          }                          }
534                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
535                  }                  }
536                    #if defined(WIN32)
537                    if (result == SOCKET_ERROR) {
538                        int wsa_lasterror = WSAGetLastError();
539                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
540                                    return false;
541                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));  
542                            CloseConnection(iter);
543                            break;
544                    }
545                    #else
546                  if (result == -1) {                  if (result == -1) {
547                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
548                                  return false;                                  return false;
# Line 373  bool LSCPServer::GetLSCPCommand( std::ve Line 581  bool LSCPServer::GetLSCPCommand( std::ve
581                          CloseConnection(iter);                          CloseConnection(iter);
582                          break;                          break;
583                  }                  }
584                    #endif
585          }          }
586          return false;          return false;
587  }  }
# Line 490  String LSCPServer::DestroyMidiInputDevic Line 699  String LSCPServer::DestroyMidiInputDevic
699      return result.Produce();      return result.Produce();
700  }  }
701    
702    EngineChannel* LSCPServer::GetEngineChannel(uint uiSamplerChannel) {
703        SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
704        if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
705    
706        EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
707        if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
708    
709        return pEngineChannel;
710    }
711    
712  /**  /**
713   * Will be called by the parser to load an instrument.   * Will be called by the parser to load an instrument.
714   */   */
# Line 636  String LSCPServer::GetEngineInfo(String Line 855  String LSCPServer::GetEngineInfo(String
855      LockRTNotify();      LockRTNotify();
856      try {      try {
857          Engine* pEngine = EngineFactory::Create(EngineName);          Engine* pEngine = EngineFactory::Create(EngineName);
858          result.Add("DESCRIPTION", pEngine->Description());          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
859          result.Add("VERSION",     pEngine->Version());          result.Add("VERSION",     pEngine->Version());
860          EngineFactory::Destroy(pEngine);          EngineFactory::Destroy(pEngine);
861      }      }
# Line 670  String LSCPServer::GetChannelInfo(uint u Line 889  String LSCPServer::GetChannelInfo(uint u
889          String AudioRouting;          String AudioRouting;
890          int Mute = 0;          int Mute = 0;
891          bool Solo = false;          bool Solo = false;
892          String MidiInstrumentMap;          String MidiInstrumentMap = "NONE";
893    
894          if (pEngineChannel) {          if (pEngineChannel) {
895              EngineName          = pEngineChannel->EngineName();              EngineName          = pEngineChannel->EngineName();
# Line 709  String LSCPServer::GetChannelInfo(uint u Line 928  String LSCPServer::GetChannelInfo(uint u
928          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
929          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
930    
931            // convert the filename into the correct encoding as defined for LSCP
932            // (especially in terms of special characters -> escape sequences)
933            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
934    #if WIN32
935                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
936    #else
937                // assuming POSIX
938                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
939    #endif
940            }
941    
942          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
943          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
944          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
945          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
946          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
947          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
# Line 1502  String LSCPServer::SetChannelSolo(bool b Line 1732  String LSCPServer::SetChannelSolo(bool b
1732    
1733          bool oldSolo = pEngineChannel->GetSolo();          bool oldSolo = pEngineChannel->GetSolo();
1734          bool hadSoloChannel = HasSoloChannel();          bool hadSoloChannel = HasSoloChannel();
1735            
1736          pEngineChannel->SetSolo(bSolo);          pEngineChannel->SetSolo(bSolo);
1737            
1738          if(!oldSolo && bSolo) {          if(!oldSolo && bSolo) {
1739              if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);              if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);
1740              if(!hadSoloChannel) MuteNonSoloChannels();              if(!hadSoloChannel) MuteNonSoloChannels();
1741          }          }
1742            
1743          if(oldSolo && !bSolo) {          if(oldSolo && !bSolo) {
1744              if(!HasSoloChannel()) UnmuteChannels();              if(!HasSoloChannel()) UnmuteChannels();
1745              else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);              else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);
# Line 1567  void  LSCPServer::UnmuteChannels() { Line 1797  void  LSCPServer::UnmuteChannels() {
1797      }      }
1798  }  }
1799    
1800  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) {
1801      dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));      dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));
1802    
1803      midi_prog_index_t idx;      midi_prog_index_t idx;
# Line 1585  String LSCPServer::AddOrReplaceMIDIInstr Line 1815  String LSCPServer::AddOrReplaceMIDIInstr
1815    
1816      LSCPResultSet result;      LSCPResultSet result;
1817      try {      try {
1818          // PERSISTENT mapping commands might bloock for a long time, so in          // PERSISTENT mapping commands might block for a long time, so in
1819          // that case we add/replace the mapping in another thread          // that case we add/replace the mapping in another thread in case
1820          bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT);          // the NON_MODAL argument was supplied, non persistent mappings
1821            // should return immediately, so we don't need to do that for them
1822            bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT && !bModal);
1823          MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);          MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);
1824      } catch (Exception e) {      } catch (Exception e) {
1825          result.Error(e);          result.Error(e);
# Line 1651  String LSCPServer::GetMidiInstrumentMapp Line 1883  String LSCPServer::GetMidiInstrumentMapp
1883          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);
1884          if (iter == mappings.end()) result.Error("there is no map entry with that index");          if (iter == mappings.end()) result.Error("there is no map entry with that index");
1885          else { // found          else { // found
1886              result.Add("NAME", iter->second.Name);  
1887                // convert the filename into the correct encoding as defined for LSCP
1888                // (especially in terms of special characters -> escape sequences)
1889    #if WIN32
1890                const String instrumentFileName = Path::fromWindows(iter->second.InstrumentFile).toLscp();
1891    #else
1892                // assuming POSIX
1893                const String instrumentFileName = Path::fromPosix(iter->second.InstrumentFile).toLscp();
1894    #endif
1895    
1896                result.Add("NAME", _escapeLscpResponse(iter->second.Name));
1897              result.Add("ENGINE_NAME", iter->second.EngineName);              result.Add("ENGINE_NAME", iter->second.EngineName);
1898              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);              result.Add("INSTRUMENT_FILE", instrumentFileName);
1899              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);
1900              String instrumentName;              String instrumentName;
1901              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);
# Line 1666  String LSCPServer::GetMidiInstrumentMapp Line 1908  String LSCPServer::GetMidiInstrumentMapp
1908                  }                  }
1909                  EngineFactory::Destroy(pEngine);                  EngineFactory::Destroy(pEngine);
1910              }              }
1911              result.Add("INSTRUMENT_NAME", instrumentName);              result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
1912              switch (iter->second.LoadMode) {              switch (iter->second.LoadMode) {
1913                  case MidiInstrumentMapper::ON_DEMAND:                  case MidiInstrumentMapper::ON_DEMAND:
1914                      result.Add("LOAD_MODE", "ON_DEMAND");                      result.Add("LOAD_MODE", "ON_DEMAND");
# Line 1698  String LSCPServer::ListMidiInstrumentMap Line 1940  String LSCPServer::ListMidiInstrumentMap
1940          for (; iter != mappings.end(); iter++) {          for (; iter != mappings.end(); iter++) {
1941              if (s.size()) s += ",";              if (s.size()) s += ",";
1942              s += "{" + ToString(MidiMapID) + ","              s += "{" + ToString(MidiMapID) + ","
1943                       + 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)) + ","
1944                       + ToString(int(iter->first.midi_prog)) + "}";                       + ToString(int(iter->first.midi_prog)) + "}";
1945          }          }
1946          result.Add(s);          result.Add(s);
# Line 1720  String LSCPServer::ListAllMidiInstrument Line 1962  String LSCPServer::ListAllMidiInstrument
1962              for (; iter != mappings.end(); iter++) {              for (; iter != mappings.end(); iter++) {
1963                  if (s.size()) s += ",";                  if (s.size()) s += ",";
1964                  s += "{" + ToString(maps[i]) + ","                  s += "{" + ToString(maps[i]) + ","
1965                           + 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)) + ","
1966                           + ToString(int(iter->first.midi_prog)) + "}";                           + ToString(int(iter->first.midi_prog)) + "}";
1967              }              }
1968          }          }
# Line 1821  String LSCPServer::GetMidiInstrumentMap( Line 2063  String LSCPServer::GetMidiInstrumentMap(
2063      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2064      LSCPResultSet result;      LSCPResultSet result;
2065      try {      try {
2066          result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID));          result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2067            result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2068      } catch (Exception e) {      } catch (Exception e) {
2069          result.Error(e);          result.Error(e);
2070      }      }
# Line 1870  String LSCPServer::CreateFxSend(uint uiS Line 2113  String LSCPServer::CreateFxSend(uint uiS
2113      dmsg(2,("LSCPServer: CreateFxSend()\n"));      dmsg(2,("LSCPServer: CreateFxSend()\n"));
2114      LSCPResultSet result;      LSCPResultSet result;
2115      try {      try {
2116          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");  
2117    
2118          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2119          if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");          if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");
# Line 1890  String LSCPServer::DestroyFxSend(uint ui Line 2129  String LSCPServer::DestroyFxSend(uint ui
2129      dmsg(2,("LSCPServer: DestroyFxSend()\n"));      dmsg(2,("LSCPServer: DestroyFxSend()\n"));
2130      LSCPResultSet result;      LSCPResultSet result;
2131      try {      try {
2132          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");  
2133    
2134          FxSend* pFxSend = NULL;          FxSend* pFxSend = NULL;
2135          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
# Line 1915  String LSCPServer::GetFxSends(uint uiSam Line 2150  String LSCPServer::GetFxSends(uint uiSam
2150      dmsg(2,("LSCPServer: GetFxSends()\n"));      dmsg(2,("LSCPServer: GetFxSends()\n"));
2151      LSCPResultSet result;      LSCPResultSet result;
2152      try {      try {
2153          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");  
2154    
2155          result.Add(pEngineChannel->GetFxSendCount());          result.Add(pEngineChannel->GetFxSendCount());
2156      } catch (Exception e) {      } catch (Exception e) {
# Line 1933  String LSCPServer::ListFxSends(uint uiSa Line 2164  String LSCPServer::ListFxSends(uint uiSa
2164      LSCPResultSet result;      LSCPResultSet result;
2165      String list;      String list;
2166      try {      try {
2167          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");  
2168    
2169          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2170              FxSend* pFxSend = pEngineChannel->GetFxSend(i);              FxSend* pFxSend = pEngineChannel->GetFxSend(i);
# Line 1951  String LSCPServer::ListFxSends(uint uiSa Line 2178  String LSCPServer::ListFxSends(uint uiSa
2178      return result.Produce();      return result.Produce();
2179  }  }
2180    
2181    FxSend* LSCPServer::GetFxSend(uint uiSamplerChannel, uint FxSendID) {
2182        EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2183    
2184        FxSend* pFxSend = NULL;
2185        for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2186            if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2187                pFxSend = pEngineChannel->GetFxSend(i);
2188                break;
2189            }
2190        }
2191        if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2192        return pFxSend;
2193    }
2194    
2195  String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {  String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {
2196      dmsg(2,("LSCPServer: GetFxSendInfo()\n"));      dmsg(2,("LSCPServer: GetFxSendInfo()\n"));
2197      LSCPResultSet result;      LSCPResultSet result;
2198      try {      try {
2199          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2200          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");  
2201    
2202          // gather audio routing informations          // gather audio routing informations
2203          String AudioRouting;          String AudioRouting;
# Line 1978  String LSCPServer::GetFxSendInfo(uint ui Line 2207  String LSCPServer::GetFxSendInfo(uint ui
2207          }          }
2208    
2209          // success          // success
2210          result.Add("NAME", pFxSend->Name());          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2211            result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2212            result.Add("LEVEL", ToString(pFxSend->Level()));
2213          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
2214      } catch (Exception e) {      } catch (Exception e) {
2215          result.Error(e);          result.Error(e);
# Line 1986  String LSCPServer::GetFxSendInfo(uint ui Line 2217  String LSCPServer::GetFxSendInfo(uint ui
2217      return result.Produce();      return result.Produce();
2218  }  }
2219    
2220    String LSCPServer::SetFxSendName(uint uiSamplerChannel, uint FxSendID, String Name) {
2221        dmsg(2,("LSCPServer: SetFxSendName()\n"));
2222        LSCPResultSet result;
2223        try {
2224            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2225    
2226            pFxSend->SetName(Name);
2227            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2228        } catch (Exception e) {
2229            result.Error(e);
2230        }
2231        return result.Produce();
2232    }
2233    
2234  String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {  String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {
2235      dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));      dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));
2236      LSCPResultSet result;      LSCPResultSet result;
2237      try {      try {
2238          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
2239    
2240          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();          pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);
2241          if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2242        } catch (Exception e) {
2243            result.Error(e);
2244        }
2245        return result.Produce();
2246    }
2247    
2248          FxSend* pFxSend = NULL;  String LSCPServer::SetFxSendMidiController(uint uiSamplerChannel, uint FxSendID, uint MidiController) {
2249          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {      dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));
2250              if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {      LSCPResultSet result;
2251                  pFxSend = pEngineChannel->GetFxSend(i);      try {
2252                  break;          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
             }  
         }  
         if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");  
2253    
2254          pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);          pFxSend->SetMidiController(MidiController);
2255            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2256        } catch (Exception e) {
2257            result.Error(e);
2258        }
2259        return result.Produce();
2260    }
2261    
2262    String LSCPServer::SetFxSendLevel(uint uiSamplerChannel, uint FxSendID, double dLevel) {
2263        dmsg(2,("LSCPServer: SetFxSendLevel()\n"));
2264        LSCPResultSet result;
2265        try {
2266            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2267    
2268            pFxSend->SetLevel((float)dLevel);
2269            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2270        } catch (Exception e) {
2271            result.Error(e);
2272        }
2273        return result.Produce();
2274    }
2275    
2276    String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2277        dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2278        LSCPResultSet result;
2279        try {
2280            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
2281            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
2282            EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
2283            if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
2284            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2285            Engine* pEngine = pEngineChannel->GetEngine();
2286            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2287            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2288            InstrumentManager::instrument_id_t instrumentID;
2289            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2290            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2291            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2292      } catch (Exception e) {      } catch (Exception e) {
2293          result.Error(e);          result.Error(e);
2294      }      }
# Line 2047  String LSCPServer::ResetSampler() { Line 2330  String LSCPServer::ResetSampler() {
2330   */   */
2331  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
2332      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
2333        const std::string description =
2334            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2335      LSCPResultSet result;      LSCPResultSet result;
2336      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
2337      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
2338      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2339    #if HAVE_SQLITE3
2340        result.Add("INSTRUMENTS_DB_SUPPORT", "yes");
2341    #else
2342        result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2343    #endif
2344    
2345      return result.Produce();      return result.Produce();
2346  }  }
2347    
# Line 2085  String LSCPServer::SetGlobalVolume(doubl Line 2376  String LSCPServer::SetGlobalVolume(doubl
2376      try {      try {
2377          if (dVolume < 0) throw Exception("Volume may not be negative");          if (dVolume < 0) throw Exception("Volume may not be negative");
2378          GLOBAL_VOLUME = dVolume; // see common/global.cpp          GLOBAL_VOLUME = dVolume; // see common/global.cpp
2379            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
2380        } catch (Exception e) {
2381            result.Error(e);
2382        }
2383        return result.Produce();
2384    }
2385    
2386    String LSCPServer::GetFileInstruments(String Filename) {
2387        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2388        LSCPResultSet result;
2389        try {
2390            VerifyFile(Filename);
2391        } catch (Exception e) {
2392            result.Error(e);
2393            return result.Produce();
2394        }
2395        // try to find a sampler engine that can handle the file
2396        bool bFound = false;
2397        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2398        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2399            Engine* pEngine = NULL;
2400            try {
2401                pEngine = EngineFactory::Create(engineTypes[i]);
2402                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2403                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2404                if (pManager) {
2405                    std::vector<InstrumentManager::instrument_id_t> IDs =
2406                        pManager->GetInstrumentFileContent(Filename);
2407                    // return the amount of instruments in the file
2408                    result.Add(IDs.size());
2409                    // no more need to ask other engine types
2410                    bFound = true;
2411                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2412            } catch (Exception e) {
2413                // NOOP, as exception is thrown if engine doesn't support file
2414            }
2415            if (pEngine) EngineFactory::Destroy(pEngine);
2416        }
2417    
2418        if (!bFound) result.Error("Unknown file format");
2419        return result.Produce();
2420    }
2421    
2422    String LSCPServer::ListFileInstruments(String Filename) {
2423        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2424        LSCPResultSet result;
2425        try {
2426            VerifyFile(Filename);
2427      } catch (Exception e) {      } catch (Exception e) {
2428          result.Error(e);          result.Error(e);
2429            return result.Produce();
2430        }
2431        // try to find a sampler engine that can handle the file
2432        bool bFound = false;
2433        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2434        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2435            Engine* pEngine = NULL;
2436            try {
2437                pEngine = EngineFactory::Create(engineTypes[i]);
2438                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2439                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2440                if (pManager) {
2441                    std::vector<InstrumentManager::instrument_id_t> IDs =
2442                        pManager->GetInstrumentFileContent(Filename);
2443                    // return a list of IDs of the instruments in the file
2444                    String s;
2445                    for (int j = 0; j < IDs.size(); j++) {
2446                        if (s.size()) s += ",";
2447                        s += ToString(IDs[j].Index);
2448                    }
2449                    result.Add(s);
2450                    // no more need to ask other engine types
2451                    bFound = true;
2452                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2453            } catch (Exception e) {
2454                // NOOP, as exception is thrown if engine doesn't support file
2455            }
2456            if (pEngine) EngineFactory::Destroy(pEngine);
2457      }      }
2458    
2459        if (!bFound) result.Error("Unknown file format");
2460      return result.Produce();      return result.Produce();
2461  }  }
2462    
2463    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2464        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2465        LSCPResultSet result;
2466        try {
2467            VerifyFile(Filename);
2468        } catch (Exception e) {
2469            result.Error(e);
2470            return result.Produce();
2471        }
2472        InstrumentManager::instrument_id_t id;
2473        id.FileName = Filename;
2474        id.Index    = InstrumentID;
2475        // try to find a sampler engine that can handle the file
2476        bool bFound = false;
2477        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2478        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2479            Engine* pEngine = NULL;
2480            try {
2481                pEngine = EngineFactory::Create(engineTypes[i]);
2482                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2483                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2484                if (pManager) {
2485                    InstrumentManager::instrument_info_t info =
2486                        pManager->GetInstrumentInfo(id);
2487                    // return detailed informations about the file
2488                    result.Add("NAME", info.InstrumentName);
2489                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2490                    result.Add("FORMAT_VERSION", info.FormatVersion);
2491                    result.Add("PRODUCT", info.Product);
2492                    result.Add("ARTISTS", info.Artists);
2493                    // no more need to ask other engine types
2494                    bFound = true;
2495                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2496            } catch (Exception e) {
2497                // NOOP, as exception is thrown if engine doesn't support file
2498            }
2499            if (pEngine) EngineFactory::Destroy(pEngine);
2500        }
2501    
2502        if (!bFound) result.Error("Unknown file format");
2503        return result.Produce();
2504    }
2505    
2506    void LSCPServer::VerifyFile(String Filename) {
2507        struct stat statBuf;
2508        int res = stat(Filename.c_str(), &statBuf);
2509        if (res) {
2510            std::stringstream ss;
2511            ss << "Fail to stat `" << Filename << "`: " << strerror(errno);
2512            throw Exception(ss.str());
2513        }
2514    
2515        if (S_ISDIR(statBuf.st_mode)) {
2516            throw Exception("Directory is specified");
2517        }
2518    }
2519    
2520  /**  /**
2521   * Will be called by the parser to subscribe a client (frontend) on the   * Will be called by the parser to subscribe a client (frontend) on the
2522   * server for receiving event messages.   * server for receiving event messages.
# Line 2117  String LSCPServer::UnsubscribeNotificati Line 2543  String LSCPServer::UnsubscribeNotificati
2543      return result.Produce();      return result.Produce();
2544  }  }
2545    
2546  static int select_callback(void * lscpResultSet, int argc,  String LSCPServer::AddDbInstrumentDirectory(String Dir) {
2547                          char **argv, char **azColName)      dmsg(2,("LSCPServer: AddDbInstrumentDirectory(Dir=%s)\n", Dir.c_str()));
2548  {      LSCPResultSet result;
2549      LSCPResultSet* resultSet = (LSCPResultSet*) lscpResultSet;  #if HAVE_SQLITE3
2550      resultSet->Add(argc, argv);      try {
2551      return 0;          InstrumentsDb::GetInstrumentsDb()->AddDirectory(Dir);
2552        } catch (Exception e) {
2553             result.Error(e);
2554        }
2555    #else
2556        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2557    #endif
2558        return result.Produce();
2559  }  }
2560    
2561  String LSCPServer::QueryDatabase(String query) {  String LSCPServer::RemoveDbInstrumentDirectory(String Dir, bool Force) {
2562        dmsg(2,("LSCPServer: RemoveDbInstrumentDirectory(Dir=%s,Force=%d)\n", Dir.c_str(), Force));
2563      LSCPResultSet result;      LSCPResultSet result;
2564  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2565      char* zErrMsg = NULL;      try {
2566      sqlite3 *db;          InstrumentsDb::GetInstrumentsDb()->RemoveDirectory(Dir, Force);
2567      String selectStr = "SELECT " + query;      } catch (Exception e) {
2568             result.Error(e);
2569        }
2570    #else
2571        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2572    #endif
2573        return result.Produce();
2574    }
2575    
2576      int rc = sqlite3_open("linuxsampler.db", &db);  String LSCPServer::GetDbInstrumentDirectoryCount(String Dir, bool Recursive) {
2577      if (rc == SQLITE_OK)      dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2578      {      LSCPResultSet result;
2579              rc = sqlite3_exec(db, selectStr.c_str(), select_callback, &result, &zErrMsg);  #if HAVE_SQLITE3
2580        try {
2581            result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir, Recursive));
2582        } catch (Exception e) {
2583             result.Error(e);
2584      }      }
2585      if ( rc != SQLITE_OK )  #else
2586      {      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2587              result.Error(String(zErrMsg), rc);  #endif
2588        return result.Produce();
2589    }
2590    
2591    String LSCPServer::GetDbInstrumentDirectories(String Dir, bool Recursive) {
2592        dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2593        LSCPResultSet result;
2594    #if HAVE_SQLITE3
2595        try {
2596            String list;
2597            StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir, Recursive);
2598    
2599            for (int i = 0; i < dirs->size(); i++) {
2600                if (list != "") list += ",";
2601                list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2602            }
2603    
2604            result.Add(list);
2605        } catch (Exception e) {
2606             result.Error(e);
2607        }
2608    #else
2609        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2610    #endif
2611        return result.Produce();
2612    }
2613    
2614    String LSCPServer::GetDbInstrumentDirectoryInfo(String Dir) {
2615        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryInfo(Dir=%s)\n", Dir.c_str()));
2616        LSCPResultSet result;
2617    #if HAVE_SQLITE3
2618        try {
2619            DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2620    
2621            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2622            result.Add("CREATED", info.Created);
2623            result.Add("MODIFIED", info.Modified);
2624        } catch (Exception e) {
2625             result.Error(e);
2626        }
2627    #else
2628        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2629    #endif
2630        return result.Produce();
2631    }
2632    
2633    String LSCPServer::SetDbInstrumentDirectoryName(String Dir, String Name) {
2634        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryName(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
2635        LSCPResultSet result;
2636    #if HAVE_SQLITE3
2637        try {
2638            InstrumentsDb::GetInstrumentsDb()->RenameDirectory(Dir, Name);
2639        } catch (Exception e) {
2640             result.Error(e);
2641        }
2642    #else
2643        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2644    #endif
2645        return result.Produce();
2646    }
2647    
2648    String LSCPServer::MoveDbInstrumentDirectory(String Dir, String Dst) {
2649        dmsg(2,("LSCPServer: MoveDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2650        LSCPResultSet result;
2651    #if HAVE_SQLITE3
2652        try {
2653            InstrumentsDb::GetInstrumentsDb()->MoveDirectory(Dir, Dst);
2654        } catch (Exception e) {
2655             result.Error(e);
2656        }
2657    #else
2658        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2659    #endif
2660        return result.Produce();
2661    }
2662    
2663    String LSCPServer::CopyDbInstrumentDirectory(String Dir, String Dst) {
2664        dmsg(2,("LSCPServer: CopyDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2665        LSCPResultSet result;
2666    #if HAVE_SQLITE3
2667        try {
2668            InstrumentsDb::GetInstrumentsDb()->CopyDirectory(Dir, Dst);
2669        } catch (Exception e) {
2670             result.Error(e);
2671        }
2672    #else
2673        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2674    #endif
2675        return result.Produce();
2676    }
2677    
2678    String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {
2679        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
2680        LSCPResultSet result;
2681    #if HAVE_SQLITE3
2682        try {
2683            InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);
2684        } catch (Exception e) {
2685             result.Error(e);
2686        }
2687    #else
2688        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2689    #endif
2690        return result.Produce();
2691    }
2692    
2693    String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
2694        dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
2695        LSCPResultSet result;
2696    #if HAVE_SQLITE3
2697        try {
2698            int id;
2699            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2700            id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
2701            if (bBackground) result = id;
2702        } catch (Exception e) {
2703             result.Error(e);
2704        }
2705    #else
2706        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2707    #endif
2708        return result.Produce();
2709    }
2710    
2711    String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {
2712        dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground));
2713        LSCPResultSet result;
2714    #if HAVE_SQLITE3
2715        try {
2716            int id;
2717            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2718            if (ScanMode.compare("RECURSIVE") == 0) {
2719               id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);
2720            } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
2721               id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);
2722            } else if (ScanMode.compare("FLAT") == 0) {
2723               id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);
2724            } else {
2725                throw Exception("Unknown scan mode: " + ScanMode);
2726            }
2727    
2728            if (bBackground) result = id;
2729        } catch (Exception e) {
2730             result.Error(e);
2731        }
2732    #else
2733        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2734    #endif
2735        return result.Produce();
2736    }
2737    
2738    String LSCPServer::RemoveDbInstrument(String Instr) {
2739        dmsg(2,("LSCPServer: RemoveDbInstrument(Instr=%s)\n", Instr.c_str()));
2740        LSCPResultSet result;
2741    #if HAVE_SQLITE3
2742        try {
2743            InstrumentsDb::GetInstrumentsDb()->RemoveInstrument(Instr);
2744        } catch (Exception e) {
2745             result.Error(e);
2746        }
2747    #else
2748        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2749    #endif
2750        return result.Produce();
2751    }
2752    
2753    String LSCPServer::GetDbInstrumentCount(String Dir, bool Recursive) {
2754        dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2755        LSCPResultSet result;
2756    #if HAVE_SQLITE3
2757        try {
2758            result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir, Recursive));
2759        } catch (Exception e) {
2760             result.Error(e);
2761        }
2762    #else
2763        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2764    #endif
2765        return result.Produce();
2766    }
2767    
2768    String LSCPServer::GetDbInstruments(String Dir, bool Recursive) {
2769        dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2770        LSCPResultSet result;
2771    #if HAVE_SQLITE3
2772        try {
2773            String list;
2774            StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir, Recursive);
2775    
2776            for (int i = 0; i < instrs->size(); i++) {
2777                if (list != "") list += ",";
2778                list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
2779            }
2780    
2781            result.Add(list);
2782        } catch (Exception e) {
2783             result.Error(e);
2784        }
2785    #else
2786        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2787    #endif
2788        return result.Produce();
2789    }
2790    
2791    String LSCPServer::GetDbInstrumentInfo(String Instr) {
2792        dmsg(2,("LSCPServer: GetDbInstrumentInfo(Instr=%s)\n", Instr.c_str()));
2793        LSCPResultSet result;
2794    #if HAVE_SQLITE3
2795        try {
2796            DbInstrument info = InstrumentsDb::GetInstrumentsDb()->GetInstrumentInfo(Instr);
2797    
2798            result.Add("INSTRUMENT_FILE", info.InstrFile);
2799            result.Add("INSTRUMENT_NR", info.InstrNr);
2800            result.Add("FORMAT_FAMILY", info.FormatFamily);
2801            result.Add("FORMAT_VERSION", info.FormatVersion);
2802            result.Add("SIZE", (int)info.Size);
2803            result.Add("CREATED", info.Created);
2804            result.Add("MODIFIED", info.Modified);
2805            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2806            result.Add("IS_DRUM", info.IsDrum);
2807            result.Add("PRODUCT", _escapeLscpResponse(info.Product));
2808            result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
2809            result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
2810        } catch (Exception e) {
2811             result.Error(e);
2812        }
2813    #else
2814        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2815    #endif
2816        return result.Produce();
2817    }
2818    
2819    String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
2820        dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
2821        LSCPResultSet result;
2822    #if HAVE_SQLITE3
2823        try {
2824            ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
2825    
2826            result.Add("FILES_TOTAL", job.FilesTotal);
2827            result.Add("FILES_SCANNED", job.FilesScanned);
2828            result.Add("SCANNING", job.Scanning);
2829            result.Add("STATUS", job.Status);
2830        } catch (Exception e) {
2831             result.Error(e);
2832        }
2833    #else
2834        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2835    #endif
2836        return result.Produce();
2837    }
2838    
2839    String LSCPServer::SetDbInstrumentName(String Instr, String Name) {
2840        dmsg(2,("LSCPServer: SetDbInstrumentName(Instr=%s,Name=%s)\n", Instr.c_str(), Name.c_str()));
2841        LSCPResultSet result;
2842    #if HAVE_SQLITE3
2843        try {
2844            InstrumentsDb::GetInstrumentsDb()->RenameInstrument(Instr, Name);
2845        } catch (Exception e) {
2846             result.Error(e);
2847        }
2848    #else
2849        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2850    #endif
2851        return result.Produce();
2852    }
2853    
2854    String LSCPServer::MoveDbInstrument(String Instr, String Dst) {
2855        dmsg(2,("LSCPServer: MoveDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
2856        LSCPResultSet result;
2857    #if HAVE_SQLITE3
2858        try {
2859            InstrumentsDb::GetInstrumentsDb()->MoveInstrument(Instr, Dst);
2860        } catch (Exception e) {
2861             result.Error(e);
2862        }
2863    #else
2864        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2865    #endif
2866        return result.Produce();
2867    }
2868    
2869    String LSCPServer::CopyDbInstrument(String Instr, String Dst) {
2870        dmsg(2,("LSCPServer: CopyDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
2871        LSCPResultSet result;
2872    #if HAVE_SQLITE3
2873        try {
2874            InstrumentsDb::GetInstrumentsDb()->CopyInstrument(Instr, Dst);
2875        } catch (Exception e) {
2876             result.Error(e);
2877        }
2878    #else
2879        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2880    #endif
2881        return result.Produce();
2882    }
2883    
2884    String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {
2885        dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
2886        LSCPResultSet result;
2887    #if HAVE_SQLITE3
2888        try {
2889            InstrumentsDb::GetInstrumentsDb()->SetInstrumentDescription(Instr, Desc);
2890        } catch (Exception e) {
2891             result.Error(e);
2892      }      }
     sqlite3_close(db);  
2893  #else  #else
2894      result.Error(String("SQLITE3 was not installed when linuxsampler was built. SELECT statement is not available."), 0);      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2895  #endif  #endif
2896      return result.Produce();      return result.Produce();
2897  }  }
2898    
2899    String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
2900        dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
2901        LSCPResultSet result;
2902    #if HAVE_SQLITE3
2903        try {
2904            SearchQuery Query;
2905            std::map<String,String>::iterator iter;
2906            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
2907                if (iter->first.compare("NAME") == 0) {
2908                    Query.Name = iter->second;
2909                } else if (iter->first.compare("CREATED") == 0) {
2910                    Query.SetCreated(iter->second);
2911                } else if (iter->first.compare("MODIFIED") == 0) {
2912                    Query.SetModified(iter->second);
2913                } else if (iter->first.compare("DESCRIPTION") == 0) {
2914                    Query.Description = iter->second;
2915                } else {
2916                    throw Exception("Unknown search criteria: " + iter->first);
2917                }
2918            }
2919    
2920            String list;
2921            StringListPtr pDirectories =
2922                InstrumentsDb::GetInstrumentsDb()->FindDirectories(Dir, &Query, Recursive);
2923    
2924            for (int i = 0; i < pDirectories->size(); i++) {
2925                if (list != "") list += ",";
2926                list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
2927            }
2928    
2929            result.Add(list);
2930        } catch (Exception e) {
2931             result.Error(e);
2932        }
2933    #else
2934        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2935    #endif
2936        return result.Produce();
2937    }
2938    
2939    String LSCPServer::FindDbInstruments(String Dir, std::map<String,String> Parameters, bool Recursive) {
2940        dmsg(2,("LSCPServer: FindDbInstruments(Dir=%s)\n", Dir.c_str()));
2941        LSCPResultSet result;
2942    #if HAVE_SQLITE3
2943        try {
2944            SearchQuery Query;
2945            std::map<String,String>::iterator iter;
2946            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
2947                if (iter->first.compare("NAME") == 0) {
2948                    Query.Name = iter->second;
2949                } else if (iter->first.compare("FORMAT_FAMILIES") == 0) {
2950                    Query.SetFormatFamilies(iter->second);
2951                } else if (iter->first.compare("SIZE") == 0) {
2952                    Query.SetSize(iter->second);
2953                } else if (iter->first.compare("CREATED") == 0) {
2954                    Query.SetCreated(iter->second);
2955                } else if (iter->first.compare("MODIFIED") == 0) {
2956                    Query.SetModified(iter->second);
2957                } else if (iter->first.compare("DESCRIPTION") == 0) {
2958                    Query.Description = iter->second;
2959                } else if (iter->first.compare("IS_DRUM") == 0) {
2960                    if (!strcasecmp(iter->second.c_str(), "true")) {
2961                        Query.InstrType = SearchQuery::DRUM;
2962                    } else {
2963                        Query.InstrType = SearchQuery::CHROMATIC;
2964                    }
2965                } else if (iter->first.compare("PRODUCT") == 0) {
2966                     Query.Product = iter->second;
2967                } else if (iter->first.compare("ARTISTS") == 0) {
2968                     Query.Artists = iter->second;
2969                } else if (iter->first.compare("KEYWORDS") == 0) {
2970                     Query.Keywords = iter->second;
2971                } else {
2972                    throw Exception("Unknown search criteria: " + iter->first);
2973                }
2974            }
2975    
2976            String list;
2977            StringListPtr pInstruments =
2978                InstrumentsDb::GetInstrumentsDb()->FindInstruments(Dir, &Query, Recursive);
2979    
2980            for (int i = 0; i < pInstruments->size(); i++) {
2981                if (list != "") list += ",";
2982                list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
2983            }
2984    
2985            result.Add(list);
2986        } catch (Exception e) {
2987             result.Error(e);
2988        }
2989    #else
2990        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2991    #endif
2992        return result.Produce();
2993    }
2994    
2995    String LSCPServer::FormatInstrumentsDb() {
2996        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
2997        LSCPResultSet result;
2998    #if HAVE_SQLITE3
2999        try {
3000            InstrumentsDb::GetInstrumentsDb()->Format();
3001        } catch (Exception e) {
3002             result.Error(e);
3003        }
3004    #else
3005        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3006    #endif
3007        return result.Produce();
3008    }
3009    
3010    
3011  /**  /**
3012   * Will be called by the parser to enable or disable echo mode; if echo   * Will be called by the parser to enable or disable echo mode; if echo
3013   * 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.1535

  ViewVC Help
Powered by ViewVC