/[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 973 by schoenebeck, Fri Dec 15 21:40:27 2006 UTC revision 1649 by nagata, Fri Jan 25 15:06:02 2008 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 66  LSCPServer::LSCPServer(Sampler* pSampler Line 106  LSCPServer::LSCPServer(Sampler* pSampler
106      SocketAddress.sin_addr.s_addr = addr;      SocketAddress.sin_addr.s_addr = addr;
107      SocketAddress.sin_port        = port;      SocketAddress.sin_port        = port;
108      this->pSampler = pSampler;      this->pSampler = pSampler;
109        LSCPEvent::RegisterEvent(LSCPEvent::event_audio_device_count, "AUDIO_OUTPUT_DEVICE_COUNT");
110        LSCPEvent::RegisterEvent(LSCPEvent::event_audio_device_info, "AUDIO_OUTPUT_DEVICE_INFO");
111        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_device_count, "MIDI_INPUT_DEVICE_COUNT");
112        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_device_info, "MIDI_INPUT_DEVICE_INFO");
113      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_count, "CHANNEL_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_count, "CHANNEL_COUNT");
114      LSCPEvent::RegisterEvent(LSCPEvent::event_voice_count, "VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_voice_count, "VOICE_COUNT");
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");
121        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");
122        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");
123        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 95  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 108  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 121  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 131  int LSCPServer::Main() { Line 309  int LSCPServer::Main() {
309      timeval timeout;      timeval timeout;
310    
311      while (true) {      while (true) {
312            #if CONFIG_PTHREAD_TESTCANCEL
313                    TestCancel();
314            #endif
315          // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers          // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers
316          {          {
317              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
# Line 140  int LSCPServer::Main() { Line 321  int LSCPServer::Main() {
321                  if ((*itEngineChannel)->StatusChanged()) {                  if ((*itEngineChannel)->StatusChanged()) {
322                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));
323                  }                  }
324    
325                    for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
326                        FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
327                        if(fxs != NULL && fxs->IsInfoChanged()) {
328                            int chn = (*itEngineChannel)->iSamplerChannelIndex;
329                            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
330                            fxs->SetInfoChanged(false);
331                        }
332                    }
333              }              }
334          }          }
335    
# Line 165  int LSCPServer::Main() { Line 355  int LSCPServer::Main() {
355                  continue; //Nothing try again                  continue; //Nothing try again
356          if (retval == -1) {          if (retval == -1) {
357                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
358                    #if defined(WIN32)
359                    closesocket(hSocket);
360                    #else
361                  close(hSocket);                  close(hSocket);
362                    #endif
363                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
364          }          }
365    
# Line 177  int LSCPServer::Main() { Line 371  int LSCPServer::Main() {
371                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
372                  }                  }
373    
374                    #if defined(WIN32)
375                    u_long nonblock_io = 1;
376                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
377                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
378                      exit(EXIT_FAILURE);
379                    }
380            #else
381                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
382                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
383                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
384                  }                  }
385                    #endif
386    
387                  // Parser initialization                  // Parser initialization
388                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 204  int LSCPServer::Main() { Line 406  int LSCPServer::Main() {
406                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
407                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
408                                  currentSocket = (*iter).hSession;  //a hack                                  currentSocket = (*iter).hSession;  //a hack
409                                    itCurrentSession = iter; // another hack
410                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
411                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
412                                      AnswerClient(bufferedCommands[currentSocket]);                                      AnswerClient(bufferedCommands[currentSocket]);
413                                  }                                  }
414                                  int result = yyparse(&(*iter));                                  int result = yyparse(&(*iter));
415                                  currentSocket = -1;     //continuation of a hack                                  currentSocket = -1;     //continuation of a hack
416                                    itCurrentSession = Sessions.end(); // hack as well
417                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
418                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?
419                                          CloseConnection(iter);                                          CloseConnection(iter);
# Line 237  void LSCPServer::CloseConnection( std::v Line 441  void LSCPServer::CloseConnection( std::v
441          NotifyMutex.Lock();          NotifyMutex.Lock();
442          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
443          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
444            #if defined(WIN32)
445            closesocket(socket);
446            #else
447          close(socket);          close(socket);
448            #endif
449          NotifyMutex.Unlock();          NotifyMutex.Unlock();
450  }  }
451    
452    void LSCPServer::LockRTNotify() {
453        RTNotifyMutex.Lock();
454    }
455    
456    void LSCPServer::UnlockRTNotify() {
457        RTNotifyMutex.Unlock();
458    }
459    
460  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
461          int subs = 0;          int subs = 0;
462          SubscriptionMutex.Lock();          SubscriptionMutex.Lock();
# Line 302  extern int GetLSCPCommand( void *buf, in Line 518  extern int GetLSCPCommand( void *buf, in
518          return command.size();          return command.size();
519  }  }
520    
521    extern yyparse_param_t* GetCurrentYaccSession() {
522        return &(*itCurrentSession);
523    }
524    
525  /**  /**
526   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
527   * 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 312  bool LSCPServer::GetLSCPCommand( std::ve Line 532  bool LSCPServer::GetLSCPCommand( std::ve
532          char c;          char c;
533          int i = 0;          int i = 0;
534          while (true) {          while (true) {
535                    #if defined(WIN32)
536                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
537                    #else
538                  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
539                    #endif
540                  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
541                          CloseConnection(iter);                          CloseConnection(iter);
542                          break;                          break;
# Line 327  bool LSCPServer::GetLSCPCommand( std::ve Line 551  bool LSCPServer::GetLSCPCommand( std::ve
551                          }                          }
552                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
553                  }                  }
554                    #if defined(WIN32)
555                    if (result == SOCKET_ERROR) {
556                        int wsa_lasterror = WSAGetLastError();
557                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
558                                    return false;
559                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
560                            CloseConnection(iter);
561                            break;
562                    }
563                    #else
564                  if (result == -1) {                  if (result == -1) {
565                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
566                                  return false;                                  return false;
# Line 365  bool LSCPServer::GetLSCPCommand( std::ve Line 599  bool LSCPServer::GetLSCPCommand( std::ve
599                          CloseConnection(iter);                          CloseConnection(iter);
600                          break;                          break;
601                  }                  }
602                    #endif
603          }          }
604          return false;          return false;
605  }  }
# Line 482  String LSCPServer::DestroyMidiInputDevic Line 717  String LSCPServer::DestroyMidiInputDevic
717      return result.Produce();      return result.Produce();
718  }  }
719    
720    EngineChannel* LSCPServer::GetEngineChannel(uint uiSamplerChannel) {
721        SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
722        if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
723    
724        EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
725        if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
726    
727        return pEngineChannel;
728    }
729    
730  /**  /**
731   * Will be called by the parser to load an instrument.   * Will be called by the parser to load an instrument.
732   */   */
# Line 628  String LSCPServer::GetEngineInfo(String Line 873  String LSCPServer::GetEngineInfo(String
873      LockRTNotify();      LockRTNotify();
874      try {      try {
875          Engine* pEngine = EngineFactory::Create(EngineName);          Engine* pEngine = EngineFactory::Create(EngineName);
876          result.Add("DESCRIPTION", pEngine->Description());          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
877          result.Add("VERSION",     pEngine->Version());          result.Add("VERSION",     pEngine->Version());
878          EngineFactory::Destroy(pEngine);          EngineFactory::Destroy(pEngine);
879      }      }
# Line 662  String LSCPServer::GetChannelInfo(uint u Line 907  String LSCPServer::GetChannelInfo(uint u
907          String AudioRouting;          String AudioRouting;
908          int Mute = 0;          int Mute = 0;
909          bool Solo = false;          bool Solo = false;
910          String MidiInstrumentMap;          String MidiInstrumentMap = "NONE";
911    
912          if (pEngineChannel) {          if (pEngineChannel) {
913              EngineName          = pEngineChannel->EngineName();              EngineName          = pEngineChannel->EngineName();
# Line 701  String LSCPServer::GetChannelInfo(uint u Line 946  String LSCPServer::GetChannelInfo(uint u
946          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
947          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
948    
949            // convert the filename into the correct encoding as defined for LSCP
950            // (especially in terms of special characters -> escape sequences)
951            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
952    #if WIN32
953                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
954    #else
955                // assuming POSIX
956                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
957    #endif
958            }
959    
960          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
961          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
962          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
963          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
964          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
965          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
# Line 1185  String LSCPServer::SetAudioOutputChannel Line 1441  String LSCPServer::SetAudioOutputChannel
1441    
1442          // set new channel parameter value          // set new channel parameter value
1443          pParameter->SetValue(ParamVal);          pParameter->SetValue(ParamVal);
1444            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_info, DeviceId));
1445      }      }
1446      catch (Exception e) {      catch (Exception e) {
1447          result.Error(e);          result.Error(e);
# Line 1202  String LSCPServer::SetAudioOutputDeviceP Line 1459  String LSCPServer::SetAudioOutputDeviceP
1459          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1460          if (!parameters.count(ParamKey)) throw Exception("Audio output device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");          if (!parameters.count(ParamKey)) throw Exception("Audio output device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");
1461          parameters[ParamKey]->SetValue(ParamVal);          parameters[ParamKey]->SetValue(ParamVal);
1462            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_info, DeviceIndex));
1463      }      }
1464      catch (Exception e) {      catch (Exception e) {
1465          result.Error(e);          result.Error(e);
# Line 1219  String LSCPServer::SetMidiInputDevicePar Line 1477  String LSCPServer::SetMidiInputDevicePar
1477          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1478          if (!parameters.count(ParamKey)) throw Exception("MIDI input device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");          if (!parameters.count(ParamKey)) throw Exception("MIDI input device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");
1479          parameters[ParamKey]->SetValue(ParamVal);          parameters[ParamKey]->SetValue(ParamVal);
1480            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_info, DeviceIndex));
1481      }      }
1482      catch (Exception e) {      catch (Exception e) {
1483          result.Error(e);          result.Error(e);
# Line 1243  String LSCPServer::SetMidiInputPortParam Line 1502  String LSCPServer::SetMidiInputPortParam
1502          std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();          std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();
1503          if (!parameters.count(ParamKey)) throw Exception("MIDI input device " + ToString(PortIndex) + " does not have a parameter '" + ParamKey + "'");          if (!parameters.count(ParamKey)) throw Exception("MIDI input device " + ToString(PortIndex) + " does not have a parameter '" + ParamKey + "'");
1504          parameters[ParamKey]->SetValue(ParamVal);          parameters[ParamKey]->SetValue(ParamVal);
1505            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_info, DeviceIndex));
1506      }      }
1507      catch (Exception e) {      catch (Exception e) {
1508          result.Error(e);          result.Error(e);
# Line 1490  String LSCPServer::SetChannelSolo(bool b Line 1750  String LSCPServer::SetChannelSolo(bool b
1750    
1751          bool oldSolo = pEngineChannel->GetSolo();          bool oldSolo = pEngineChannel->GetSolo();
1752          bool hadSoloChannel = HasSoloChannel();          bool hadSoloChannel = HasSoloChannel();
1753            
1754          pEngineChannel->SetSolo(bSolo);          pEngineChannel->SetSolo(bSolo);
1755            
1756          if(!oldSolo && bSolo) {          if(!oldSolo && bSolo) {
1757              if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);              if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);
1758              if(!hadSoloChannel) MuteNonSoloChannels();              if(!hadSoloChannel) MuteNonSoloChannels();
1759          }          }
1760            
1761          if(oldSolo && !bSolo) {          if(oldSolo && !bSolo) {
1762              if(!HasSoloChannel()) UnmuteChannels();              if(!HasSoloChannel()) UnmuteChannels();
1763              else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);              else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);
# Line 1555  void  LSCPServer::UnmuteChannels() { Line 1815  void  LSCPServer::UnmuteChannels() {
1815      }      }
1816  }  }
1817    
1818  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) {
1819      dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));      dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));
1820    
1821      midi_prog_index_t idx;      midi_prog_index_t idx;
# Line 1573  String LSCPServer::AddOrReplaceMIDIInstr Line 1833  String LSCPServer::AddOrReplaceMIDIInstr
1833    
1834      LSCPResultSet result;      LSCPResultSet result;
1835      try {      try {
1836          // PERSISTENT mapping commands might bloock for a long time, so in          // PERSISTENT mapping commands might block for a long time, so in
1837          // that case we add/replace the mapping in another thread          // that case we add/replace the mapping in another thread in case
1838          bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT);          // the NON_MODAL argument was supplied, non persistent mappings
1839            // should return immediately, so we don't need to do that for them
1840            bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT && !bModal);
1841          MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);          MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);
1842      } catch (Exception e) {      } catch (Exception e) {
1843          result.Error(e);          result.Error(e);
# Line 1639  String LSCPServer::GetMidiInstrumentMapp Line 1901  String LSCPServer::GetMidiInstrumentMapp
1901          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);
1902          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");
1903          else { // found          else { // found
1904              result.Add("NAME", iter->second.Name);  
1905                // convert the filename into the correct encoding as defined for LSCP
1906                // (especially in terms of special characters -> escape sequences)
1907    #if WIN32
1908                const String instrumentFileName = Path::fromWindows(iter->second.InstrumentFile).toLscp();
1909    #else
1910                // assuming POSIX
1911                const String instrumentFileName = Path::fromPosix(iter->second.InstrumentFile).toLscp();
1912    #endif
1913    
1914                result.Add("NAME", _escapeLscpResponse(iter->second.Name));
1915              result.Add("ENGINE_NAME", iter->second.EngineName);              result.Add("ENGINE_NAME", iter->second.EngineName);
1916              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);              result.Add("INSTRUMENT_FILE", instrumentFileName);
1917              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);
1918              String instrumentName;              String instrumentName;
1919              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);
# Line 1654  String LSCPServer::GetMidiInstrumentMapp Line 1926  String LSCPServer::GetMidiInstrumentMapp
1926                  }                  }
1927                  EngineFactory::Destroy(pEngine);                  EngineFactory::Destroy(pEngine);
1928              }              }
1929              result.Add("INSTRUMENT_NAME", instrumentName);              result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
1930              switch (iter->second.LoadMode) {              switch (iter->second.LoadMode) {
1931                  case MidiInstrumentMapper::ON_DEMAND:                  case MidiInstrumentMapper::ON_DEMAND:
1932                      result.Add("LOAD_MODE", "ON_DEMAND");                      result.Add("LOAD_MODE", "ON_DEMAND");
# Line 1686  String LSCPServer::ListMidiInstrumentMap Line 1958  String LSCPServer::ListMidiInstrumentMap
1958          for (; iter != mappings.end(); iter++) {          for (; iter != mappings.end(); iter++) {
1959              if (s.size()) s += ",";              if (s.size()) s += ",";
1960              s += "{" + ToString(MidiMapID) + ","              s += "{" + ToString(MidiMapID) + ","
1961                       + 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)) + ","
1962                       + ToString(int(iter->first.midi_prog)) + "}";                       + ToString(int(iter->first.midi_prog)) + "}";
1963          }          }
1964          result.Add(s);          result.Add(s);
# Line 1708  String LSCPServer::ListAllMidiInstrument Line 1980  String LSCPServer::ListAllMidiInstrument
1980              for (; iter != mappings.end(); iter++) {              for (; iter != mappings.end(); iter++) {
1981                  if (s.size()) s += ",";                  if (s.size()) s += ",";
1982                  s += "{" + ToString(maps[i]) + ","                  s += "{" + ToString(maps[i]) + ","
1983                           + 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)) + ","
1984                           + ToString(int(iter->first.midi_prog)) + "}";                           + ToString(int(iter->first.midi_prog)) + "}";
1985              }              }
1986          }          }
# Line 1809  String LSCPServer::GetMidiInstrumentMap( Line 2081  String LSCPServer::GetMidiInstrumentMap(
2081      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2082      LSCPResultSet result;      LSCPResultSet result;
2083      try {      try {
2084          result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID));          result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2085            result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2086      } catch (Exception e) {      } catch (Exception e) {
2087          result.Error(e);          result.Error(e);
2088      }      }
# Line 1854  String LSCPServer::SetChannelMap(uint ui Line 2127  String LSCPServer::SetChannelMap(uint ui
2127      return result.Produce();      return result.Produce();
2128  }  }
2129    
2130    String LSCPServer::CreateFxSend(uint uiSamplerChannel, uint MidiCtrl, String Name) {
2131        dmsg(2,("LSCPServer: CreateFxSend()\n"));
2132        LSCPResultSet result;
2133        try {
2134            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2135    
2136            FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2137            if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");
2138    
2139            result = LSCPResultSet(pFxSend->Id()); // success
2140        } catch (Exception e) {
2141            result.Error(e);
2142        }
2143        return result.Produce();
2144    }
2145    
2146    String LSCPServer::DestroyFxSend(uint uiSamplerChannel, uint FxSendID) {
2147        dmsg(2,("LSCPServer: DestroyFxSend()\n"));
2148        LSCPResultSet result;
2149        try {
2150            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2151    
2152            FxSend* pFxSend = NULL;
2153            for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2154                if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2155                    pFxSend = pEngineChannel->GetFxSend(i);
2156                    break;
2157                }
2158            }
2159            if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2160            pEngineChannel->RemoveFxSend(pFxSend);
2161        } catch (Exception e) {
2162            result.Error(e);
2163        }
2164        return result.Produce();
2165    }
2166    
2167    String LSCPServer::GetFxSends(uint uiSamplerChannel) {
2168        dmsg(2,("LSCPServer: GetFxSends()\n"));
2169        LSCPResultSet result;
2170        try {
2171            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2172    
2173            result.Add(pEngineChannel->GetFxSendCount());
2174        } catch (Exception e) {
2175            result.Error(e);
2176        }
2177        return result.Produce();
2178    }
2179    
2180    String LSCPServer::ListFxSends(uint uiSamplerChannel) {
2181        dmsg(2,("LSCPServer: ListFxSends()\n"));
2182        LSCPResultSet result;
2183        String list;
2184        try {
2185            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2186    
2187            for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2188                FxSend* pFxSend = pEngineChannel->GetFxSend(i);
2189                if (list != "") list += ",";
2190                list += ToString(pFxSend->Id());
2191            }
2192            result.Add(list);
2193        } catch (Exception e) {
2194            result.Error(e);
2195        }
2196        return result.Produce();
2197    }
2198    
2199    FxSend* LSCPServer::GetFxSend(uint uiSamplerChannel, uint FxSendID) {
2200        EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2201    
2202        FxSend* pFxSend = NULL;
2203        for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2204            if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2205                pFxSend = pEngineChannel->GetFxSend(i);
2206                break;
2207            }
2208        }
2209        if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2210        return pFxSend;
2211    }
2212    
2213    String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {
2214        dmsg(2,("LSCPServer: GetFxSendInfo()\n"));
2215        LSCPResultSet result;
2216        try {
2217            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2218            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2219    
2220            // gather audio routing informations
2221            String AudioRouting;
2222            for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {
2223                if (AudioRouting != "") AudioRouting += ",";
2224                AudioRouting += ToString(pFxSend->DestinationChannel(chan));
2225            }
2226    
2227            // success
2228            result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2229            result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2230            result.Add("LEVEL", ToString(pFxSend->Level()));
2231            result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
2232        } catch (Exception e) {
2233            result.Error(e);
2234        }
2235        return result.Produce();
2236    }
2237    
2238    String LSCPServer::SetFxSendName(uint uiSamplerChannel, uint FxSendID, String Name) {
2239        dmsg(2,("LSCPServer: SetFxSendName()\n"));
2240        LSCPResultSet result;
2241        try {
2242            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2243    
2244            pFxSend->SetName(Name);
2245            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2246        } catch (Exception e) {
2247            result.Error(e);
2248        }
2249        return result.Produce();
2250    }
2251    
2252    String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {
2253        dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));
2254        LSCPResultSet result;
2255        try {
2256            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2257    
2258            pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);
2259            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2260        } catch (Exception e) {
2261            result.Error(e);
2262        }
2263        return result.Produce();
2264    }
2265    
2266    String LSCPServer::SetFxSendMidiController(uint uiSamplerChannel, uint FxSendID, uint MidiController) {
2267        dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));
2268        LSCPResultSet result;
2269        try {
2270            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2271    
2272            pFxSend->SetMidiController(MidiController);
2273            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2274        } catch (Exception e) {
2275            result.Error(e);
2276        }
2277        return result.Produce();
2278    }
2279    
2280    String LSCPServer::SetFxSendLevel(uint uiSamplerChannel, uint FxSendID, double dLevel) {
2281        dmsg(2,("LSCPServer: SetFxSendLevel()\n"));
2282        LSCPResultSet result;
2283        try {
2284            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2285    
2286            pFxSend->SetLevel((float)dLevel);
2287            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2288        } catch (Exception e) {
2289            result.Error(e);
2290        }
2291        return result.Produce();
2292    }
2293    
2294    String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2295        dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2296        LSCPResultSet result;
2297        try {
2298            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
2299            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
2300            EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
2301            if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
2302            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2303            Engine* pEngine = pEngineChannel->GetEngine();
2304            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2305            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2306            InstrumentManager::instrument_id_t instrumentID;
2307            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2308            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2309            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2310        } catch (Exception e) {
2311            result.Error(e);
2312        }
2313        return result.Produce();
2314    }
2315    
2316  /**  /**
2317   * Will be called by the parser to reset a particular sampler channel.   * Will be called by the parser to reset a particular sampler channel.
2318   */   */
# Line 1889  String LSCPServer::ResetSampler() { Line 2348  String LSCPServer::ResetSampler() {
2348   */   */
2349  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
2350      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
2351        const std::string description =
2352            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2353      LSCPResultSet result;      LSCPResultSet result;
2354      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
2355      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
2356      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2357    #if HAVE_SQLITE3
2358        result.Add("INSTRUMENTS_DB_SUPPORT", "yes");
2359    #else
2360        result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2361    #endif
2362    
2363        return result.Produce();
2364    }
2365    
2366    /**
2367     * Will be called by the parser to return the current number of all active streams.
2368     */
2369    String LSCPServer::GetTotalStreamCount() {
2370        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2371        LSCPResultSet result;
2372        result.Add(pSampler->GetDiskStreamCount());
2373      return result.Produce();      return result.Produce();
2374  }  }
2375    
# Line 1916  String LSCPServer::GetTotalVoiceCountMax Line 2393  String LSCPServer::GetTotalVoiceCountMax
2393      return result.Produce();      return result.Produce();
2394  }  }
2395    
2396    String LSCPServer::GetGlobalVolume() {
2397        LSCPResultSet result;
2398        result.Add(ToString(GLOBAL_VOLUME)); // see common/global.cpp
2399        return result.Produce();
2400    }
2401    
2402    String LSCPServer::SetGlobalVolume(double dVolume) {
2403        LSCPResultSet result;
2404        try {
2405            if (dVolume < 0) throw Exception("Volume may not be negative");
2406            GLOBAL_VOLUME = dVolume; // see common/global.cpp
2407            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
2408        } catch (Exception e) {
2409            result.Error(e);
2410        }
2411        return result.Produce();
2412    }
2413    
2414    String LSCPServer::GetFileInstruments(String Filename) {
2415        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2416        LSCPResultSet result;
2417        try {
2418            VerifyFile(Filename);
2419        } catch (Exception e) {
2420            result.Error(e);
2421            return result.Produce();
2422        }
2423        // try to find a sampler engine that can handle the file
2424        bool bFound = false;
2425        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2426        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2427            Engine* pEngine = NULL;
2428            try {
2429                pEngine = EngineFactory::Create(engineTypes[i]);
2430                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2431                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2432                if (pManager) {
2433                    std::vector<InstrumentManager::instrument_id_t> IDs =
2434                        pManager->GetInstrumentFileContent(Filename);
2435                    // return the amount of instruments in the file
2436                    result.Add(IDs.size());
2437                    // no more need to ask other engine types
2438                    bFound = true;
2439                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2440            } catch (Exception e) {
2441                // NOOP, as exception is thrown if engine doesn't support file
2442            }
2443            if (pEngine) EngineFactory::Destroy(pEngine);
2444        }
2445    
2446        if (!bFound) result.Error("Unknown file format");
2447        return result.Produce();
2448    }
2449    
2450    String LSCPServer::ListFileInstruments(String Filename) {
2451        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2452        LSCPResultSet result;
2453        try {
2454            VerifyFile(Filename);
2455        } catch (Exception e) {
2456            result.Error(e);
2457            return result.Produce();
2458        }
2459        // try to find a sampler engine that can handle the file
2460        bool bFound = false;
2461        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2462        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2463            Engine* pEngine = NULL;
2464            try {
2465                pEngine = EngineFactory::Create(engineTypes[i]);
2466                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2467                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2468                if (pManager) {
2469                    std::vector<InstrumentManager::instrument_id_t> IDs =
2470                        pManager->GetInstrumentFileContent(Filename);
2471                    // return a list of IDs of the instruments in the file
2472                    String s;
2473                    for (int j = 0; j < IDs.size(); j++) {
2474                        if (s.size()) s += ",";
2475                        s += ToString(IDs[j].Index);
2476                    }
2477                    result.Add(s);
2478                    // no more need to ask other engine types
2479                    bFound = true;
2480                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2481            } catch (Exception e) {
2482                // NOOP, as exception is thrown if engine doesn't support file
2483            }
2484            if (pEngine) EngineFactory::Destroy(pEngine);
2485        }
2486    
2487        if (!bFound) result.Error("Unknown file format");
2488        return result.Produce();
2489    }
2490    
2491    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2492        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2493        LSCPResultSet result;
2494        try {
2495            VerifyFile(Filename);
2496        } catch (Exception e) {
2497            result.Error(e);
2498            return result.Produce();
2499        }
2500        InstrumentManager::instrument_id_t id;
2501        id.FileName = Filename;
2502        id.Index    = InstrumentID;
2503        // try to find a sampler engine that can handle the file
2504        bool bFound = false;
2505        bool bFatalErr = false;
2506        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2507        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2508            Engine* pEngine = NULL;
2509            try {
2510                pEngine = EngineFactory::Create(engineTypes[i]);
2511                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2512                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2513                if (pManager) {
2514                    // check if the instrument index is valid
2515                    // FIXME: this won't work if an engine only supports parts of the instrument file
2516                    std::vector<InstrumentManager::instrument_id_t> IDs =
2517                        pManager->GetInstrumentFileContent(Filename);
2518                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2519                        std::stringstream ss;
2520                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2521                        bFatalErr = true;
2522                        throw Exception(ss.str());
2523                    }
2524                    // get the info of the requested instrument
2525                    InstrumentManager::instrument_info_t info =
2526                        pManager->GetInstrumentInfo(id);
2527                    // return detailed informations about the file
2528                    result.Add("NAME", info.InstrumentName);
2529                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2530                    result.Add("FORMAT_VERSION", info.FormatVersion);
2531                    result.Add("PRODUCT", info.Product);
2532                    result.Add("ARTISTS", info.Artists);
2533                    // no more need to ask other engine types
2534                    bFound = true;
2535                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2536            } catch (Exception e) {
2537                // usually NOOP, as exception is thrown if engine doesn't support file
2538                if (bFatalErr) result.Error(e);
2539            }
2540            if (pEngine) EngineFactory::Destroy(pEngine);
2541        }
2542    
2543        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2544        return result.Produce();
2545    }
2546    
2547    void LSCPServer::VerifyFile(String Filename) {
2548        #if WIN32
2549        WIN32_FIND_DATA win32FileAttributeData;
2550        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2551        if (!res) {
2552            std::stringstream ss;
2553            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2554            throw Exception(ss.str());
2555        }
2556        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2557            throw Exception("Directory is specified");
2558        }
2559        #else
2560        struct stat statBuf;
2561        int res = stat(Filename.c_str(), &statBuf);
2562        if (res) {
2563            std::stringstream ss;
2564            ss << "Fail to stat `" << Filename << "`: " << strerror(errno);
2565            throw Exception(ss.str());
2566        }
2567    
2568        if (S_ISDIR(statBuf.st_mode)) {
2569            throw Exception("Directory is specified");
2570        }
2571        #endif
2572    }
2573    
2574  /**  /**
2575   * 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
2576   * server for receiving event messages.   * server for receiving event messages.
# Line 1942  String LSCPServer::UnsubscribeNotificati Line 2597  String LSCPServer::UnsubscribeNotificati
2597      return result.Produce();      return result.Produce();
2598  }  }
2599    
2600  static int select_callback(void * lscpResultSet, int argc,  String LSCPServer::AddDbInstrumentDirectory(String Dir) {
2601                          char **argv, char **azColName)      dmsg(2,("LSCPServer: AddDbInstrumentDirectory(Dir=%s)\n", Dir.c_str()));
2602  {      LSCPResultSet result;
2603      LSCPResultSet* resultSet = (LSCPResultSet*) lscpResultSet;  #if HAVE_SQLITE3
2604      resultSet->Add(argc, argv);      try {
2605      return 0;          InstrumentsDb::GetInstrumentsDb()->AddDirectory(Dir);
2606        } catch (Exception e) {
2607             result.Error(e);
2608        }
2609    #else
2610        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2611    #endif
2612        return result.Produce();
2613    }
2614    
2615    String LSCPServer::RemoveDbInstrumentDirectory(String Dir, bool Force) {
2616        dmsg(2,("LSCPServer: RemoveDbInstrumentDirectory(Dir=%s,Force=%d)\n", Dir.c_str(), Force));
2617        LSCPResultSet result;
2618    #if HAVE_SQLITE3
2619        try {
2620            InstrumentsDb::GetInstrumentsDb()->RemoveDirectory(Dir, Force);
2621        } catch (Exception e) {
2622             result.Error(e);
2623        }
2624    #else
2625        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2626    #endif
2627        return result.Produce();
2628    }
2629    
2630    String LSCPServer::GetDbInstrumentDirectoryCount(String Dir, bool Recursive) {
2631        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2632        LSCPResultSet result;
2633    #if HAVE_SQLITE3
2634        try {
2635            result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir, Recursive));
2636        } catch (Exception e) {
2637             result.Error(e);
2638        }
2639    #else
2640        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2641    #endif
2642        return result.Produce();
2643    }
2644    
2645    String LSCPServer::GetDbInstrumentDirectories(String Dir, bool Recursive) {
2646        dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2647        LSCPResultSet result;
2648    #if HAVE_SQLITE3
2649        try {
2650            String list;
2651            StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir, Recursive);
2652    
2653            for (int i = 0; i < dirs->size(); i++) {
2654                if (list != "") list += ",";
2655                list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2656            }
2657    
2658            result.Add(list);
2659        } catch (Exception e) {
2660             result.Error(e);
2661        }
2662    #else
2663        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2664    #endif
2665        return result.Produce();
2666    }
2667    
2668    String LSCPServer::GetDbInstrumentDirectoryInfo(String Dir) {
2669        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryInfo(Dir=%s)\n", Dir.c_str()));
2670        LSCPResultSet result;
2671    #if HAVE_SQLITE3
2672        try {
2673            DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2674    
2675            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2676            result.Add("CREATED", info.Created);
2677            result.Add("MODIFIED", info.Modified);
2678        } catch (Exception e) {
2679             result.Error(e);
2680        }
2681    #else
2682        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2683    #endif
2684        return result.Produce();
2685    }
2686    
2687    String LSCPServer::SetDbInstrumentDirectoryName(String Dir, String Name) {
2688        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryName(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
2689        LSCPResultSet result;
2690    #if HAVE_SQLITE3
2691        try {
2692            InstrumentsDb::GetInstrumentsDb()->RenameDirectory(Dir, Name);
2693        } catch (Exception e) {
2694             result.Error(e);
2695        }
2696    #else
2697        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2698    #endif
2699        return result.Produce();
2700    }
2701    
2702    String LSCPServer::MoveDbInstrumentDirectory(String Dir, String Dst) {
2703        dmsg(2,("LSCPServer: MoveDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2704        LSCPResultSet result;
2705    #if HAVE_SQLITE3
2706        try {
2707            InstrumentsDb::GetInstrumentsDb()->MoveDirectory(Dir, Dst);
2708        } catch (Exception e) {
2709             result.Error(e);
2710        }
2711    #else
2712        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2713    #endif
2714        return result.Produce();
2715    }
2716    
2717    String LSCPServer::CopyDbInstrumentDirectory(String Dir, String Dst) {
2718        dmsg(2,("LSCPServer: CopyDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2719        LSCPResultSet result;
2720    #if HAVE_SQLITE3
2721        try {
2722            InstrumentsDb::GetInstrumentsDb()->CopyDirectory(Dir, Dst);
2723        } catch (Exception e) {
2724             result.Error(e);
2725        }
2726    #else
2727        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2728    #endif
2729        return result.Produce();
2730    }
2731    
2732    String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {
2733        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
2734        LSCPResultSet result;
2735    #if HAVE_SQLITE3
2736        try {
2737            InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);
2738        } catch (Exception e) {
2739             result.Error(e);
2740        }
2741    #else
2742        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2743    #endif
2744        return result.Produce();
2745    }
2746    
2747    String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
2748        dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
2749        LSCPResultSet result;
2750    #if HAVE_SQLITE3
2751        try {
2752            int id;
2753            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2754            id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
2755            if (bBackground) result = id;
2756        } catch (Exception e) {
2757             result.Error(e);
2758        }
2759    #else
2760        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2761    #endif
2762        return result.Produce();
2763    }
2764    
2765    String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {
2766        dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground));
2767        LSCPResultSet result;
2768    #if HAVE_SQLITE3
2769        try {
2770            int id;
2771            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2772            if (ScanMode.compare("RECURSIVE") == 0) {
2773               id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);
2774            } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
2775               id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);
2776            } else if (ScanMode.compare("FLAT") == 0) {
2777               id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);
2778            } else {
2779                throw Exception("Unknown scan mode: " + ScanMode);
2780            }
2781    
2782            if (bBackground) result = id;
2783        } catch (Exception e) {
2784             result.Error(e);
2785        }
2786    #else
2787        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2788    #endif
2789        return result.Produce();
2790    }
2791    
2792    String LSCPServer::RemoveDbInstrument(String Instr) {
2793        dmsg(2,("LSCPServer: RemoveDbInstrument(Instr=%s)\n", Instr.c_str()));
2794        LSCPResultSet result;
2795    #if HAVE_SQLITE3
2796        try {
2797            InstrumentsDb::GetInstrumentsDb()->RemoveInstrument(Instr);
2798        } catch (Exception e) {
2799             result.Error(e);
2800        }
2801    #else
2802        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2803    #endif
2804        return result.Produce();
2805    }
2806    
2807    String LSCPServer::GetDbInstrumentCount(String Dir, bool Recursive) {
2808        dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2809        LSCPResultSet result;
2810    #if HAVE_SQLITE3
2811        try {
2812            result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir, Recursive));
2813        } catch (Exception e) {
2814             result.Error(e);
2815        }
2816    #else
2817        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2818    #endif
2819        return result.Produce();
2820    }
2821    
2822    String LSCPServer::GetDbInstruments(String Dir, bool Recursive) {
2823        dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2824        LSCPResultSet result;
2825    #if HAVE_SQLITE3
2826        try {
2827            String list;
2828            StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir, Recursive);
2829    
2830            for (int i = 0; i < instrs->size(); i++) {
2831                if (list != "") list += ",";
2832                list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
2833            }
2834    
2835            result.Add(list);
2836        } catch (Exception e) {
2837             result.Error(e);
2838        }
2839    #else
2840        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2841    #endif
2842        return result.Produce();
2843    }
2844    
2845    String LSCPServer::GetDbInstrumentInfo(String Instr) {
2846        dmsg(2,("LSCPServer: GetDbInstrumentInfo(Instr=%s)\n", Instr.c_str()));
2847        LSCPResultSet result;
2848    #if HAVE_SQLITE3
2849        try {
2850            DbInstrument info = InstrumentsDb::GetInstrumentsDb()->GetInstrumentInfo(Instr);
2851    
2852            result.Add("INSTRUMENT_FILE", info.InstrFile);
2853            result.Add("INSTRUMENT_NR", info.InstrNr);
2854            result.Add("FORMAT_FAMILY", info.FormatFamily);
2855            result.Add("FORMAT_VERSION", info.FormatVersion);
2856            result.Add("SIZE", (int)info.Size);
2857            result.Add("CREATED", info.Created);
2858            result.Add("MODIFIED", info.Modified);
2859            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2860            result.Add("IS_DRUM", info.IsDrum);
2861            result.Add("PRODUCT", _escapeLscpResponse(info.Product));
2862            result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
2863            result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
2864        } catch (Exception e) {
2865             result.Error(e);
2866        }
2867    #else
2868        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2869    #endif
2870        return result.Produce();
2871  }  }
2872    
2873  String LSCPServer::QueryDatabase(String query) {  String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
2874        dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
2875      LSCPResultSet result;      LSCPResultSet result;
2876  #if HAVE_SQLITE3  #if HAVE_SQLITE3
2877      char* zErrMsg = NULL;      try {
2878      sqlite3 *db;          ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
     String selectStr = "SELECT " + query;  
2879    
2880      int rc = sqlite3_open("linuxsampler.db", &db);          result.Add("FILES_TOTAL", job.FilesTotal);
2881      if (rc == SQLITE_OK)          result.Add("FILES_SCANNED", job.FilesScanned);
2882      {          result.Add("SCANNING", job.Scanning);
2883              rc = sqlite3_exec(db, selectStr.c_str(), select_callback, &result, &zErrMsg);          result.Add("STATUS", job.Status);
2884        } catch (Exception e) {
2885             result.Error(e);
2886      }      }
2887      if ( rc != SQLITE_OK )  #else
2888      {      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2889              result.Error(String(zErrMsg), rc);  #endif
2890        return result.Produce();
2891    }
2892    
2893    String LSCPServer::SetDbInstrumentName(String Instr, String Name) {
2894        dmsg(2,("LSCPServer: SetDbInstrumentName(Instr=%s,Name=%s)\n", Instr.c_str(), Name.c_str()));
2895        LSCPResultSet result;
2896    #if HAVE_SQLITE3
2897        try {
2898            InstrumentsDb::GetInstrumentsDb()->RenameInstrument(Instr, Name);
2899        } catch (Exception e) {
2900             result.Error(e);
2901        }
2902    #else
2903        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2904    #endif
2905        return result.Produce();
2906    }
2907    
2908    String LSCPServer::MoveDbInstrument(String Instr, String Dst) {
2909        dmsg(2,("LSCPServer: MoveDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
2910        LSCPResultSet result;
2911    #if HAVE_SQLITE3
2912        try {
2913            InstrumentsDb::GetInstrumentsDb()->MoveInstrument(Instr, Dst);
2914        } catch (Exception e) {
2915             result.Error(e);
2916      }      }
     sqlite3_close(db);  
2917  #else  #else
2918      result.Error(String("SQLITE3 was not installed when linuxsampler was built. SELECT statement is not available."), 0);      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2919  #endif  #endif
2920      return result.Produce();      return result.Produce();
2921  }  }
2922    
2923    String LSCPServer::CopyDbInstrument(String Instr, String Dst) {
2924        dmsg(2,("LSCPServer: CopyDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
2925        LSCPResultSet result;
2926    #if HAVE_SQLITE3
2927        try {
2928            InstrumentsDb::GetInstrumentsDb()->CopyInstrument(Instr, Dst);
2929        } catch (Exception e) {
2930             result.Error(e);
2931        }
2932    #else
2933        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2934    #endif
2935        return result.Produce();
2936    }
2937    
2938    String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {
2939        dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
2940        LSCPResultSet result;
2941    #if HAVE_SQLITE3
2942        try {
2943            InstrumentsDb::GetInstrumentsDb()->SetInstrumentDescription(Instr, Desc);
2944        } catch (Exception e) {
2945             result.Error(e);
2946        }
2947    #else
2948        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2949    #endif
2950        return result.Produce();
2951    }
2952    
2953    String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
2954        dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
2955        LSCPResultSet result;
2956    #if HAVE_SQLITE3
2957        try {
2958            SearchQuery Query;
2959            std::map<String,String>::iterator iter;
2960            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
2961                if (iter->first.compare("NAME") == 0) {
2962                    Query.Name = iter->second;
2963                } else if (iter->first.compare("CREATED") == 0) {
2964                    Query.SetCreated(iter->second);
2965                } else if (iter->first.compare("MODIFIED") == 0) {
2966                    Query.SetModified(iter->second);
2967                } else if (iter->first.compare("DESCRIPTION") == 0) {
2968                    Query.Description = iter->second;
2969                } else {
2970                    throw Exception("Unknown search criteria: " + iter->first);
2971                }
2972            }
2973    
2974            String list;
2975            StringListPtr pDirectories =
2976                InstrumentsDb::GetInstrumentsDb()->FindDirectories(Dir, &Query, Recursive);
2977    
2978            for (int i = 0; i < pDirectories->size(); i++) {
2979                if (list != "") list += ",";
2980                list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
2981            }
2982    
2983            result.Add(list);
2984        } catch (Exception e) {
2985             result.Error(e);
2986        }
2987    #else
2988        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2989    #endif
2990        return result.Produce();
2991    }
2992    
2993    String LSCPServer::FindDbInstruments(String Dir, std::map<String,String> Parameters, bool Recursive) {
2994        dmsg(2,("LSCPServer: FindDbInstruments(Dir=%s)\n", Dir.c_str()));
2995        LSCPResultSet result;
2996    #if HAVE_SQLITE3
2997        try {
2998            SearchQuery Query;
2999            std::map<String,String>::iterator iter;
3000            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3001                if (iter->first.compare("NAME") == 0) {
3002                    Query.Name = iter->second;
3003                } else if (iter->first.compare("FORMAT_FAMILIES") == 0) {
3004                    Query.SetFormatFamilies(iter->second);
3005                } else if (iter->first.compare("SIZE") == 0) {
3006                    Query.SetSize(iter->second);
3007                } else if (iter->first.compare("CREATED") == 0) {
3008                    Query.SetCreated(iter->second);
3009                } else if (iter->first.compare("MODIFIED") == 0) {
3010                    Query.SetModified(iter->second);
3011                } else if (iter->first.compare("DESCRIPTION") == 0) {
3012                    Query.Description = iter->second;
3013                } else if (iter->first.compare("IS_DRUM") == 0) {
3014                    if (!strcasecmp(iter->second.c_str(), "true")) {
3015                        Query.InstrType = SearchQuery::DRUM;
3016                    } else {
3017                        Query.InstrType = SearchQuery::CHROMATIC;
3018                    }
3019                } else if (iter->first.compare("PRODUCT") == 0) {
3020                     Query.Product = iter->second;
3021                } else if (iter->first.compare("ARTISTS") == 0) {
3022                     Query.Artists = iter->second;
3023                } else if (iter->first.compare("KEYWORDS") == 0) {
3024                     Query.Keywords = iter->second;
3025                } else {
3026                    throw Exception("Unknown search criteria: " + iter->first);
3027                }
3028            }
3029    
3030            String list;
3031            StringListPtr pInstruments =
3032                InstrumentsDb::GetInstrumentsDb()->FindInstruments(Dir, &Query, Recursive);
3033    
3034            for (int i = 0; i < pInstruments->size(); i++) {
3035                if (list != "") list += ",";
3036                list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
3037            }
3038    
3039            result.Add(list);
3040        } catch (Exception e) {
3041             result.Error(e);
3042        }
3043    #else
3044        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3045    #endif
3046        return result.Produce();
3047    }
3048    
3049    String LSCPServer::FormatInstrumentsDb() {
3050        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3051        LSCPResultSet result;
3052    #if HAVE_SQLITE3
3053        try {
3054            InstrumentsDb::GetInstrumentsDb()->Format();
3055        } catch (Exception e) {
3056             result.Error(e);
3057        }
3058    #else
3059        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3060    #endif
3061        return result.Produce();
3062    }
3063    
3064    
3065  /**  /**
3066   * 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
3067   * 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.973  
changed lines
  Added in v.1649

  ViewVC Help
Powered by ViewVC