/[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 1133 by iliev, Mon Mar 26 08:27:06 2007 UTC revision 1686 by schoenebeck, Thu Feb 14 14:58:50 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 - 2007 Christian Schoenebeck                       *   *   Copyright (C) 2005 - 2008 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 61  Mutex LSCPServer::NotifyBufferMutex = Mu Line 101  Mutex LSCPServer::NotifyBufferMutex = Mu
101  Mutex LSCPServer::SubscriptionMutex = Mutex();  Mutex LSCPServer::SubscriptionMutex = Mutex();
102  Mutex LSCPServer::RTNotifyMutex = Mutex();  Mutex LSCPServer::RTNotifyMutex = Mutex();
103    
104  LSCPServer::LSCPServer(Sampler* pSampler, long int addr, short int port) : Thread(true, false, 0, -4) {  LSCPServer::LSCPServer(Sampler* pSampler, long int addr, short int port) : Thread(true, false, 0, -4), eventHandler(this) {
105      SocketAddress.sin_family      = AF_INET;      SocketAddress.sin_family      = AF_INET;
106      SocketAddress.sin_addr.s_addr = addr;      SocketAddress.sin_addr.s_addr = addr;
107      SocketAddress.sin_port        = port;      SocketAddress.sin_port        = port;
# Line 81  LSCPServer::LSCPServer(Sampler* pSampler Line 121  LSCPServer::LSCPServer(Sampler* pSampler
121      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");
122      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");
123      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");
124        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_count, "DB_INSTRUMENT_DIRECTORY_COUNT");
125        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_info, "DB_INSTRUMENT_DIRECTORY_INFO");
126        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_count, "DB_INSTRUMENT_COUNT");
127        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
128        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
129      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
130        LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT");
131      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
132      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
133        LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");
134      hSocket = -1;      hSocket = -1;
135  }  }
136    
137  LSCPServer::~LSCPServer() {  LSCPServer::~LSCPServer() {
138    #if defined(WIN32)
139        if (hSocket >= 0) closesocket(hSocket);
140    #else
141      if (hSocket >= 0) close(hSocket);      if (hSocket >= 0) close(hSocket);
142    #endif
143    }
144    
145    LSCPServer::EventHandler::EventHandler(LSCPServer* pParent) {
146        this->pParent = pParent;
147    }
148    
149    LSCPServer::EventHandler::~EventHandler() {
150        std::vector<midi_listener_entry> l = channelMidiListeners;
151        channelMidiListeners.clear();
152        for (int i = 0; i < l.size(); i++)
153            delete l[i].pMidiListener;
154  }  }
155    
156  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
157      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
158  }  }
159    
160    void LSCPServer::EventHandler::ChannelAdded(SamplerChannel* pChannel) {
161        pChannel->AddEngineChangeListener(this);
162    }
163    
164    void LSCPServer::EventHandler::ChannelToBeRemoved(SamplerChannel* pChannel) {
165        if (!pChannel->GetEngineChannel()) return;
166        EngineToBeChanged(pChannel->Index());
167    }
168    
169    void LSCPServer::EventHandler::EngineToBeChanged(int ChannelId) {
170        SamplerChannel* pSamplerChannel =
171            pParent->pSampler->GetSamplerChannel(ChannelId);
172        if (!pSamplerChannel) return;
173        EngineChannel* pEngineChannel =
174            pSamplerChannel->GetEngineChannel();
175        if (!pEngineChannel) return;
176        for (std::vector<midi_listener_entry>::iterator iter = channelMidiListeners.begin(); iter != channelMidiListeners.end(); ++iter) {
177            if ((*iter).pEngineChannel == pEngineChannel) {
178                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
179                pEngineChannel->Disconnect(pMidiListener);
180                channelMidiListeners.erase(iter);
181                delete pMidiListener;
182                return;
183            }
184        }
185    }
186    
187    void LSCPServer::EventHandler::EngineChanged(int ChannelId) {
188        SamplerChannel* pSamplerChannel =
189            pParent->pSampler->GetSamplerChannel(ChannelId);
190        if (!pSamplerChannel) return;
191        EngineChannel* pEngineChannel =
192            pSamplerChannel->GetEngineChannel();
193        if (!pEngineChannel) return;
194        VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
195        pEngineChannel->Connect(pMidiListener);
196        midi_listener_entry entry = {
197            pSamplerChannel, pEngineChannel, pMidiListener
198        };
199        channelMidiListeners.push_back(entry);
200    }
201    
202  void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {  void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
203      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
204  }  }
# Line 139  void LSCPServer::EventHandler::TotalVoic Line 243  void LSCPServer::EventHandler::TotalVoic
243      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));      LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
244  }  }
245    
246    void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
247        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
248    }
249    
250    #if HAVE_SQLITE3
251    void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
252        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
253    }
254    
255    void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {
256        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, InstrumentsDb::toEscapedPath(Dir)));
257    }
258    
259    void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {
260        Dir = "'" + InstrumentsDb::toEscapedPath(Dir) + "'";
261        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
262        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));
263    }
264    
265    void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {
266        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, InstrumentsDb::toEscapedPath(Dir)));
267    }
268    
269    void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {
270        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, InstrumentsDb::toEscapedPath(Instr)));
271    }
272    
273    void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {
274        Instr = "'" + InstrumentsDb::toEscapedPath(Instr) + "'";
275        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
276        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));
277    }
278    
279    void LSCPServer::DbInstrumentsEventHandler::JobStatusChanged(int JobId) {
280        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instrs_job_info, JobId));
281    }
282    #endif // HAVE_SQLITE3
283    
284    
285  /**  /**
286   * Blocks the calling thread until the LSCP Server is initialized and   * Blocks the calling thread until the LSCP Server is initialized and
# Line 155  int LSCPServer::WaitUntilInitialized(lon Line 297  int LSCPServer::WaitUntilInitialized(lon
297  }  }
298    
299  int LSCPServer::Main() {  int LSCPServer::Main() {
300            #if defined(WIN32)
301            WSADATA wsaData;
302            int iResult;
303            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
304            if (iResult != 0) {
305                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
306                    exit(EXIT_FAILURE);
307            }
308            #endif
309      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
310      if (hSocket < 0) {      if (hSocket < 0) {
311          std::cerr << "LSCPServer: Could not create server socket." << std::endl;          std::cerr << "LSCPServer: Could not create server socket." << std::endl;
# Line 168  int LSCPServer::Main() { Line 319  int LSCPServer::Main() {
319              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
320                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
321                      std::cerr << "gave up!" << std::endl;                      std::cerr << "gave up!" << std::endl;
322                        #if defined(WIN32)
323                        closesocket(hSocket);
324                        #else
325                      close(hSocket);                      close(hSocket);
326                        #endif
327                      //return -1;                      //return -1;
328                      exit(EXIT_FAILURE);                      exit(EXIT_FAILURE);
329                  }                  }
# Line 180  int LSCPServer::Main() { Line 335  int LSCPServer::Main() {
335    
336      listen(hSocket, 1);      listen(hSocket, 1);
337      Initialized.Set(true);      Initialized.Set(true);
338        
339      // Registering event listeners      // Registering event listeners
340      pSampler->AddChannelCountListener(&eventHandler);      pSampler->AddChannelCountListener(&eventHandler);
341      pSampler->AddAudioDeviceCountListener(&eventHandler);      pSampler->AddAudioDeviceCountListener(&eventHandler);
# Line 188  int LSCPServer::Main() { Line 343  int LSCPServer::Main() {
343      pSampler->AddVoiceCountListener(&eventHandler);      pSampler->AddVoiceCountListener(&eventHandler);
344      pSampler->AddStreamCountListener(&eventHandler);      pSampler->AddStreamCountListener(&eventHandler);
345      pSampler->AddBufferFillListener(&eventHandler);      pSampler->AddBufferFillListener(&eventHandler);
346        pSampler->AddTotalStreamCountListener(&eventHandler);
347      pSampler->AddTotalVoiceCountListener(&eventHandler);      pSampler->AddTotalVoiceCountListener(&eventHandler);
348      pSampler->AddFxSendCountListener(&eventHandler);      pSampler->AddFxSendCountListener(&eventHandler);
349      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);      MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
350      MidiInstrumentMapper::AddMidiInstrumentInfoListener(&eventHandler);      MidiInstrumentMapper::AddMidiInstrumentInfoListener(&eventHandler);
351      MidiInstrumentMapper::AddMidiInstrumentMapCountListener(&eventHandler);      MidiInstrumentMapper::AddMidiInstrumentMapCountListener(&eventHandler);
352      MidiInstrumentMapper::AddMidiInstrumentMapInfoListener(&eventHandler);      MidiInstrumentMapper::AddMidiInstrumentMapInfoListener(&eventHandler);
353    #if HAVE_SQLITE3
354        InstrumentsDb::GetInstrumentsDb()->AddInstrumentsDbListener(&dbInstrumentsEventHandler);
355    #endif
356      // now wait for client connections and handle their requests      // now wait for client connections and handle their requests
357      sockaddr_in client;      sockaddr_in client;
358      int length = sizeof(client);      int length = sizeof(client);
# Line 205  int LSCPServer::Main() { Line 363  int LSCPServer::Main() {
363      timeval timeout;      timeval timeout;
364    
365      while (true) {      while (true) {
366            #if CONFIG_PTHREAD_TESTCANCEL
367                    TestCancel();
368            #endif
369          // 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
370          {          {
371              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
# Line 226  int LSCPServer::Main() { Line 387  int LSCPServer::Main() {
387              }              }
388          }          }
389    
390            // check if MIDI data arrived on some engine channel
391            for (int i = 0; i < eventHandler.channelMidiListeners.size(); ++i) {
392                const EventHandler::midi_listener_entry entry =
393                    eventHandler.channelMidiListeners[i];
394                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
395                if (pMidiListener->NotesChanged()) {
396                    for (int iNote = 0; iNote < 128; iNote++) {
397                        if (pMidiListener->NoteChanged(iNote)) {
398                            const bool bActive = pMidiListener->NoteIsActive(iNote);
399                            LSCPServer::SendLSCPNotify(
400                                LSCPEvent(
401                                    LSCPEvent::event_channel_midi,
402                                    entry.pSamplerChannel->Index(),
403                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
404                                    iNote,
405                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
406                                            : pMidiListener->NoteOffVelocity(iNote)
407                                )
408                            );
409                        }
410                    }
411                }
412            }
413    
414          //Now let's deliver late notifies (if any)          //Now let's deliver late notifies (if any)
415          NotifyBufferMutex.Lock();          NotifyBufferMutex.Lock();
416          for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {          for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {
# Line 248  int LSCPServer::Main() { Line 433  int LSCPServer::Main() {
433                  continue; //Nothing try again                  continue; //Nothing try again
434          if (retval == -1) {          if (retval == -1) {
435                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
436                    #if defined(WIN32)
437                    closesocket(hSocket);
438                    #else
439                  close(hSocket);                  close(hSocket);
440                    #endif
441                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
442          }          }
443    
# Line 260  int LSCPServer::Main() { Line 449  int LSCPServer::Main() {
449                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
450                  }                  }
451    
452                    #if defined(WIN32)
453                    u_long nonblock_io = 1;
454                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
455                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
456                      exit(EXIT_FAILURE);
457                    }
458            #else
459                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
460                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
461                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
462                  }                  }
463                    #endif
464    
465                  // Parser initialization                  // Parser initialization
466                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 287  int LSCPServer::Main() { Line 484  int LSCPServer::Main() {
484                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
485                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
486                                  currentSocket = (*iter).hSession;  //a hack                                  currentSocket = (*iter).hSession;  //a hack
487                                    itCurrentSession = iter; // another hack
488                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
489                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
490                                      AnswerClient(bufferedCommands[currentSocket]);                                      AnswerClient(bufferedCommands[currentSocket]);
491                                  }                                  }
492                                  int result = yyparse(&(*iter));                                  int result = yyparse(&(*iter));
493                                  currentSocket = -1;     //continuation of a hack                                  currentSocket = -1;     //continuation of a hack
494                                    itCurrentSession = Sessions.end(); // hack as well
495                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
496                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?
497                                          CloseConnection(iter);                                          CloseConnection(iter);
# Line 320  void LSCPServer::CloseConnection( std::v Line 519  void LSCPServer::CloseConnection( std::v
519          NotifyMutex.Lock();          NotifyMutex.Lock();
520          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
521          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
522            #if defined(WIN32)
523            closesocket(socket);
524            #else
525          close(socket);          close(socket);
526            #endif
527          NotifyMutex.Unlock();          NotifyMutex.Unlock();
528  }  }
529    
530    void LSCPServer::LockRTNotify() {
531        RTNotifyMutex.Lock();
532    }
533    
534    void LSCPServer::UnlockRTNotify() {
535        RTNotifyMutex.Unlock();
536    }
537    
538  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
539          int subs = 0;          int subs = 0;
540          SubscriptionMutex.Lock();          SubscriptionMutex.Lock();
# Line 385  extern int GetLSCPCommand( void *buf, in Line 596  extern int GetLSCPCommand( void *buf, in
596          return command.size();          return command.size();
597  }  }
598    
599    extern yyparse_param_t* GetCurrentYaccSession() {
600        return &(*itCurrentSession);
601    }
602    
603  /**  /**
604   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
605   * 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 395  bool LSCPServer::GetLSCPCommand( std::ve Line 610  bool LSCPServer::GetLSCPCommand( std::ve
610          char c;          char c;
611          int i = 0;          int i = 0;
612          while (true) {          while (true) {
613                    #if defined(WIN32)
614                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
615                    #else
616                  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
617                    #endif
618                  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
619                          CloseConnection(iter);                          CloseConnection(iter);
620                          break;                          break;
# Line 410  bool LSCPServer::GetLSCPCommand( std::ve Line 629  bool LSCPServer::GetLSCPCommand( std::ve
629                          }                          }
630                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
631                  }                  }
632                    #if defined(WIN32)
633                    if (result == SOCKET_ERROR) {
634                        int wsa_lasterror = WSAGetLastError();
635                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
636                                    return false;
637                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
638                            CloseConnection(iter);
639                            break;
640                    }
641                    #else
642                  if (result == -1) {                  if (result == -1) {
643                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
644                                  return false;                                  return false;
# Line 448  bool LSCPServer::GetLSCPCommand( std::ve Line 677  bool LSCPServer::GetLSCPCommand( std::ve
677                          CloseConnection(iter);                          CloseConnection(iter);
678                          break;                          break;
679                  }                  }
680                    #endif
681          }          }
682          return false;          return false;
683  }  }
# Line 565  String LSCPServer::DestroyMidiInputDevic Line 795  String LSCPServer::DestroyMidiInputDevic
795      return result.Produce();      return result.Produce();
796  }  }
797    
798    EngineChannel* LSCPServer::GetEngineChannel(uint uiSamplerChannel) {
799        SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
800        if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
801    
802        EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
803        if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
804    
805        return pEngineChannel;
806    }
807    
808  /**  /**
809   * Will be called by the parser to load an instrument.   * Will be called by the parser to load an instrument.
810   */   */
# Line 711  String LSCPServer::GetEngineInfo(String Line 951  String LSCPServer::GetEngineInfo(String
951      LockRTNotify();      LockRTNotify();
952      try {      try {
953          Engine* pEngine = EngineFactory::Create(EngineName);          Engine* pEngine = EngineFactory::Create(EngineName);
954          result.Add("DESCRIPTION", pEngine->Description());          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
955          result.Add("VERSION",     pEngine->Version());          result.Add("VERSION",     pEngine->Version());
956          EngineFactory::Destroy(pEngine);          EngineFactory::Destroy(pEngine);
957      }      }
# Line 784  String LSCPServer::GetChannelInfo(uint u Line 1024  String LSCPServer::GetChannelInfo(uint u
1024          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
1025          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
1026    
1027            // convert the filename into the correct encoding as defined for LSCP
1028            // (especially in terms of special characters -> escape sequences)
1029            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
1030    #if WIN32
1031                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
1032    #else
1033                // assuming POSIX
1034                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
1035    #endif
1036            }
1037    
1038          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
1039          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
1040          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
1041          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
1042          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
1043          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
# Line 1728  String LSCPServer::GetMidiInstrumentMapp Line 1979  String LSCPServer::GetMidiInstrumentMapp
1979          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);
1980          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");
1981          else { // found          else { // found
1982              result.Add("NAME", iter->second.Name);  
1983                // convert the filename into the correct encoding as defined for LSCP
1984                // (especially in terms of special characters -> escape sequences)
1985    #if WIN32
1986                const String instrumentFileName = Path::fromWindows(iter->second.InstrumentFile).toLscp();
1987    #else
1988                // assuming POSIX
1989                const String instrumentFileName = Path::fromPosix(iter->second.InstrumentFile).toLscp();
1990    #endif
1991    
1992                result.Add("NAME", _escapeLscpResponse(iter->second.Name));
1993              result.Add("ENGINE_NAME", iter->second.EngineName);              result.Add("ENGINE_NAME", iter->second.EngineName);
1994              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);              result.Add("INSTRUMENT_FILE", instrumentFileName);
1995              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);
1996              String instrumentName;              String instrumentName;
1997              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);
# Line 1743  String LSCPServer::GetMidiInstrumentMapp Line 2004  String LSCPServer::GetMidiInstrumentMapp
2004                  }                  }
2005                  EngineFactory::Destroy(pEngine);                  EngineFactory::Destroy(pEngine);
2006              }              }
2007              result.Add("INSTRUMENT_NAME", instrumentName);              result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
2008              switch (iter->second.LoadMode) {              switch (iter->second.LoadMode) {
2009                  case MidiInstrumentMapper::ON_DEMAND:                  case MidiInstrumentMapper::ON_DEMAND:
2010                      result.Add("LOAD_MODE", "ON_DEMAND");                      result.Add("LOAD_MODE", "ON_DEMAND");
# Line 1898  String LSCPServer::GetMidiInstrumentMap( Line 2159  String LSCPServer::GetMidiInstrumentMap(
2159      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2160      LSCPResultSet result;      LSCPResultSet result;
2161      try {      try {
2162          result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID));          result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2163            result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2164      } catch (Exception e) {      } catch (Exception e) {
2165          result.Error(e);          result.Error(e);
2166      }      }
# Line 1947  String LSCPServer::CreateFxSend(uint uiS Line 2209  String LSCPServer::CreateFxSend(uint uiS
2209      dmsg(2,("LSCPServer: CreateFxSend()\n"));      dmsg(2,("LSCPServer: CreateFxSend()\n"));
2210      LSCPResultSet result;      LSCPResultSet result;
2211      try {      try {
2212          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");  
2213    
2214          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2215          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 1967  String LSCPServer::DestroyFxSend(uint ui Line 2225  String LSCPServer::DestroyFxSend(uint ui
2225      dmsg(2,("LSCPServer: DestroyFxSend()\n"));      dmsg(2,("LSCPServer: DestroyFxSend()\n"));
2226      LSCPResultSet result;      LSCPResultSet result;
2227      try {      try {
2228          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");  
2229    
2230          FxSend* pFxSend = NULL;          FxSend* pFxSend = NULL;
2231          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
# Line 1992  String LSCPServer::GetFxSends(uint uiSam Line 2246  String LSCPServer::GetFxSends(uint uiSam
2246      dmsg(2,("LSCPServer: GetFxSends()\n"));      dmsg(2,("LSCPServer: GetFxSends()\n"));
2247      LSCPResultSet result;      LSCPResultSet result;
2248      try {      try {
2249          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");  
2250    
2251          result.Add(pEngineChannel->GetFxSendCount());          result.Add(pEngineChannel->GetFxSendCount());
2252      } catch (Exception e) {      } catch (Exception e) {
# Line 2010  String LSCPServer::ListFxSends(uint uiSa Line 2260  String LSCPServer::ListFxSends(uint uiSa
2260      LSCPResultSet result;      LSCPResultSet result;
2261      String list;      String list;
2262      try {      try {
2263          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");  
2264    
2265          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2266              FxSend* pFxSend = pEngineChannel->GetFxSend(i);              FxSend* pFxSend = pEngineChannel->GetFxSend(i);
# Line 2028  String LSCPServer::ListFxSends(uint uiSa Line 2274  String LSCPServer::ListFxSends(uint uiSa
2274      return result.Produce();      return result.Produce();
2275  }  }
2276    
2277    FxSend* LSCPServer::GetFxSend(uint uiSamplerChannel, uint FxSendID) {
2278        EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2279    
2280        FxSend* pFxSend = NULL;
2281        for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2282            if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2283                pFxSend = pEngineChannel->GetFxSend(i);
2284                break;
2285            }
2286        }
2287        if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2288        return pFxSend;
2289    }
2290    
2291  String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {  String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {
2292      dmsg(2,("LSCPServer: GetFxSendInfo()\n"));      dmsg(2,("LSCPServer: GetFxSendInfo()\n"));
2293      LSCPResultSet result;      LSCPResultSet result;
2294      try {      try {
2295          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2296          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");  
2297    
2298          // gather audio routing informations          // gather audio routing informations
2299          String AudioRouting;          String AudioRouting;
# Line 2055  String LSCPServer::GetFxSendInfo(uint ui Line 2303  String LSCPServer::GetFxSendInfo(uint ui
2303          }          }
2304    
2305          // success          // success
2306          result.Add("NAME", pFxSend->Name());          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2307          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2308          result.Add("LEVEL", ToString(pFxSend->Level()));          result.Add("LEVEL", ToString(pFxSend->Level()));
2309          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
# Line 2065  String LSCPServer::GetFxSendInfo(uint ui Line 2313  String LSCPServer::GetFxSendInfo(uint ui
2313      return result.Produce();      return result.Produce();
2314  }  }
2315    
2316  String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {  String LSCPServer::SetFxSendName(uint uiSamplerChannel, uint FxSendID, String Name) {
2317      dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));      dmsg(2,("LSCPServer: SetFxSendName()\n"));
2318      LSCPResultSet result;      LSCPResultSet result;
2319      try {      try {
2320          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
2321    
2322          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();          pFxSend->SetName(Name);
2323          if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2324        } catch (Exception e) {
2325            result.Error(e);
2326        }
2327        return result.Produce();
2328    }
2329    
2330          FxSend* pFxSend = NULL;  String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {
2331          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {      dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));
2332              if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {      LSCPResultSet result;
2333                  pFxSend = pEngineChannel->GetFxSend(i);      try {
2334                  break;          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
             }  
         }  
         if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");  
2335    
2336          pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);          pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);
2337          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
# Line 2096  String LSCPServer::SetFxSendMidiControll Line 2345  String LSCPServer::SetFxSendMidiControll
2345      dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));      dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));
2346      LSCPResultSet result;      LSCPResultSet result;
2347      try {      try {
2348          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
         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");  
   
         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");  
2349    
2350          pFxSend->SetMidiController(MidiController);          pFxSend->SetMidiController(MidiController);
2351          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
# Line 2123  String LSCPServer::SetFxSendLevel(uint u Line 2359  String LSCPServer::SetFxSendLevel(uint u
2359      dmsg(2,("LSCPServer: SetFxSendLevel()\n"));      dmsg(2,("LSCPServer: SetFxSendLevel()\n"));
2360      LSCPResultSet result;      LSCPResultSet result;
2361      try {      try {
2362          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
         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");  
   
         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");  
2363    
2364          pFxSend->SetLevel((float)dLevel);          pFxSend->SetLevel((float)dLevel);
2365          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
# Line 2146  String LSCPServer::SetFxSendLevel(uint u Line 2369  String LSCPServer::SetFxSendLevel(uint u
2369      return result.Produce();      return result.Produce();
2370  }  }
2371    
2372    String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2373        dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2374        LSCPResultSet result;
2375        try {
2376            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
2377            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
2378            EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
2379            if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
2380            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2381            Engine* pEngine = pEngineChannel->GetEngine();
2382            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2383            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2384            InstrumentManager::instrument_id_t instrumentID;
2385            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2386            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2387            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2388        } catch (Exception e) {
2389            result.Error(e);
2390        }
2391        return result.Produce();
2392    }
2393    
2394  /**  /**
2395   * Will be called by the parser to reset a particular sampler channel.   * Will be called by the parser to reset a particular sampler channel.
2396   */   */
# Line 2181  String LSCPServer::ResetSampler() { Line 2426  String LSCPServer::ResetSampler() {
2426   */   */
2427  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
2428      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
2429        const std::string description =
2430            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2431      LSCPResultSet result;      LSCPResultSet result;
2432      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
2433      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
2434      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2435    #if HAVE_SQLITE3
2436        result.Add("INSTRUMENTS_DB_SUPPORT", "yes");
2437    #else
2438        result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2439    #endif
2440    
2441        return result.Produce();
2442    }
2443    
2444    /**
2445     * Will be called by the parser to return the current number of all active streams.
2446     */
2447    String LSCPServer::GetTotalStreamCount() {
2448        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2449        LSCPResultSet result;
2450        result.Add(pSampler->GetDiskStreamCount());
2451      return result.Produce();      return result.Produce();
2452  }  }
2453    
# Line 2226  String LSCPServer::SetGlobalVolume(doubl Line 2489  String LSCPServer::SetGlobalVolume(doubl
2489      return result.Produce();      return result.Produce();
2490  }  }
2491    
2492    String LSCPServer::GetFileInstruments(String Filename) {
2493        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2494        LSCPResultSet result;
2495        try {
2496            VerifyFile(Filename);
2497        } catch (Exception e) {
2498            result.Error(e);
2499            return result.Produce();
2500        }
2501        // try to find a sampler engine that can handle the file
2502        bool bFound = false;
2503        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2504        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2505            Engine* pEngine = NULL;
2506            try {
2507                pEngine = EngineFactory::Create(engineTypes[i]);
2508                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2509                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2510                if (pManager) {
2511                    std::vector<InstrumentManager::instrument_id_t> IDs =
2512                        pManager->GetInstrumentFileContent(Filename);
2513                    // return the amount of instruments in the file
2514                    result.Add(IDs.size());
2515                    // no more need to ask other engine types
2516                    bFound = true;
2517                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2518            } catch (Exception e) {
2519                // NOOP, as exception is thrown if engine doesn't support file
2520            }
2521            if (pEngine) EngineFactory::Destroy(pEngine);
2522        }
2523    
2524        if (!bFound) result.Error("Unknown file format");
2525        return result.Produce();
2526    }
2527    
2528    String LSCPServer::ListFileInstruments(String Filename) {
2529        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2530        LSCPResultSet result;
2531        try {
2532            VerifyFile(Filename);
2533        } catch (Exception e) {
2534            result.Error(e);
2535            return result.Produce();
2536        }
2537        // try to find a sampler engine that can handle the file
2538        bool bFound = false;
2539        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2540        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2541            Engine* pEngine = NULL;
2542            try {
2543                pEngine = EngineFactory::Create(engineTypes[i]);
2544                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2545                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2546                if (pManager) {
2547                    std::vector<InstrumentManager::instrument_id_t> IDs =
2548                        pManager->GetInstrumentFileContent(Filename);
2549                    // return a list of IDs of the instruments in the file
2550                    String s;
2551                    for (int j = 0; j < IDs.size(); j++) {
2552                        if (s.size()) s += ",";
2553                        s += ToString(IDs[j].Index);
2554                    }
2555                    result.Add(s);
2556                    // no more need to ask other engine types
2557                    bFound = true;
2558                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2559            } catch (Exception e) {
2560                // NOOP, as exception is thrown if engine doesn't support file
2561            }
2562            if (pEngine) EngineFactory::Destroy(pEngine);
2563        }
2564    
2565        if (!bFound) result.Error("Unknown file format");
2566        return result.Produce();
2567    }
2568    
2569    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2570        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2571        LSCPResultSet result;
2572        try {
2573            VerifyFile(Filename);
2574        } catch (Exception e) {
2575            result.Error(e);
2576            return result.Produce();
2577        }
2578        InstrumentManager::instrument_id_t id;
2579        id.FileName = Filename;
2580        id.Index    = InstrumentID;
2581        // try to find a sampler engine that can handle the file
2582        bool bFound = false;
2583        bool bFatalErr = false;
2584        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2585        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2586            Engine* pEngine = NULL;
2587            try {
2588                pEngine = EngineFactory::Create(engineTypes[i]);
2589                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2590                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2591                if (pManager) {
2592                    // check if the instrument index is valid
2593                    // FIXME: this won't work if an engine only supports parts of the instrument file
2594                    std::vector<InstrumentManager::instrument_id_t> IDs =
2595                        pManager->GetInstrumentFileContent(Filename);
2596                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2597                        std::stringstream ss;
2598                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2599                        bFatalErr = true;
2600                        throw Exception(ss.str());
2601                    }
2602                    // get the info of the requested instrument
2603                    InstrumentManager::instrument_info_t info =
2604                        pManager->GetInstrumentInfo(id);
2605                    // return detailed informations about the file
2606                    result.Add("NAME", info.InstrumentName);
2607                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2608                    result.Add("FORMAT_VERSION", info.FormatVersion);
2609                    result.Add("PRODUCT", info.Product);
2610                    result.Add("ARTISTS", info.Artists);
2611                    // no more need to ask other engine types
2612                    bFound = true;
2613                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2614            } catch (Exception e) {
2615                // usually NOOP, as exception is thrown if engine doesn't support file
2616                if (bFatalErr) result.Error(e);
2617            }
2618            if (pEngine) EngineFactory::Destroy(pEngine);
2619        }
2620    
2621        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2622        return result.Produce();
2623    }
2624    
2625    void LSCPServer::VerifyFile(String Filename) {
2626        #if WIN32
2627        WIN32_FIND_DATA win32FileAttributeData;
2628        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2629        if (!res) {
2630            std::stringstream ss;
2631            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2632            throw Exception(ss.str());
2633        }
2634        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2635            throw Exception("Directory is specified");
2636        }
2637        #else
2638        struct stat statBuf;
2639        int res = stat(Filename.c_str(), &statBuf);
2640        if (res) {
2641            std::stringstream ss;
2642            ss << "Fail to stat `" << Filename << "`: " << strerror(errno);
2643            throw Exception(ss.str());
2644        }
2645    
2646        if (S_ISDIR(statBuf.st_mode)) {
2647            throw Exception("Directory is specified");
2648        }
2649        #endif
2650    }
2651    
2652  /**  /**
2653   * 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
2654   * server for receiving event messages.   * server for receiving event messages.
# Line 2252  String LSCPServer::UnsubscribeNotificati Line 2675  String LSCPServer::UnsubscribeNotificati
2675      return result.Produce();      return result.Produce();
2676  }  }
2677    
2678  static int select_callback(void * lscpResultSet, int argc,  String LSCPServer::AddDbInstrumentDirectory(String Dir) {
2679                          char **argv, char **azColName)      dmsg(2,("LSCPServer: AddDbInstrumentDirectory(Dir=%s)\n", Dir.c_str()));
2680  {      LSCPResultSet result;
2681      LSCPResultSet* resultSet = (LSCPResultSet*) lscpResultSet;  #if HAVE_SQLITE3
2682      resultSet->Add(argc, argv);      try {
2683      return 0;          InstrumentsDb::GetInstrumentsDb()->AddDirectory(Dir);
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::RemoveDbInstrumentDirectory(String Dir, bool Force) {
2694        dmsg(2,("LSCPServer: RemoveDbInstrumentDirectory(Dir=%s,Force=%d)\n", Dir.c_str(), Force));
2695        LSCPResultSet result;
2696    #if HAVE_SQLITE3
2697        try {
2698            InstrumentsDb::GetInstrumentsDb()->RemoveDirectory(Dir, Force);
2699        } catch (Exception e) {
2700             result.Error(e);
2701        }
2702    #else
2703        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2704    #endif
2705        return result.Produce();
2706    }
2707    
2708    String LSCPServer::GetDbInstrumentDirectoryCount(String Dir, bool Recursive) {
2709        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2710        LSCPResultSet result;
2711    #if HAVE_SQLITE3
2712        try {
2713            result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir, Recursive));
2714        } catch (Exception e) {
2715             result.Error(e);
2716        }
2717    #else
2718        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2719    #endif
2720        return result.Produce();
2721    }
2722    
2723    String LSCPServer::GetDbInstrumentDirectories(String Dir, bool Recursive) {
2724        dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2725        LSCPResultSet result;
2726    #if HAVE_SQLITE3
2727        try {
2728            String list;
2729            StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir, Recursive);
2730    
2731            for (int i = 0; i < dirs->size(); i++) {
2732                if (list != "") list += ",";
2733                list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2734            }
2735    
2736            result.Add(list);
2737        } catch (Exception e) {
2738             result.Error(e);
2739        }
2740    #else
2741        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2742    #endif
2743        return result.Produce();
2744    }
2745    
2746    String LSCPServer::GetDbInstrumentDirectoryInfo(String Dir) {
2747        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryInfo(Dir=%s)\n", Dir.c_str()));
2748        LSCPResultSet result;
2749    #if HAVE_SQLITE3
2750        try {
2751            DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2752    
2753            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2754            result.Add("CREATED", info.Created);
2755            result.Add("MODIFIED", info.Modified);
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::SetDbInstrumentDirectoryName(String Dir, String Name) {
2766        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryName(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
2767        LSCPResultSet result;
2768    #if HAVE_SQLITE3
2769        try {
2770            InstrumentsDb::GetInstrumentsDb()->RenameDirectory(Dir, Name);
2771        } catch (Exception e) {
2772             result.Error(e);
2773        }
2774    #else
2775        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2776    #endif
2777        return result.Produce();
2778    }
2779    
2780    String LSCPServer::MoveDbInstrumentDirectory(String Dir, String Dst) {
2781        dmsg(2,("LSCPServer: MoveDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2782        LSCPResultSet result;
2783    #if HAVE_SQLITE3
2784        try {
2785            InstrumentsDb::GetInstrumentsDb()->MoveDirectory(Dir, Dst);
2786        } catch (Exception e) {
2787             result.Error(e);
2788        }
2789    #else
2790        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2791    #endif
2792        return result.Produce();
2793    }
2794    
2795    String LSCPServer::CopyDbInstrumentDirectory(String Dir, String Dst) {
2796        dmsg(2,("LSCPServer: CopyDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2797        LSCPResultSet result;
2798    #if HAVE_SQLITE3
2799        try {
2800            InstrumentsDb::GetInstrumentsDb()->CopyDirectory(Dir, Dst);
2801        } catch (Exception e) {
2802             result.Error(e);
2803        }
2804    #else
2805        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2806    #endif
2807        return result.Produce();
2808    }
2809    
2810    String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {
2811        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
2812        LSCPResultSet result;
2813    #if HAVE_SQLITE3
2814        try {
2815            InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);
2816        } catch (Exception e) {
2817             result.Error(e);
2818        }
2819    #else
2820        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2821    #endif
2822        return result.Produce();
2823    }
2824    
2825    String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
2826        dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
2827        LSCPResultSet result;
2828    #if HAVE_SQLITE3
2829        try {
2830            int id;
2831            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2832            id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
2833            if (bBackground) result = id;
2834        } catch (Exception e) {
2835             result.Error(e);
2836        }
2837    #else
2838        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2839    #endif
2840        return result.Produce();
2841    }
2842    
2843    String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {
2844        dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground));
2845        LSCPResultSet result;
2846    #if HAVE_SQLITE3
2847        try {
2848            int id;
2849            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2850            if (ScanMode.compare("RECURSIVE") == 0) {
2851               id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);
2852            } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
2853               id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);
2854            } else if (ScanMode.compare("FLAT") == 0) {
2855               id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);
2856            } else {
2857                throw Exception("Unknown scan mode: " + ScanMode);
2858            }
2859    
2860            if (bBackground) result = id;
2861        } catch (Exception e) {
2862             result.Error(e);
2863        }
2864    #else
2865        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2866    #endif
2867        return result.Produce();
2868    }
2869    
2870    String LSCPServer::RemoveDbInstrument(String Instr) {
2871        dmsg(2,("LSCPServer: RemoveDbInstrument(Instr=%s)\n", Instr.c_str()));
2872        LSCPResultSet result;
2873    #if HAVE_SQLITE3
2874        try {
2875            InstrumentsDb::GetInstrumentsDb()->RemoveInstrument(Instr);
2876        } catch (Exception e) {
2877             result.Error(e);
2878        }
2879    #else
2880        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2881    #endif
2882        return result.Produce();
2883    }
2884    
2885    String LSCPServer::GetDbInstrumentCount(String Dir, bool Recursive) {
2886        dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2887        LSCPResultSet result;
2888    #if HAVE_SQLITE3
2889        try {
2890            result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir, Recursive));
2891        } catch (Exception e) {
2892             result.Error(e);
2893        }
2894    #else
2895        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2896    #endif
2897        return result.Produce();
2898    }
2899    
2900    String LSCPServer::GetDbInstruments(String Dir, bool Recursive) {
2901        dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2902        LSCPResultSet result;
2903    #if HAVE_SQLITE3
2904        try {
2905            String list;
2906            StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir, Recursive);
2907    
2908            for (int i = 0; i < instrs->size(); i++) {
2909                if (list != "") list += ",";
2910                list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
2911            }
2912    
2913            result.Add(list);
2914        } catch (Exception e) {
2915             result.Error(e);
2916        }
2917    #else
2918        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2919    #endif
2920        return result.Produce();
2921    }
2922    
2923    String LSCPServer::GetDbInstrumentInfo(String Instr) {
2924        dmsg(2,("LSCPServer: GetDbInstrumentInfo(Instr=%s)\n", Instr.c_str()));
2925        LSCPResultSet result;
2926    #if HAVE_SQLITE3
2927        try {
2928            DbInstrument info = InstrumentsDb::GetInstrumentsDb()->GetInstrumentInfo(Instr);
2929    
2930            result.Add("INSTRUMENT_FILE", info.InstrFile);
2931            result.Add("INSTRUMENT_NR", info.InstrNr);
2932            result.Add("FORMAT_FAMILY", info.FormatFamily);
2933            result.Add("FORMAT_VERSION", info.FormatVersion);
2934            result.Add("SIZE", (int)info.Size);
2935            result.Add("CREATED", info.Created);
2936            result.Add("MODIFIED", info.Modified);
2937            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2938            result.Add("IS_DRUM", info.IsDrum);
2939            result.Add("PRODUCT", _escapeLscpResponse(info.Product));
2940            result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
2941            result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
2942        } catch (Exception e) {
2943             result.Error(e);
2944        }
2945    #else
2946        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2947    #endif
2948        return result.Produce();
2949    }
2950    
2951    String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
2952        dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
2953        LSCPResultSet result;
2954    #if HAVE_SQLITE3
2955        try {
2956            ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
2957    
2958            result.Add("FILES_TOTAL", job.FilesTotal);
2959            result.Add("FILES_SCANNED", job.FilesScanned);
2960            result.Add("SCANNING", job.Scanning);
2961            result.Add("STATUS", job.Status);
2962        } catch (Exception e) {
2963             result.Error(e);
2964        }
2965    #else
2966        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2967    #endif
2968        return result.Produce();
2969    }
2970    
2971    String LSCPServer::SetDbInstrumentName(String Instr, String Name) {
2972        dmsg(2,("LSCPServer: SetDbInstrumentName(Instr=%s,Name=%s)\n", Instr.c_str(), Name.c_str()));
2973        LSCPResultSet result;
2974    #if HAVE_SQLITE3
2975        try {
2976            InstrumentsDb::GetInstrumentsDb()->RenameInstrument(Instr, Name);
2977        } catch (Exception e) {
2978             result.Error(e);
2979        }
2980    #else
2981        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2982    #endif
2983        return result.Produce();
2984    }
2985    
2986    String LSCPServer::MoveDbInstrument(String Instr, String Dst) {
2987        dmsg(2,("LSCPServer: MoveDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
2988        LSCPResultSet result;
2989    #if HAVE_SQLITE3
2990        try {
2991            InstrumentsDb::GetInstrumentsDb()->MoveInstrument(Instr, Dst);
2992        } catch (Exception e) {
2993             result.Error(e);
2994        }
2995    #else
2996        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2997    #endif
2998        return result.Produce();
2999  }  }
3000    
3001  String LSCPServer::QueryDatabase(String query) {  String LSCPServer::CopyDbInstrument(String Instr, String Dst) {
3002        dmsg(2,("LSCPServer: CopyDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3003      LSCPResultSet result;      LSCPResultSet result;
3004  #if HAVE_SQLITE3  #if HAVE_SQLITE3
3005      char* zErrMsg = NULL;      try {
3006      sqlite3 *db;          InstrumentsDb::GetInstrumentsDb()->CopyInstrument(Instr, Dst);
3007      String selectStr = "SELECT " + query;      } catch (Exception e) {
3008             result.Error(e);
3009        }
3010    #else
3011        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3012    #endif
3013        return result.Produce();
3014    }
3015    
3016      int rc = sqlite3_open("linuxsampler.db", &db);  String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {
3017      if (rc == SQLITE_OK)      dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
3018      {      LSCPResultSet result;
3019              rc = sqlite3_exec(db, selectStr.c_str(), select_callback, &result, &zErrMsg);  #if HAVE_SQLITE3
3020        try {
3021            InstrumentsDb::GetInstrumentsDb()->SetInstrumentDescription(Instr, Desc);
3022        } catch (Exception e) {
3023             result.Error(e);
3024      }      }
3025      if ( rc != SQLITE_OK )  #else
3026      {      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3027              result.Error(String(zErrMsg), rc);  #endif
3028        return result.Produce();
3029    }
3030    
3031    String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
3032        dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
3033        LSCPResultSet result;
3034    #if HAVE_SQLITE3
3035        try {
3036            SearchQuery Query;
3037            std::map<String,String>::iterator iter;
3038            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3039                if (iter->first.compare("NAME") == 0) {
3040                    Query.Name = iter->second;
3041                } else if (iter->first.compare("CREATED") == 0) {
3042                    Query.SetCreated(iter->second);
3043                } else if (iter->first.compare("MODIFIED") == 0) {
3044                    Query.SetModified(iter->second);
3045                } else if (iter->first.compare("DESCRIPTION") == 0) {
3046                    Query.Description = iter->second;
3047                } else {
3048                    throw Exception("Unknown search criteria: " + iter->first);
3049                }
3050            }
3051    
3052            String list;
3053            StringListPtr pDirectories =
3054                InstrumentsDb::GetInstrumentsDb()->FindDirectories(Dir, &Query, Recursive);
3055    
3056            for (int i = 0; i < pDirectories->size(); i++) {
3057                if (list != "") list += ",";
3058                list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
3059            }
3060    
3061            result.Add(list);
3062        } catch (Exception e) {
3063             result.Error(e);
3064      }      }
     sqlite3_close(db);  
3065  #else  #else
3066      result.Error(String("SQLITE3 was not installed when linuxsampler was built. SELECT statement is not available."), 0);      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3067  #endif  #endif
3068      return result.Produce();      return result.Produce();
3069  }  }
3070    
3071    String LSCPServer::FindDbInstruments(String Dir, std::map<String,String> Parameters, bool Recursive) {
3072        dmsg(2,("LSCPServer: FindDbInstruments(Dir=%s)\n", Dir.c_str()));
3073        LSCPResultSet result;
3074    #if HAVE_SQLITE3
3075        try {
3076            SearchQuery Query;
3077            std::map<String,String>::iterator iter;
3078            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3079                if (iter->first.compare("NAME") == 0) {
3080                    Query.Name = iter->second;
3081                } else if (iter->first.compare("FORMAT_FAMILIES") == 0) {
3082                    Query.SetFormatFamilies(iter->second);
3083                } else if (iter->first.compare("SIZE") == 0) {
3084                    Query.SetSize(iter->second);
3085                } else if (iter->first.compare("CREATED") == 0) {
3086                    Query.SetCreated(iter->second);
3087                } else if (iter->first.compare("MODIFIED") == 0) {
3088                    Query.SetModified(iter->second);
3089                } else if (iter->first.compare("DESCRIPTION") == 0) {
3090                    Query.Description = iter->second;
3091                } else if (iter->first.compare("IS_DRUM") == 0) {
3092                    if (!strcasecmp(iter->second.c_str(), "true")) {
3093                        Query.InstrType = SearchQuery::DRUM;
3094                    } else {
3095                        Query.InstrType = SearchQuery::CHROMATIC;
3096                    }
3097                } else if (iter->first.compare("PRODUCT") == 0) {
3098                     Query.Product = iter->second;
3099                } else if (iter->first.compare("ARTISTS") == 0) {
3100                     Query.Artists = iter->second;
3101                } else if (iter->first.compare("KEYWORDS") == 0) {
3102                     Query.Keywords = iter->second;
3103                } else {
3104                    throw Exception("Unknown search criteria: " + iter->first);
3105                }
3106            }
3107    
3108            String list;
3109            StringListPtr pInstruments =
3110                InstrumentsDb::GetInstrumentsDb()->FindInstruments(Dir, &Query, Recursive);
3111    
3112            for (int i = 0; i < pInstruments->size(); i++) {
3113                if (list != "") list += ",";
3114                list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
3115            }
3116    
3117            result.Add(list);
3118        } catch (Exception e) {
3119             result.Error(e);
3120        }
3121    #else
3122        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3123    #endif
3124        return result.Produce();
3125    }
3126    
3127    String LSCPServer::FormatInstrumentsDb() {
3128        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3129        LSCPResultSet result;
3130    #if HAVE_SQLITE3
3131        try {
3132            InstrumentsDb::GetInstrumentsDb()->Format();
3133        } catch (Exception e) {
3134             result.Error(e);
3135        }
3136    #else
3137        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3138    #endif
3139        return result.Produce();
3140    }
3141    
3142    
3143  /**  /**
3144   * 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
3145   * 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.1133  
changed lines
  Added in v.1686

  ViewVC Help
Powered by ViewVC