/[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 951 by persson, Tue Nov 28 20:55:19 2006 UTC revision 1848 by iliev, Sat Feb 28 21:23:06 2009 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 - 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 21  Line 21 
21   *   MA  02111-1307  USA                                                   *   *   MA  02111-1307  USA                                                   *
22   ***************************************************************************/   ***************************************************************************/
23    
24    #include <algorithm>
25    #include <string>
26    
27    #include "../common/File.h"
28  #include "lscpserver.h"  #include "lscpserver.h"
29  #include "lscpresultset.h"  #include "lscpresultset.h"
30  #include "lscpevent.h"  #include "lscpevent.h"
 //#include "../common/global.h"  
31    
32    #if defined(WIN32)
33    #include <windows.h>
34    #else
35  #include <fcntl.h>  #include <fcntl.h>
36    #endif
37    
38  #if HAVE_SQLITE3  #if ! HAVE_SQLITE3
39  # include "sqlite3.h"  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."
40  #endif  #endif
41    
42  #include "../engines/EngineFactory.h"  #include "../engines/EngineFactory.h"
# Line 37  Line 44 
44  #include "../drivers/audio/AudioOutputDeviceFactory.h"  #include "../drivers/audio/AudioOutputDeviceFactory.h"
45  #include "../drivers/midi/MidiInputDeviceFactory.h"  #include "../drivers/midi/MidiInputDeviceFactory.h"
46    
47    namespace LinuxSampler {
48    
49    /**
50     * Returns a copy of the given string where all special characters are
51     * replaced by LSCP escape sequences ("\xHH"). This function shall be used
52     * to escape LSCP response fields in case the respective response field is
53     * actually defined as using escape sequences in the LSCP specs.
54     *
55     * @e Caution: DO NOT use this function for escaping path based responses,
56     * use the Path class (src/common/Path.h) for this instead!
57     */
58    static String _escapeLscpResponse(String txt) {
59        for (int i = 0; i < txt.length(); i++) {
60            const char c = txt.c_str()[i];
61            if (
62                !(c >= '0' && c <= '9') &&
63                !(c >= 'a' && c <= 'z') &&
64                !(c >= 'A' && c <= 'Z') &&
65                !(c == ' ') && !(c == '!') && !(c == '#') && !(c == '$') &&
66                !(c == '%') && !(c == '&') && !(c == '(') && !(c == ')') &&
67                !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&
68                !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&
69                !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&
70                !(c == '@') && !(c == '[') && !(c == ']') &&
71                !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&
72                !(c == '|') && !(c == '}') && !(c == '~')
73            ) {
74                // convert the "special" character into a "\xHH" LSCP escape sequence
75                char buf[5];
76                snprintf(buf, sizeof(buf), "\\x%02x", static_cast<unsigned char>(c));
77                txt.replace(i, 1, buf);
78                i += 3;
79            }
80        }
81        return txt;
82    }
83    
84  /**  /**
85   * Below are a few static members of the LSCPServer class.   * Below are a few static members of the LSCPServer class.
86   * 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 97 
97  fd_set LSCPServer::fdSet;  fd_set LSCPServer::fdSet;
98  int LSCPServer::currentSocket = -1;  int LSCPServer::currentSocket = -1;
99  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();  std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();
100    std::vector<yyparse_param_t>::iterator itCurrentSession = std::vector<yyparse_param_t>::iterator();
101  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();
102  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();  std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();
103  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 106  Mutex LSCPServer::NotifyBufferMutex = Mu
106  Mutex LSCPServer::SubscriptionMutex = Mutex();  Mutex LSCPServer::SubscriptionMutex = Mutex();
107  Mutex LSCPServer::RTNotifyMutex = Mutex();  Mutex LSCPServer::RTNotifyMutex = Mutex();
108    
109  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) {
110      SocketAddress.sin_family      = AF_INET;      SocketAddress.sin_family      = AF_INET;
111      SocketAddress.sin_addr.s_addr = addr;      SocketAddress.sin_addr.s_addr = addr;
112      SocketAddress.sin_port        = port;      SocketAddress.sin_port        = port;
113      this->pSampler = pSampler;      this->pSampler = pSampler;
114        LSCPEvent::RegisterEvent(LSCPEvent::event_audio_device_count, "AUDIO_OUTPUT_DEVICE_COUNT");
115        LSCPEvent::RegisterEvent(LSCPEvent::event_audio_device_info, "AUDIO_OUTPUT_DEVICE_INFO");
116        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_device_count, "MIDI_INPUT_DEVICE_COUNT");
117        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_device_info, "MIDI_INPUT_DEVICE_INFO");
118      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_count, "CHANNEL_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_count, "CHANNEL_COUNT");
119      LSCPEvent::RegisterEvent(LSCPEvent::event_voice_count, "VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_voice_count, "VOICE_COUNT");
120      LSCPEvent::RegisterEvent(LSCPEvent::event_stream_count, "STREAM_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_stream_count, "STREAM_COUNT");
121      LSCPEvent::RegisterEvent(LSCPEvent::event_buffer_fill, "BUFFER_FILL");      LSCPEvent::RegisterEvent(LSCPEvent::event_buffer_fill, "BUFFER_FILL");
122      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_info, "CHANNEL_INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_info, "CHANNEL_INFO");
123        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_send_count, "FX_SEND_COUNT");
124        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_send_info, "FX_SEND_INFO");
125        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_count, "MIDI_INSTRUMENT_MAP_COUNT");
126        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");
127        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");
128        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");
129        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_count, "DB_INSTRUMENT_DIRECTORY_COUNT");
130        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_info, "DB_INSTRUMENT_DIRECTORY_INFO");
131        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_count, "DB_INSTRUMENT_COUNT");
132        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
133        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
134      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
135        LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT");
136      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
137        LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
138        LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");
139        LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI");
140      hSocket = -1;      hSocket = -1;
141  }  }
142    
143  LSCPServer::~LSCPServer() {  LSCPServer::~LSCPServer() {
144        CloseAllConnections();
145    #if defined(WIN32)
146        if (hSocket >= 0) closesocket(hSocket);
147    #else
148      if (hSocket >= 0) close(hSocket);      if (hSocket >= 0) close(hSocket);
149    #endif
150    }
151    
152    LSCPServer::EventHandler::EventHandler(LSCPServer* pParent) {
153        this->pParent = pParent;
154    }
155    
156    LSCPServer::EventHandler::~EventHandler() {
157        std::vector<midi_listener_entry> l = channelMidiListeners;
158        channelMidiListeners.clear();
159        for (int i = 0; i < l.size(); i++)
160            delete l[i].pMidiListener;
161    }
162    
163    void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
164        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
165    }
166    
167    void LSCPServer::EventHandler::ChannelAdded(SamplerChannel* pChannel) {
168        pChannel->AddEngineChangeListener(this);
169    }
170    
171    void LSCPServer::EventHandler::ChannelToBeRemoved(SamplerChannel* pChannel) {
172        if (!pChannel->GetEngineChannel()) return;
173        EngineToBeChanged(pChannel->Index());
174    }
175    
176    void LSCPServer::EventHandler::EngineToBeChanged(int ChannelId) {
177        SamplerChannel* pSamplerChannel =
178            pParent->pSampler->GetSamplerChannel(ChannelId);
179        if (!pSamplerChannel) return;
180        EngineChannel* pEngineChannel =
181            pSamplerChannel->GetEngineChannel();
182        if (!pEngineChannel) return;
183        for (std::vector<midi_listener_entry>::iterator iter = channelMidiListeners.begin(); iter != channelMidiListeners.end(); ++iter) {
184            if ((*iter).pEngineChannel == pEngineChannel) {
185                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
186                pEngineChannel->Disconnect(pMidiListener);
187                channelMidiListeners.erase(iter);
188                delete pMidiListener;
189                return;
190            }
191        }
192    }
193    
194    void LSCPServer::EventHandler::EngineChanged(int ChannelId) {
195        SamplerChannel* pSamplerChannel =
196            pParent->pSampler->GetSamplerChannel(ChannelId);
197        if (!pSamplerChannel) return;
198        EngineChannel* pEngineChannel =
199            pSamplerChannel->GetEngineChannel();
200        if (!pEngineChannel) return;
201        VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
202        pEngineChannel->Connect(pMidiListener);
203        midi_listener_entry entry = {
204            pSamplerChannel, pEngineChannel, pMidiListener
205        };
206        channelMidiListeners.push_back(entry);
207    }
208    
209    void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
210        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
211    }
212    
213    void LSCPServer::EventHandler::MidiDeviceCountChanged(int NewCount) {
214        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));
215    }
216    
217    void LSCPServer::EventHandler::MidiDeviceToBeDestroyed(MidiInputDevice* pDevice) {
218        pDevice->RemoveMidiPortCountListener(this);
219        for (int i = 0; i < pDevice->PortCount(); ++i)
220            MidiPortToBeRemoved(pDevice->GetPort(i));
221    }
222    
223    void LSCPServer::EventHandler::MidiDeviceCreated(MidiInputDevice* pDevice) {
224        pDevice->AddMidiPortCountListener(this);
225        for (int i = 0; i < pDevice->PortCount(); ++i)
226            MidiPortAdded(pDevice->GetPort(i));
227    }
228    
229    void LSCPServer::EventHandler::MidiPortCountChanged(int NewCount) {
230        // yet unused
231    }
232    
233    void LSCPServer::EventHandler::MidiPortToBeRemoved(MidiInputPort* pPort) {
234        for (std::vector<device_midi_listener_entry>::iterator iter = deviceMidiListeners.begin(); iter != deviceMidiListeners.end(); ++iter) {
235            if ((*iter).pPort == pPort) {
236                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
237                pPort->Disconnect(pMidiListener);
238                deviceMidiListeners.erase(iter);
239                delete pMidiListener;
240                return;
241            }
242        }
243    }
244    
245    void LSCPServer::EventHandler::MidiPortAdded(MidiInputPort* pPort) {
246        // find out the device ID
247        std::map<uint, MidiInputDevice*> devices =
248            pParent->pSampler->GetMidiInputDevices();
249        for (
250            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
251            iter != devices.end(); ++iter
252        ) {
253            if (iter->second == pPort->GetDevice()) { // found
254                VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
255                pPort->Connect(pMidiListener);
256                device_midi_listener_entry entry = {
257                    pPort, pMidiListener, iter->first
258                };
259                deviceMidiListeners.push_back(entry);
260                return;
261            }
262        }
263    }
264    
265    void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {
266        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));
267    }
268    
269    void LSCPServer::EventHandler::MidiInstrumentInfoChanged(int MapId, int Bank, int Program) {
270        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_info, MapId, Bank, Program));
271    }
272    
273    void LSCPServer::EventHandler::MidiInstrumentMapCountChanged(int NewCount) {
274        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_count, NewCount));
275    }
276    
277    void LSCPServer::EventHandler::MidiInstrumentMapInfoChanged(int MapId) {
278        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_info, MapId));
279    }
280    
281    void LSCPServer::EventHandler::FxSendCountChanged(int ChannelId, int NewCount) {
282        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_count, ChannelId, NewCount));
283    }
284    
285    void LSCPServer::EventHandler::VoiceCountChanged(int ChannelId, int NewCount) {
286        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_voice_count, ChannelId, NewCount));
287    }
288    
289    void LSCPServer::EventHandler::StreamCountChanged(int ChannelId, int NewCount) {
290        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_stream_count, ChannelId, NewCount));
291    }
292    
293    void LSCPServer::EventHandler::BufferFillChanged(int ChannelId, String FillData) {
294        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_buffer_fill, ChannelId, FillData));
295    }
296    
297    void LSCPServer::EventHandler::TotalVoiceCountChanged(int NewCount) {
298        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
299    }
300    
301    void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
302        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
303    }
304    
305    #if HAVE_SQLITE3
306    void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
307        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
308    }
309    
310    void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {
311        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, InstrumentsDb::toEscapedPath(Dir)));
312    }
313    
314    void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {
315        Dir = "'" + InstrumentsDb::toEscapedPath(Dir) + "'";
316        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
317        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));
318    }
319    
320    void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {
321        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, InstrumentsDb::toEscapedPath(Dir)));
322    }
323    
324    void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {
325        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, InstrumentsDb::toEscapedPath(Instr)));
326    }
327    
328    void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {
329        Instr = "'" + InstrumentsDb::toEscapedPath(Instr) + "'";
330        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
331        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));
332    }
333    
334    void LSCPServer::DbInstrumentsEventHandler::JobStatusChanged(int JobId) {
335        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instrs_job_info, JobId));
336    }
337    #endif // HAVE_SQLITE3
338    
339    void LSCPServer::RemoveListeners() {
340        pSampler->RemoveChannelCountListener(&eventHandler);
341        pSampler->RemoveAudioDeviceCountListener(&eventHandler);
342        pSampler->RemoveMidiDeviceCountListener(&eventHandler);
343        pSampler->RemoveVoiceCountListener(&eventHandler);
344        pSampler->RemoveStreamCountListener(&eventHandler);
345        pSampler->RemoveBufferFillListener(&eventHandler);
346        pSampler->RemoveTotalStreamCountListener(&eventHandler);
347        pSampler->RemoveTotalVoiceCountListener(&eventHandler);
348        pSampler->RemoveFxSendCountListener(&eventHandler);
349        MidiInstrumentMapper::RemoveMidiInstrumentCountListener(&eventHandler);
350        MidiInstrumentMapper::RemoveMidiInstrumentInfoListener(&eventHandler);
351        MidiInstrumentMapper::RemoveMidiInstrumentMapCountListener(&eventHandler);
352        MidiInstrumentMapper::RemoveMidiInstrumentMapInfoListener(&eventHandler);
353    #if HAVE_SQLITE3
354        InstrumentsDb::GetInstrumentsDb()->RemoveInstrumentsDbListener(&dbInstrumentsEventHandler);
355    #endif
356  }  }
357    
358  /**  /**
# Line 95  int LSCPServer::WaitUntilInitialized(lon Line 370  int LSCPServer::WaitUntilInitialized(lon
370  }  }
371    
372  int LSCPServer::Main() {  int LSCPServer::Main() {
373            #if defined(WIN32)
374            WSADATA wsaData;
375            int iResult;
376            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
377            if (iResult != 0) {
378                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
379                    exit(EXIT_FAILURE);
380            }
381            #endif
382      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
383      if (hSocket < 0) {      if (hSocket < 0) {
384          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 392  int LSCPServer::Main() {
392              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
393                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
394                      std::cerr << "gave up!" << std::endl;                      std::cerr << "gave up!" << std::endl;
395                        #if defined(WIN32)
396                        closesocket(hSocket);
397                        #else
398                      close(hSocket);                      close(hSocket);
399                        #endif
400                      //return -1;                      //return -1;
401                      exit(EXIT_FAILURE);                      exit(EXIT_FAILURE);
402                  }                  }
# Line 121  int LSCPServer::Main() { Line 409  int LSCPServer::Main() {
409      listen(hSocket, 1);      listen(hSocket, 1);
410      Initialized.Set(true);      Initialized.Set(true);
411    
412        // Registering event listeners
413        pSampler->AddChannelCountListener(&eventHandler);
414        pSampler->AddAudioDeviceCountListener(&eventHandler);
415        pSampler->AddMidiDeviceCountListener(&eventHandler);
416        pSampler->AddVoiceCountListener(&eventHandler);
417        pSampler->AddStreamCountListener(&eventHandler);
418        pSampler->AddBufferFillListener(&eventHandler);
419        pSampler->AddTotalStreamCountListener(&eventHandler);
420        pSampler->AddTotalVoiceCountListener(&eventHandler);
421        pSampler->AddFxSendCountListener(&eventHandler);
422        MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
423        MidiInstrumentMapper::AddMidiInstrumentInfoListener(&eventHandler);
424        MidiInstrumentMapper::AddMidiInstrumentMapCountListener(&eventHandler);
425        MidiInstrumentMapper::AddMidiInstrumentMapInfoListener(&eventHandler);
426    #if HAVE_SQLITE3
427        InstrumentsDb::GetInstrumentsDb()->AddInstrumentsDbListener(&dbInstrumentsEventHandler);
428    #endif
429      // now wait for client connections and handle their requests      // now wait for client connections and handle their requests
430      sockaddr_in client;      sockaddr_in client;
431      int length = sizeof(client);      int length = sizeof(client);
# Line 131  int LSCPServer::Main() { Line 436  int LSCPServer::Main() {
436      timeval timeout;      timeval timeout;
437    
438      while (true) {      while (true) {
439            #if CONFIG_PTHREAD_TESTCANCEL
440                    TestCancel();
441            #endif
442          // 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
443          {          {
444              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
# Line 138  int LSCPServer::Main() { Line 446  int LSCPServer::Main() {
446              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
447              for (; itEngineChannel != itEnd; ++itEngineChannel) {              for (; itEngineChannel != itEnd; ++itEngineChannel) {
448                  if ((*itEngineChannel)->StatusChanged()) {                  if ((*itEngineChannel)->StatusChanged()) {
449                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->GetSamplerChannel()->Index()));
450                    }
451    
452                    for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
453                        FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
454                        if(fxs != NULL && fxs->IsInfoChanged()) {
455                            int chn = (*itEngineChannel)->GetSamplerChannel()->Index();
456                            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
457                            fxs->SetInfoChanged(false);
458                        }
459                    }
460                }
461            }
462    
463            // check if MIDI data arrived on some engine channel
464            for (int i = 0; i < eventHandler.channelMidiListeners.size(); ++i) {
465                const EventHandler::midi_listener_entry entry =
466                    eventHandler.channelMidiListeners[i];
467                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
468                if (pMidiListener->NotesChanged()) {
469                    for (int iNote = 0; iNote < 128; iNote++) {
470                        if (pMidiListener->NoteChanged(iNote)) {
471                            const bool bActive = pMidiListener->NoteIsActive(iNote);
472                            LSCPServer::SendLSCPNotify(
473                                LSCPEvent(
474                                    LSCPEvent::event_channel_midi,
475                                    entry.pSamplerChannel->Index(),
476                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
477                                    iNote,
478                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
479                                            : pMidiListener->NoteOffVelocity(iNote)
480                                )
481                            );
482                        }
483                    }
484                }
485            }
486    
487            // check if MIDI data arrived on some MIDI device
488            for (int i = 0; i < eventHandler.deviceMidiListeners.size(); ++i) {
489                const EventHandler::device_midi_listener_entry entry =
490                    eventHandler.deviceMidiListeners[i];
491                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
492                if (pMidiListener->NotesChanged()) {
493                    for (int iNote = 0; iNote < 128; iNote++) {
494                        if (pMidiListener->NoteChanged(iNote)) {
495                            const bool bActive = pMidiListener->NoteIsActive(iNote);
496                            LSCPServer::SendLSCPNotify(
497                                LSCPEvent(
498                                    LSCPEvent::event_device_midi,
499                                    entry.uiDeviceID,
500                                    entry.pPort->GetPortNumber(),
501                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
502                                    iNote,
503                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
504                                            : pMidiListener->NoteOffVelocity(iNote)
505                                )
506                            );
507                        }
508                  }                  }
509              }              }
510          }          }
# Line 161  int LSCPServer::Main() { Line 527  int LSCPServer::Main() {
527    
528          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);
529    
530          if (retval == 0)          if (retval == 0 || (retval == -1 && errno == EINTR))
531                  continue; //Nothing try again                  continue; //Nothing try again
532          if (retval == -1) {          if (retval == -1) {
533                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
534                    #if defined(WIN32)
535                    closesocket(hSocket);
536                    #else
537                  close(hSocket);                  close(hSocket);
538                    #endif
539                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
540          }          }
541    
# Line 177  int LSCPServer::Main() { Line 547  int LSCPServer::Main() {
547                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
548                  }                  }
549    
550                    #if defined(WIN32)
551                    u_long nonblock_io = 1;
552                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
553                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
554                      exit(EXIT_FAILURE);
555                    }
556            #else
557                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
558                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
559                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
560                  }                  }
561                    #endif
562    
563                  // Parser initialization                  // Parser initialization
564                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 204  int LSCPServer::Main() { Line 582  int LSCPServer::Main() {
582                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
583                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
584                                  currentSocket = (*iter).hSession;  //a hack                                  currentSocket = (*iter).hSession;  //a hack
585                                    itCurrentSession = iter; // another hack
586                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
587                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
588                                      AnswerClient(bufferedCommands[currentSocket]);                                      AnswerClient(bufferedCommands[currentSocket]);
589                                  }                                  }
590                                  int result = yyparse(&(*iter));                                  int result = yyparse(&(*iter));
591                                  currentSocket = -1;     //continuation of a hack                                  currentSocket = -1;     //continuation of a hack
592                                    itCurrentSession = Sessions.end(); // hack as well
593                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
594                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?
595                                          CloseConnection(iter);                                          CloseConnection(iter);
# Line 237  void LSCPServer::CloseConnection( std::v Line 617  void LSCPServer::CloseConnection( std::v
617          NotifyMutex.Lock();          NotifyMutex.Lock();
618          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
619          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
620            #if defined(WIN32)
621            closesocket(socket);
622            #else
623          close(socket);          close(socket);
624            #endif
625          NotifyMutex.Unlock();          NotifyMutex.Unlock();
626  }  }
627    
628    void LSCPServer::CloseAllConnections() {
629        std::vector<yyparse_param_t>::iterator iter = Sessions.begin();
630        while(iter != Sessions.end()) {
631            CloseConnection(iter);
632            iter = Sessions.begin();
633        }
634    }
635    
636    void LSCPServer::LockRTNotify() {
637        RTNotifyMutex.Lock();
638    }
639    
640    void LSCPServer::UnlockRTNotify() {
641        RTNotifyMutex.Unlock();
642    }
643    
644  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
645          int subs = 0;          int subs = 0;
646          SubscriptionMutex.Lock();          SubscriptionMutex.Lock();
# Line 302  extern int GetLSCPCommand( void *buf, in Line 702  extern int GetLSCPCommand( void *buf, in
702          return command.size();          return command.size();
703  }  }
704    
705    extern yyparse_param_t* GetCurrentYaccSession() {
706        return &(*itCurrentSession);
707    }
708    
709  /**  /**
710   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
711   * 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 716  bool LSCPServer::GetLSCPCommand( std::ve
716          char c;          char c;
717          int i = 0;          int i = 0;
718          while (true) {          while (true) {
719                    #if defined(WIN32)
720                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
721                    #else
722                  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
723                    #endif
724                  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
725                          CloseConnection(iter);                          CloseConnection(iter);
726                          break;                          break;
# Line 327  bool LSCPServer::GetLSCPCommand( std::ve Line 735  bool LSCPServer::GetLSCPCommand( std::ve
735                          }                          }
736                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
737                  }                  }
738                    #if defined(WIN32)
739                    if (result == SOCKET_ERROR) {
740                        int wsa_lasterror = WSAGetLastError();
741                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
742                                    return false;
743                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
744                            CloseConnection(iter);
745                            break;
746                    }
747                    #else
748                  if (result == -1) {                  if (result == -1) {
749                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
750                                  return false;                                  return false;
# Line 365  bool LSCPServer::GetLSCPCommand( std::ve Line 783  bool LSCPServer::GetLSCPCommand( std::ve
783                          CloseConnection(iter);                          CloseConnection(iter);
784                          break;                          break;
785                  }                  }
786                    #endif
787          }          }
788          return false;          return false;
789  }  }
# Line 482  String LSCPServer::DestroyMidiInputDevic Line 901  String LSCPServer::DestroyMidiInputDevic
901      return result.Produce();      return result.Produce();
902  }  }
903    
904    EngineChannel* LSCPServer::GetEngineChannel(uint uiSamplerChannel) {
905        SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
906        if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
907    
908        EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
909        if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
910    
911        return pEngineChannel;
912    }
913    
914  /**  /**
915   * Will be called by the parser to load an instrument.   * Will be called by the parser to load an instrument.
916   */   */
# Line 628  String LSCPServer::GetEngineInfo(String Line 1057  String LSCPServer::GetEngineInfo(String
1057      LockRTNotify();      LockRTNotify();
1058      try {      try {
1059          Engine* pEngine = EngineFactory::Create(EngineName);          Engine* pEngine = EngineFactory::Create(EngineName);
1060          result.Add("DESCRIPTION", pEngine->Description());          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
1061          result.Add("VERSION",     pEngine->Version());          result.Add("VERSION",     pEngine->Version());
1062          EngineFactory::Destroy(pEngine);          EngineFactory::Destroy(pEngine);
1063      }      }
# Line 662  String LSCPServer::GetChannelInfo(uint u Line 1091  String LSCPServer::GetChannelInfo(uint u
1091          String AudioRouting;          String AudioRouting;
1092          int Mute = 0;          int Mute = 0;
1093          bool Solo = false;          bool Solo = false;
1094            String MidiInstrumentMap = "NONE";
1095    
1096          if (pEngineChannel) {          if (pEngineChannel) {
1097              EngineName          = pEngineChannel->EngineName();              EngineName          = pEngineChannel->EngineName();
# Line 679  String LSCPServer::GetChannelInfo(uint u Line 1109  String LSCPServer::GetChannelInfo(uint u
1109              }              }
1110              Mute = pEngineChannel->GetMute();              Mute = pEngineChannel->GetMute();
1111              Solo = pEngineChannel->GetSolo();              Solo = pEngineChannel->GetSolo();
1112                if (pEngineChannel->UsesNoMidiInstrumentMap())
1113                    MidiInstrumentMap = "NONE";
1114                else if (pEngineChannel->UsesDefaultMidiInstrumentMap())
1115                    MidiInstrumentMap = "DEFAULT";
1116                else
1117                    MidiInstrumentMap = ToString(pEngineChannel->GetMidiInstrumentMap());
1118          }          }
1119    
1120          result.Add("ENGINE_NAME", EngineName);          result.Add("ENGINE_NAME", EngineName);
# Line 694  String LSCPServer::GetChannelInfo(uint u Line 1130  String LSCPServer::GetChannelInfo(uint u
1130          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
1131          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
1132    
1133            // convert the filename into the correct encoding as defined for LSCP
1134            // (especially in terms of special characters -> escape sequences)
1135            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
1136    #if WIN32
1137                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
1138    #else
1139                // assuming POSIX
1140                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
1141    #endif
1142            }
1143    
1144          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
1145          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
1146          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
1147          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
1148          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
1149          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
1150            result.Add("MIDI_INSTRUMENT_MAP", MidiInstrumentMap);
1151      }      }
1152      catch (Exception e) {      catch (Exception e) {
1153           result.Error(e);           result.Error(e);
# Line 715  String LSCPServer::GetVoiceCount(uint ui Line 1163  String LSCPServer::GetVoiceCount(uint ui
1163      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));
1164      LSCPResultSet result;      LSCPResultSet result;
1165      try {      try {
1166          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("No engine loaded on sampler channel");  
1167          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1168          result.Add(pEngineChannel->GetEngine()->VoiceCount());          result.Add(pEngineChannel->GetEngine()->VoiceCount());
1169      }      }
# Line 736  String LSCPServer::GetStreamCount(uint u Line 1181  String LSCPServer::GetStreamCount(uint u
1181      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));
1182      LSCPResultSet result;      LSCPResultSet result;
1183      try {      try {
1184          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("No engine type assigned to sampler channel");  
1185          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1186          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());
1187      }      }
# Line 757  String LSCPServer::GetBufferFill(fill_re Line 1199  String LSCPServer::GetBufferFill(fill_re
1199      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));
1200      LSCPResultSet result;      LSCPResultSet result;
1201      try {      try {
1202          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("No engine type assigned to sampler channel");  
1203          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1204          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");
1205          else {          else {
# Line 848  String LSCPServer::GetMidiInputDriverInf Line 1287  String LSCPServer::GetMidiInputDriverInf
1287              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1288                  if (s != "") s += ",";                  if (s != "") s += ",";
1289                  s += iter->first;                  s += iter->first;
1290                    delete iter->second;
1291              }              }
1292              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1293          }          }
# Line 872  String LSCPServer::GetAudioOutputDriverI Line 1312  String LSCPServer::GetAudioOutputDriverI
1312              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1313                  if (s != "") s += ",";                  if (s != "") s += ",";
1314                  s += iter->first;                  s += iter->first;
1315                    delete iter->second;
1316              }              }
1317              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1318          }          }
# Line 902  String LSCPServer::GetMidiInputDriverPar Line 1343  String LSCPServer::GetMidiInputDriverPar
1343          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1344          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1345          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1346            delete pParameter;
1347      }      }
1348      catch (Exception e) {      catch (Exception e) {
1349          result.Error(e);          result.Error(e);
# Line 929  String LSCPServer::GetAudioOutputDriverP Line 1371  String LSCPServer::GetAudioOutputDriverP
1371          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1372          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1373          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1374            delete pParameter;
1375      }      }
1376      catch (Exception e) {      catch (Exception e) {
1377          result.Error(e);          result.Error(e);
# Line 1177  String LSCPServer::SetAudioOutputChannel Line 1620  String LSCPServer::SetAudioOutputChannel
1620    
1621          // set new channel parameter value          // set new channel parameter value
1622          pParameter->SetValue(ParamVal);          pParameter->SetValue(ParamVal);
1623            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_info, DeviceId));
1624      }      }
1625      catch (Exception e) {      catch (Exception e) {
1626          result.Error(e);          result.Error(e);
# Line 1194  String LSCPServer::SetAudioOutputDeviceP Line 1638  String LSCPServer::SetAudioOutputDeviceP
1638          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1639          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 + "'");
1640          parameters[ParamKey]->SetValue(ParamVal);          parameters[ParamKey]->SetValue(ParamVal);
1641            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_info, DeviceIndex));
1642      }      }
1643      catch (Exception e) {      catch (Exception e) {
1644          result.Error(e);          result.Error(e);
# Line 1211  String LSCPServer::SetMidiInputDevicePar Line 1656  String LSCPServer::SetMidiInputDevicePar
1656          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1657          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 + "'");
1658          parameters[ParamKey]->SetValue(ParamVal);          parameters[ParamKey]->SetValue(ParamVal);
1659            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_info, DeviceIndex));
1660      }      }
1661      catch (Exception e) {      catch (Exception e) {
1662          result.Error(e);          result.Error(e);
# Line 1235  String LSCPServer::SetMidiInputPortParam Line 1681  String LSCPServer::SetMidiInputPortParam
1681          std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();          std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();
1682          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 + "'");
1683          parameters[ParamKey]->SetValue(ParamVal);          parameters[ParamKey]->SetValue(ParamVal);
1684            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_info, DeviceIndex));
1685      }      }
1686      catch (Exception e) {      catch (Exception e) {
1687          result.Error(e);          result.Error(e);
# Line 1434  String LSCPServer::SetVolume(double dVol Line 1881  String LSCPServer::SetVolume(double dVol
1881      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));
1882      LSCPResultSet result;      LSCPResultSet result;
1883      try {      try {
1884          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("No engine type assigned to sampler channel");  
1885          pEngineChannel->Volume(dVolume);          pEngineChannel->Volume(dVolume);
1886      }      }
1887      catch (Exception e) {      catch (Exception e) {
# Line 1453  String LSCPServer::SetChannelMute(bool b Line 1897  String LSCPServer::SetChannelMute(bool b
1897      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));
1898      LSCPResultSet result;      LSCPResultSet result;
1899      try {      try {
1900          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("No engine type assigned to sampler channel");  
1901    
1902          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);
1903          else pEngineChannel->SetMute(1);          else pEngineChannel->SetMute(1);
# Line 1474  String LSCPServer::SetChannelSolo(bool b Line 1914  String LSCPServer::SetChannelSolo(bool b
1914      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));
1915      LSCPResultSet result;      LSCPResultSet result;
1916      try {      try {
1917          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("No engine type assigned to sampler channel");  
1918    
1919          bool oldSolo = pEngineChannel->GetSolo();          bool oldSolo = pEngineChannel->GetSolo();
1920          bool hadSoloChannel = HasSoloChannel();          bool hadSoloChannel = HasSoloChannel();
1921            
1922          pEngineChannel->SetSolo(bSolo);          pEngineChannel->SetSolo(bSolo);
1923            
1924          if(!oldSolo && bSolo) {          if(!oldSolo && bSolo) {
1925              if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);              if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);
1926              if(!hadSoloChannel) MuteNonSoloChannels();              if(!hadSoloChannel) MuteNonSoloChannels();
1927          }          }
1928            
1929          if(oldSolo && !bSolo) {          if(oldSolo && !bSolo) {
1930              if(!HasSoloChannel()) UnmuteChannels();              if(!HasSoloChannel()) UnmuteChannels();
1931              else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);              else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);
# Line 1547  void  LSCPServer::UnmuteChannels() { Line 1983  void  LSCPServer::UnmuteChannels() {
1983      }      }
1984  }  }
1985    
1986  String LSCPServer::AddOrReplaceMIDIInstrumentMapping(uint MidiBankMSB, uint MidiBankLSB, 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) {
1987      dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));      dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));
1988    
1989      midi_prog_index_t idx;      midi_prog_index_t idx;
1990      idx.midi_bank_msb = MidiBankMSB;      idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;
1991      idx.midi_bank_lsb = MidiBankLSB;      idx.midi_bank_lsb = MidiBank & 0x7f;
1992      idx.midi_prog     = MidiProg;      idx.midi_prog     = MidiProg;
1993    
1994      MidiInstrumentMapper::entry_t entry;      MidiInstrumentMapper::entry_t entry;
# Line 1565  String LSCPServer::AddOrReplaceMIDIInstr Line 2001  String LSCPServer::AddOrReplaceMIDIInstr
2001    
2002      LSCPResultSet result;      LSCPResultSet result;
2003      try {      try {
2004          // PERSISTENT mapping commands might bloock for a long time, so in          // PERSISTENT mapping commands might block for a long time, so in
2005          // that case we add/replace the mapping in another thread          // that case we add/replace the mapping in another thread in case
2006          bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT);          // the NON_MODAL argument was supplied, non persistent mappings
2007          MidiInstrumentMapper::AddOrReplaceMapping(idx, entry, bInBackground);          // should return immediately, so we don't need to do that for them
2008            bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT && !bModal);
2009            MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);
2010      } catch (Exception e) {      } catch (Exception e) {
2011          result.Error(e);          result.Error(e);
2012      }      }
2013      return result.Produce();      return result.Produce();
2014  }  }
2015    
2016  String LSCPServer::RemoveMIDIInstrumentMapping(uint MidiBankMSB, uint MidiBankLSB, uint MidiProg) {  String LSCPServer::RemoveMIDIInstrumentMapping(uint MidiMapID, uint MidiBank, uint MidiProg) {
2017      dmsg(2,("LSCPServer: RemoveMIDIInstrumentMapping()\n"));      dmsg(2,("LSCPServer: RemoveMIDIInstrumentMapping()\n"));
2018    
2019      midi_prog_index_t idx;      midi_prog_index_t idx;
2020      idx.midi_bank_msb = MidiBankMSB;      idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;
2021      idx.midi_bank_lsb = MidiBankLSB;      idx.midi_bank_lsb = MidiBank & 0x7f;
2022      idx.midi_prog     = MidiProg;      idx.midi_prog     = MidiProg;
2023    
2024      LSCPResultSet result;      LSCPResultSet result;
2025      try {      try {
2026          MidiInstrumentMapper::RemoveMapping(idx);          MidiInstrumentMapper::RemoveEntry(MidiMapID, idx);
2027      } catch (Exception e) {      } catch (Exception e) {
2028          result.Error(e);          result.Error(e);
2029      }      }
2030      return result.Produce();      return result.Produce();
2031  }  }
2032    
2033  String LSCPServer::GetMidiIstrumentMappings() {  String LSCPServer::GetMidiInstrumentMappings(uint MidiMapID) {
2034      dmsg(2,("LSCPServer: GetMidiIstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));
2035      LSCPResultSet result;      LSCPResultSet result;
2036      result.Add(MidiInstrumentMapper::Mappings().size());      try {
2037            result.Add(MidiInstrumentMapper::GetInstrumentCount(MidiMapID));
2038        } catch (Exception e) {
2039            result.Error(e);
2040        }
2041      return result.Produce();      return result.Produce();
2042  }  }
2043    
2044  String LSCPServer::GetMidiInstrumentMapping(uint MidiBankMSB, uint MidiBankLSB, uint MidiProg) {  
2045    String LSCPServer::GetAllMidiInstrumentMappings() {
2046        dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));
2047        LSCPResultSet result;
2048        try {
2049            result.Add(MidiInstrumentMapper::GetInstrumentCount());
2050        } catch (Exception e) {
2051            result.Error(e);
2052        }
2053        return result.Produce();
2054    }
2055    
2056    String LSCPServer::GetMidiInstrumentMapping(uint MidiMapID, uint MidiBank, uint MidiProg) {
2057      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));
2058      LSCPResultSet result;      LSCPResultSet result;
2059      try {      try {
2060          midi_prog_index_t idx;          MidiInstrumentMapper::entry_t entry = MidiInstrumentMapper::GetEntry(MidiMapID, MidiBank, MidiProg);
2061          idx.midi_bank_msb = MidiBankMSB;          // convert the filename into the correct encoding as defined for LSCP
2062          idx.midi_bank_lsb = MidiBankLSB;          // (especially in terms of special characters -> escape sequences)
2063          idx.midi_prog     = MidiProg;  #if WIN32
2064            const String instrumentFileName = Path::fromWindows(entry.InstrumentFile).toLscp();
2065          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Mappings();  #else
2066          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);          // assuming POSIX
2067          if (iter == mappings.end()) result.Error("there is no map entry with that index");          const String instrumentFileName = Path::fromPosix(entry.InstrumentFile).toLscp();
2068          else { // found  #endif
2069              result.Add("NAME", iter->second.Name);  
2070              result.Add("ENGINE_NAME", iter->second.EngineName);          result.Add("NAME", _escapeLscpResponse(entry.Name));
2071              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);          result.Add("ENGINE_NAME", entry.EngineName);
2072              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);          result.Add("INSTRUMENT_FILE", instrumentFileName);
2073              String instrumentName;          result.Add("INSTRUMENT_NR", (int) entry.InstrumentIndex);
2074              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);          String instrumentName;
2075              if (pEngine) {          Engine* pEngine = EngineFactory::Create(entry.EngineName);
2076                  if (pEngine->GetInstrumentManager()) {          if (pEngine) {
2077                      InstrumentManager::instrument_id_t instrID;              if (pEngine->GetInstrumentManager()) {
2078                      instrID.FileName = iter->second.InstrumentFile;                  InstrumentManager::instrument_id_t instrID;
2079                      instrID.Index    = iter->second.InstrumentIndex;                  instrID.FileName = entry.InstrumentFile;
2080                      instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);                  instrID.Index    = entry.InstrumentIndex;
2081                  }                  instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);
                 EngineFactory::Destroy(pEngine);  
             }  
             result.Add("INSTRUMENT_NAME", instrumentName);  
             switch (iter->second.LoadMode) {  
                 case MidiInstrumentMapper::ON_DEMAND:  
                     result.Add("LOAD_MODE", "ON_DEMAND");  
                     break;  
                 case MidiInstrumentMapper::ON_DEMAND_HOLD:  
                     result.Add("LOAD_MODE", "ON_DEMAND_HOLD");  
                     break;  
                 case MidiInstrumentMapper::PERSISTENT:  
                     result.Add("LOAD_MODE", "PERSISTENT");  
                     break;  
                 default:  
                     throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");  
2082              }              }
2083              result.Add("VOLUME", iter->second.Volume);              EngineFactory::Destroy(pEngine);
2084          }          }
2085            result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
2086            switch (entry.LoadMode) {
2087                case MidiInstrumentMapper::ON_DEMAND:
2088                    result.Add("LOAD_MODE", "ON_DEMAND");
2089                    break;
2090                case MidiInstrumentMapper::ON_DEMAND_HOLD:
2091                    result.Add("LOAD_MODE", "ON_DEMAND_HOLD");
2092                    break;
2093                case MidiInstrumentMapper::PERSISTENT:
2094                    result.Add("LOAD_MODE", "PERSISTENT");
2095                    break;
2096                default:
2097                    throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");
2098            }
2099            result.Add("VOLUME", entry.Volume);
2100      } catch (Exception e) {      } catch (Exception e) {
2101          result.Error(e);          result.Error(e);
2102      }      }
2103      return result.Produce();      return result.Produce();
2104  }  }
2105    
2106  String LSCPServer::ListMidiInstrumentMappings() {  String LSCPServer::ListMidiInstrumentMappings(uint MidiMapID) {
2107      dmsg(2,("LSCPServer: ListMidiIstrumentMappings()\n"));      dmsg(2,("LSCPServer: ListMidiInstrumentMappings()\n"));
2108      LSCPResultSet result;      LSCPResultSet result;
2109      try {      try {
2110          String s;          String s;
2111          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Mappings();          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(MidiMapID);
2112          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.begin();          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.begin();
2113          for (; iter != mappings.end(); iter++) {          for (; iter != mappings.end(); iter++) {
2114              if (s.size()) s += ",";              if (s.size()) s += ",";
2115              s += "{" + ToString(int(iter->first.midi_bank_msb)) + ","              s += "{" + ToString(MidiMapID) + ","
2116                       + ToString(int(iter->first.midi_bank_lsb)) + ","                       + ToString((int(iter->first.midi_bank_msb) << 7) | int(iter->first.midi_bank_lsb)) + ","
2117                       + ToString(int(iter->first.midi_prog))     + "}";                       + ToString(int(iter->first.midi_prog)) + "}";
2118            }
2119            result.Add(s);
2120        } catch (Exception e) {
2121            result.Error(e);
2122        }
2123        return result.Produce();
2124    }
2125    
2126    String LSCPServer::ListAllMidiInstrumentMappings() {
2127        dmsg(2,("LSCPServer: ListAllMidiInstrumentMappings()\n"));
2128        LSCPResultSet result;
2129        try {
2130            std::vector<int> maps = MidiInstrumentMapper::Maps();
2131            String s;
2132            for (int i = 0; i < maps.size(); i++) {
2133                std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(maps[i]);
2134                std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.begin();
2135                for (; iter != mappings.end(); iter++) {
2136                    if (s.size()) s += ",";
2137                    s += "{" + ToString(maps[i]) + ","
2138                             + ToString((int(iter->first.midi_bank_msb) << 7) | int(iter->first.midi_bank_lsb)) + ","
2139                             + ToString(int(iter->first.midi_prog)) + "}";
2140                }
2141          }          }
2142          result.Add(s);          result.Add(s);
2143      } catch (Exception e) {      } catch (Exception e) {
# Line 1669  String LSCPServer::ListMidiInstrumentMap Line 2146  String LSCPServer::ListMidiInstrumentMap
2146      return result.Produce();      return result.Produce();
2147  }  }
2148    
2149  String LSCPServer::ClearMidiInstrumentMappings() {  String LSCPServer::ClearMidiInstrumentMappings(uint MidiMapID) {
2150      dmsg(2,("LSCPServer: ClearMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: ClearMidiInstrumentMappings()\n"));
2151      LSCPResultSet result;      LSCPResultSet result;
2152      try {      try {
2153          MidiInstrumentMapper::RemoveAllMappings();          MidiInstrumentMapper::RemoveAllEntries(MidiMapID);
2154        } catch (Exception e) {
2155            result.Error(e);
2156        }
2157        return result.Produce();
2158    }
2159    
2160    String LSCPServer::ClearAllMidiInstrumentMappings() {
2161        dmsg(2,("LSCPServer: ClearAllMidiInstrumentMappings()\n"));
2162        LSCPResultSet result;
2163        try {
2164            std::vector<int> maps = MidiInstrumentMapper::Maps();
2165            for (int i = 0; i < maps.size(); i++)
2166                MidiInstrumentMapper::RemoveAllEntries(maps[i]);
2167        } catch (Exception e) {
2168            result.Error(e);
2169        }
2170        return result.Produce();
2171    }
2172    
2173    String LSCPServer::AddMidiInstrumentMap(String MapName) {
2174        dmsg(2,("LSCPServer: AddMidiInstrumentMap()\n"));
2175        LSCPResultSet result;
2176        try {
2177            int MapID = MidiInstrumentMapper::AddMap(MapName);
2178            result = LSCPResultSet(MapID);
2179        } catch (Exception e) {
2180            result.Error(e);
2181        }
2182        return result.Produce();
2183    }
2184    
2185    String LSCPServer::RemoveMidiInstrumentMap(uint MidiMapID) {
2186        dmsg(2,("LSCPServer: RemoveMidiInstrumentMap()\n"));
2187        LSCPResultSet result;
2188        try {
2189            MidiInstrumentMapper::RemoveMap(MidiMapID);
2190        } catch (Exception e) {
2191            result.Error(e);
2192        }
2193        return result.Produce();
2194    }
2195    
2196    String LSCPServer::RemoveAllMidiInstrumentMaps() {
2197        dmsg(2,("LSCPServer: RemoveAllMidiInstrumentMaps()\n"));
2198        LSCPResultSet result;
2199        try {
2200            MidiInstrumentMapper::RemoveAllMaps();
2201        } catch (Exception e) {
2202            result.Error(e);
2203        }
2204        return result.Produce();
2205    }
2206    
2207    String LSCPServer::GetMidiInstrumentMaps() {
2208        dmsg(2,("LSCPServer: GetMidiInstrumentMaps()\n"));
2209        LSCPResultSet result;
2210        try {
2211            result.Add(MidiInstrumentMapper::Maps().size());
2212        } catch (Exception e) {
2213            result.Error(e);
2214        }
2215        return result.Produce();
2216    }
2217    
2218    String LSCPServer::ListMidiInstrumentMaps() {
2219        dmsg(2,("LSCPServer: ListMidiInstrumentMaps()\n"));
2220        LSCPResultSet result;
2221        try {
2222            std::vector<int> maps = MidiInstrumentMapper::Maps();
2223            String sList;
2224            for (int i = 0; i < maps.size(); i++) {
2225                if (sList != "") sList += ",";
2226                sList += ToString(maps[i]);
2227            }
2228            result.Add(sList);
2229        } catch (Exception e) {
2230            result.Error(e);
2231        }
2232        return result.Produce();
2233    }
2234    
2235    String LSCPServer::GetMidiInstrumentMap(uint MidiMapID) {
2236        dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2237        LSCPResultSet result;
2238        try {
2239            result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2240            result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2241        } catch (Exception e) {
2242            result.Error(e);
2243        }
2244        return result.Produce();
2245    }
2246    
2247    String LSCPServer::SetMidiInstrumentMapName(uint MidiMapID, String NewName) {
2248        dmsg(2,("LSCPServer: SetMidiInstrumentMapName()\n"));
2249        LSCPResultSet result;
2250        try {
2251            MidiInstrumentMapper::RenameMap(MidiMapID, NewName);
2252        } catch (Exception e) {
2253            result.Error(e);
2254        }
2255        return result.Produce();
2256    }
2257    
2258    /**
2259     * Set the MIDI instrument map the given sampler channel shall use for
2260     * handling MIDI program change messages. There are the following two
2261     * special (negative) values:
2262     *
2263     *    - (-1) :  set to NONE (ignore program changes)
2264     *    - (-2) :  set to DEFAULT map
2265     */
2266    String LSCPServer::SetChannelMap(uint uiSamplerChannel, int MidiMapID) {
2267        dmsg(2,("LSCPServer: SetChannelMap()\n"));
2268        LSCPResultSet result;
2269        try {
2270            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2271    
2272            if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();
2273            else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();
2274            else                      pEngineChannel->SetMidiInstrumentMap(MidiMapID);
2275        } catch (Exception e) {
2276            result.Error(e);
2277        }
2278        return result.Produce();
2279    }
2280    
2281    String LSCPServer::CreateFxSend(uint uiSamplerChannel, uint MidiCtrl, String Name) {
2282        dmsg(2,("LSCPServer: CreateFxSend()\n"));
2283        LSCPResultSet result;
2284        try {
2285            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2286    
2287            FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2288            if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");
2289    
2290            result = LSCPResultSet(pFxSend->Id()); // success
2291        } catch (Exception e) {
2292            result.Error(e);
2293        }
2294        return result.Produce();
2295    }
2296    
2297    String LSCPServer::DestroyFxSend(uint uiSamplerChannel, uint FxSendID) {
2298        dmsg(2,("LSCPServer: DestroyFxSend()\n"));
2299        LSCPResultSet result;
2300        try {
2301            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2302    
2303            FxSend* pFxSend = NULL;
2304            for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2305                if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2306                    pFxSend = pEngineChannel->GetFxSend(i);
2307                    break;
2308                }
2309            }
2310            if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2311            pEngineChannel->RemoveFxSend(pFxSend);
2312        } catch (Exception e) {
2313            result.Error(e);
2314        }
2315        return result.Produce();
2316    }
2317    
2318    String LSCPServer::GetFxSends(uint uiSamplerChannel) {
2319        dmsg(2,("LSCPServer: GetFxSends()\n"));
2320        LSCPResultSet result;
2321        try {
2322            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2323    
2324            result.Add(pEngineChannel->GetFxSendCount());
2325        } catch (Exception e) {
2326            result.Error(e);
2327        }
2328        return result.Produce();
2329    }
2330    
2331    String LSCPServer::ListFxSends(uint uiSamplerChannel) {
2332        dmsg(2,("LSCPServer: ListFxSends()\n"));
2333        LSCPResultSet result;
2334        String list;
2335        try {
2336            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2337    
2338            for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2339                FxSend* pFxSend = pEngineChannel->GetFxSend(i);
2340                if (list != "") list += ",";
2341                list += ToString(pFxSend->Id());
2342            }
2343            result.Add(list);
2344        } catch (Exception e) {
2345            result.Error(e);
2346        }
2347        return result.Produce();
2348    }
2349    
2350    FxSend* LSCPServer::GetFxSend(uint uiSamplerChannel, uint FxSendID) {
2351        EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2352    
2353        FxSend* pFxSend = NULL;
2354        for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2355            if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2356                pFxSend = pEngineChannel->GetFxSend(i);
2357                break;
2358            }
2359        }
2360        if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2361        return pFxSend;
2362    }
2363    
2364    String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {
2365        dmsg(2,("LSCPServer: GetFxSendInfo()\n"));
2366        LSCPResultSet result;
2367        try {
2368            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2369            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2370    
2371            // gather audio routing informations
2372            String AudioRouting;
2373            for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {
2374                if (AudioRouting != "") AudioRouting += ",";
2375                AudioRouting += ToString(pFxSend->DestinationChannel(chan));
2376            }
2377    
2378            // success
2379            result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2380            result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2381            result.Add("LEVEL", ToString(pFxSend->Level()));
2382            result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
2383        } catch (Exception e) {
2384            result.Error(e);
2385        }
2386        return result.Produce();
2387    }
2388    
2389    String LSCPServer::SetFxSendName(uint uiSamplerChannel, uint FxSendID, String Name) {
2390        dmsg(2,("LSCPServer: SetFxSendName()\n"));
2391        LSCPResultSet result;
2392        try {
2393            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2394    
2395            pFxSend->SetName(Name);
2396            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2397        } catch (Exception e) {
2398            result.Error(e);
2399        }
2400        return result.Produce();
2401    }
2402    
2403    String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {
2404        dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));
2405        LSCPResultSet result;
2406        try {
2407            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2408    
2409            pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);
2410            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2411        } catch (Exception e) {
2412            result.Error(e);
2413        }
2414        return result.Produce();
2415    }
2416    
2417    String LSCPServer::SetFxSendMidiController(uint uiSamplerChannel, uint FxSendID, uint MidiController) {
2418        dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));
2419        LSCPResultSet result;
2420        try {
2421            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2422    
2423            pFxSend->SetMidiController(MidiController);
2424            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2425        } catch (Exception e) {
2426            result.Error(e);
2427        }
2428        return result.Produce();
2429    }
2430    
2431    String LSCPServer::SetFxSendLevel(uint uiSamplerChannel, uint FxSendID, double dLevel) {
2432        dmsg(2,("LSCPServer: SetFxSendLevel()\n"));
2433        LSCPResultSet result;
2434        try {
2435            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2436    
2437            pFxSend->SetLevel((float)dLevel);
2438            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2439        } catch (Exception e) {
2440            result.Error(e);
2441        }
2442        return result.Produce();
2443    }
2444    
2445    String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2446        dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2447        LSCPResultSet result;
2448        try {
2449            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2450            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2451            Engine* pEngine = pEngineChannel->GetEngine();
2452            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2453            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2454            InstrumentManager::instrument_id_t instrumentID;
2455            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2456            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2457            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2458        } catch (Exception e) {
2459            result.Error(e);
2460        }
2461        return result.Produce();
2462    }
2463    
2464    String LSCPServer::SendChannelMidiData(String MidiMsg, uint uiSamplerChannel, uint Arg1, uint Arg2) {
2465        dmsg(2,("LSCPServer: SendChannelMidiData(MidiMsg=%s,uiSamplerChannel=%d,Arg1=%d,Arg2=%d)\n", MidiMsg.c_str(), uiSamplerChannel, Arg1, Arg2));
2466        LSCPResultSet result;
2467        try {
2468            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2469    
2470            if (Arg1 > 127 || Arg2 > 127) {
2471                throw Exception("Invalid MIDI message");
2472            }
2473    
2474            VirtualMidiDevice* pMidiDevice = NULL;
2475            std::vector<EventHandler::midi_listener_entry>::iterator iter = eventHandler.channelMidiListeners.begin();
2476            for (; iter != eventHandler.channelMidiListeners.end(); ++iter) {
2477                if ((*iter).pEngineChannel == pEngineChannel) {
2478                    pMidiDevice = (*iter).pMidiListener;
2479                    break;
2480                }
2481            }
2482            
2483            if(pMidiDevice == NULL) throw Exception("Couldn't find virtual MIDI device");
2484    
2485            if (MidiMsg == "NOTE_ON") {
2486                pMidiDevice->SendNoteOnToDevice(Arg1, Arg2);
2487                bool b = pMidiDevice->SendNoteOnToSampler(Arg1, Arg2);
2488                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2489            } else if (MidiMsg == "NOTE_OFF") {
2490                pMidiDevice->SendNoteOffToDevice(Arg1, Arg2);
2491                bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2);
2492                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2493            } else {
2494                throw Exception("Unknown MIDI message type: " + MidiMsg);
2495            }
2496      } catch (Exception e) {      } catch (Exception e) {
2497          result.Error(e);          result.Error(e);
2498      }      }
# Line 1687  String LSCPServer::ResetChannel(uint uiS Line 2506  String LSCPServer::ResetChannel(uint uiS
2506      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));
2507      LSCPResultSet result;      LSCPResultSet result;
2508      try {      try {
2509          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("No engine type assigned to sampler channel");  
2510          pEngineChannel->Reset();          pEngineChannel->Reset();
2511      }      }
2512      catch (Exception e) {      catch (Exception e) {
# Line 1715  String LSCPServer::ResetSampler() { Line 2531  String LSCPServer::ResetSampler() {
2531   */   */
2532  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
2533      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
2534        const std::string description =
2535            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2536      LSCPResultSet result;      LSCPResultSet result;
2537      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
2538      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
2539      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2540    #if HAVE_SQLITE3
2541        result.Add("INSTRUMENTS_DB_SUPPORT", "yes");
2542    #else
2543        result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2544    #endif
2545    
2546        return result.Produce();
2547    }
2548    
2549    /**
2550     * Will be called by the parser to return the current number of all active streams.
2551     */
2552    String LSCPServer::GetTotalStreamCount() {
2553        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2554        LSCPResultSet result;
2555        result.Add(pSampler->GetDiskStreamCount());
2556      return result.Produce();      return result.Produce();
2557  }  }
2558    
# Line 1738  String LSCPServer::GetTotalVoiceCount() Line 2572  String LSCPServer::GetTotalVoiceCount()
2572  String LSCPServer::GetTotalVoiceCountMax() {  String LSCPServer::GetTotalVoiceCountMax() {
2573      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));
2574      LSCPResultSet result;      LSCPResultSet result;
2575      result.Add(EngineFactory::EngineInstances().size() * CONFIG_MAX_VOICES);      result.Add(EngineFactory::EngineInstances().size() * GLOBAL_MAX_VOICES);
2576        return result.Produce();
2577    }
2578    
2579    /**
2580     * Will be called by the parser to return the sampler global maximum
2581     * allowed number of voices.
2582     */
2583    String LSCPServer::GetGlobalMaxVoices() {
2584        dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n"));
2585        LSCPResultSet result;
2586        result.Add(GLOBAL_MAX_VOICES);
2587        return result.Produce();
2588    }
2589    
2590    /**
2591     * Will be called by the parser to set the sampler global maximum number of
2592     * voices.
2593     */
2594    String LSCPServer::SetGlobalMaxVoices(int iVoices) {
2595        dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices));
2596        LSCPResultSet result;
2597        try {
2598            if (iVoices < 1) throw Exception("Maximum voices may not be less than 1");
2599            GLOBAL_MAX_VOICES = iVoices; // see common/global_private.cpp
2600            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
2601            if (engines.size() > 0) {
2602                std::set<Engine*>::iterator iter = engines.begin();
2603                std::set<Engine*>::iterator end  = engines.end();
2604                for (; iter != end; ++iter) {
2605                    (*iter)->SetMaxVoices(iVoices);
2606                }
2607            }
2608            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOICES", GLOBAL_MAX_VOICES));
2609        } catch (Exception e) {
2610            result.Error(e);
2611        }
2612        return result.Produce();
2613    }
2614    
2615    /**
2616     * Will be called by the parser to return the sampler global maximum
2617     * allowed number of disk streams.
2618     */
2619    String LSCPServer::GetGlobalMaxStreams() {
2620        dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n"));
2621        LSCPResultSet result;
2622        result.Add(GLOBAL_MAX_STREAMS);
2623        return result.Produce();
2624    }
2625    
2626    /**
2627     * Will be called by the parser to set the sampler global maximum number of
2628     * disk streams.
2629     */
2630    String LSCPServer::SetGlobalMaxStreams(int iStreams) {
2631        dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams));
2632        LSCPResultSet result;
2633        try {
2634            if (iStreams < 0) throw Exception("Maximum disk streams may not be negative");
2635            GLOBAL_MAX_STREAMS = iStreams; // see common/global_private.cpp
2636            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
2637            if (engines.size() > 0) {
2638                std::set<Engine*>::iterator iter = engines.begin();
2639                std::set<Engine*>::iterator end  = engines.end();
2640                for (; iter != end; ++iter) {
2641                    (*iter)->SetMaxDiskStreams(iStreams);
2642                }
2643            }
2644            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "STREAMS", GLOBAL_MAX_STREAMS));
2645        } catch (Exception e) {
2646            result.Error(e);
2647        }
2648        return result.Produce();
2649    }
2650    
2651    String LSCPServer::GetGlobalVolume() {
2652        LSCPResultSet result;
2653        result.Add(ToString(GLOBAL_VOLUME)); // see common/global.cpp
2654        return result.Produce();
2655    }
2656    
2657    String LSCPServer::SetGlobalVolume(double dVolume) {
2658        LSCPResultSet result;
2659        try {
2660            if (dVolume < 0) throw Exception("Volume may not be negative");
2661            GLOBAL_VOLUME = dVolume; // see common/global_private.cpp
2662            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
2663        } catch (Exception e) {
2664            result.Error(e);
2665        }
2666      return result.Produce();      return result.Produce();
2667  }  }
2668    
2669    String LSCPServer::GetFileInstruments(String Filename) {
2670        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2671        LSCPResultSet result;
2672        try {
2673            VerifyFile(Filename);
2674        } catch (Exception e) {
2675            result.Error(e);
2676            return result.Produce();
2677        }
2678        // try to find a sampler engine that can handle the file
2679        bool bFound = false;
2680        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2681        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2682            Engine* pEngine = NULL;
2683            try {
2684                pEngine = EngineFactory::Create(engineTypes[i]);
2685                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2686                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2687                if (pManager) {
2688                    std::vector<InstrumentManager::instrument_id_t> IDs =
2689                        pManager->GetInstrumentFileContent(Filename);
2690                    // return the amount of instruments in the file
2691                    result.Add(IDs.size());
2692                    // no more need to ask other engine types
2693                    bFound = true;
2694                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2695            } catch (Exception e) {
2696                // NOOP, as exception is thrown if engine doesn't support file
2697            }
2698            if (pEngine) EngineFactory::Destroy(pEngine);
2699        }
2700    
2701        if (!bFound) result.Error("Unknown file format");
2702        return result.Produce();
2703    }
2704    
2705    String LSCPServer::ListFileInstruments(String Filename) {
2706        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2707        LSCPResultSet result;
2708        try {
2709            VerifyFile(Filename);
2710        } catch (Exception e) {
2711            result.Error(e);
2712            return result.Produce();
2713        }
2714        // try to find a sampler engine that can handle the file
2715        bool bFound = false;
2716        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2717        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2718            Engine* pEngine = NULL;
2719            try {
2720                pEngine = EngineFactory::Create(engineTypes[i]);
2721                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2722                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2723                if (pManager) {
2724                    std::vector<InstrumentManager::instrument_id_t> IDs =
2725                        pManager->GetInstrumentFileContent(Filename);
2726                    // return a list of IDs of the instruments in the file
2727                    String s;
2728                    for (int j = 0; j < IDs.size(); j++) {
2729                        if (s.size()) s += ",";
2730                        s += ToString(IDs[j].Index);
2731                    }
2732                    result.Add(s);
2733                    // no more need to ask other engine types
2734                    bFound = true;
2735                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2736            } catch (Exception e) {
2737                // NOOP, as exception is thrown if engine doesn't support file
2738            }
2739            if (pEngine) EngineFactory::Destroy(pEngine);
2740        }
2741    
2742        if (!bFound) result.Error("Unknown file format");
2743        return result.Produce();
2744    }
2745    
2746    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2747        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2748        LSCPResultSet result;
2749        try {
2750            VerifyFile(Filename);
2751        } catch (Exception e) {
2752            result.Error(e);
2753            return result.Produce();
2754        }
2755        InstrumentManager::instrument_id_t id;
2756        id.FileName = Filename;
2757        id.Index    = InstrumentID;
2758        // try to find a sampler engine that can handle the file
2759        bool bFound = false;
2760        bool bFatalErr = false;
2761        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2762        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2763            Engine* pEngine = NULL;
2764            try {
2765                pEngine = EngineFactory::Create(engineTypes[i]);
2766                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2767                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2768                if (pManager) {
2769                    // check if the instrument index is valid
2770                    // FIXME: this won't work if an engine only supports parts of the instrument file
2771                    std::vector<InstrumentManager::instrument_id_t> IDs =
2772                        pManager->GetInstrumentFileContent(Filename);
2773                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2774                        std::stringstream ss;
2775                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2776                        bFatalErr = true;
2777                        throw Exception(ss.str());
2778                    }
2779                    // get the info of the requested instrument
2780                    InstrumentManager::instrument_info_t info =
2781                        pManager->GetInstrumentInfo(id);
2782                    // return detailed informations about the file
2783                    result.Add("NAME", info.InstrumentName);
2784                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2785                    result.Add("FORMAT_VERSION", info.FormatVersion);
2786                    result.Add("PRODUCT", info.Product);
2787                    result.Add("ARTISTS", info.Artists);
2788    
2789                    std::stringstream ss;
2790                    bool b = false;
2791                    for (int i = 0; i < 128; i++) {
2792                        if (info.KeyBindings[i]) {
2793                            if (b) ss << ',';
2794                            ss << i; b = true;
2795                        }
2796                    }
2797                    result.Add("KEY_BINDINGS", ss.str());
2798    
2799                    b = false;
2800                    std::stringstream ss2;
2801                    for (int i = 0; i < 128; i++) {
2802                        if (info.KeySwitchBindings[i]) {
2803                            if (b) ss2 << ',';
2804                            ss2 << i; b = true;
2805                        }
2806                    }
2807                    result.Add("KEYSWITCH_BINDINGS", ss2.str());
2808                    // no more need to ask other engine types
2809                    bFound = true;
2810                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2811            } catch (Exception e) {
2812                // usually NOOP, as exception is thrown if engine doesn't support file
2813                if (bFatalErr) result.Error(e);
2814            }
2815            if (pEngine) EngineFactory::Destroy(pEngine);
2816        }
2817    
2818        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2819        return result.Produce();
2820    }
2821    
2822    void LSCPServer::VerifyFile(String Filename) {
2823        #if WIN32
2824        WIN32_FIND_DATA win32FileAttributeData;
2825        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2826        if (!res) {
2827            std::stringstream ss;
2828            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2829            throw Exception(ss.str());
2830        }
2831        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2832            throw Exception("Directory is specified");
2833        }
2834        #else
2835        File f(Filename);
2836        if(!f.Exist()) throw Exception(f.GetErrorMsg());
2837        if (f.IsDirectory()) throw Exception("Directory is specified");
2838        #endif
2839    }
2840    
2841  /**  /**
2842   * 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
2843   * server for receiving event messages.   * server for receiving event messages.
# Line 1768  String LSCPServer::UnsubscribeNotificati Line 2864  String LSCPServer::UnsubscribeNotificati
2864      return result.Produce();      return result.Produce();
2865  }  }
2866    
2867  static int select_callback(void * lscpResultSet, int argc,  String LSCPServer::AddDbInstrumentDirectory(String Dir) {
2868                          char **argv, char **azColName)      dmsg(2,("LSCPServer: AddDbInstrumentDirectory(Dir=%s)\n", Dir.c_str()));
2869  {      LSCPResultSet result;
2870      LSCPResultSet* resultSet = (LSCPResultSet*) lscpResultSet;  #if HAVE_SQLITE3
2871      resultSet->Add(argc, argv);      try {
2872      return 0;          InstrumentsDb::GetInstrumentsDb()->AddDirectory(Dir);
2873        } catch (Exception e) {
2874             result.Error(e);
2875        }
2876    #else
2877        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2878    #endif
2879        return result.Produce();
2880    }
2881    
2882    String LSCPServer::RemoveDbInstrumentDirectory(String Dir, bool Force) {
2883        dmsg(2,("LSCPServer: RemoveDbInstrumentDirectory(Dir=%s,Force=%d)\n", Dir.c_str(), Force));
2884        LSCPResultSet result;
2885    #if HAVE_SQLITE3
2886        try {
2887            InstrumentsDb::GetInstrumentsDb()->RemoveDirectory(Dir, Force);
2888        } catch (Exception e) {
2889             result.Error(e);
2890        }
2891    #else
2892        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2893    #endif
2894        return result.Produce();
2895    }
2896    
2897    String LSCPServer::GetDbInstrumentDirectoryCount(String Dir, bool Recursive) {
2898        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2899        LSCPResultSet result;
2900    #if HAVE_SQLITE3
2901        try {
2902            result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir, Recursive));
2903        } catch (Exception e) {
2904             result.Error(e);
2905        }
2906    #else
2907        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2908    #endif
2909        return result.Produce();
2910    }
2911    
2912    String LSCPServer::GetDbInstrumentDirectories(String Dir, bool Recursive) {
2913        dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2914        LSCPResultSet result;
2915    #if HAVE_SQLITE3
2916        try {
2917            String list;
2918            StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir, Recursive);
2919    
2920            for (int i = 0; i < dirs->size(); i++) {
2921                if (list != "") list += ",";
2922                list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2923            }
2924    
2925            result.Add(list);
2926        } catch (Exception e) {
2927             result.Error(e);
2928        }
2929    #else
2930        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2931    #endif
2932        return result.Produce();
2933    }
2934    
2935    String LSCPServer::GetDbInstrumentDirectoryInfo(String Dir) {
2936        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryInfo(Dir=%s)\n", Dir.c_str()));
2937        LSCPResultSet result;
2938    #if HAVE_SQLITE3
2939        try {
2940            DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2941    
2942            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2943            result.Add("CREATED", info.Created);
2944            result.Add("MODIFIED", info.Modified);
2945        } catch (Exception e) {
2946             result.Error(e);
2947        }
2948    #else
2949        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2950    #endif
2951        return result.Produce();
2952    }
2953    
2954    String LSCPServer::SetDbInstrumentDirectoryName(String Dir, String Name) {
2955        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryName(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
2956        LSCPResultSet result;
2957    #if HAVE_SQLITE3
2958        try {
2959            InstrumentsDb::GetInstrumentsDb()->RenameDirectory(Dir, Name);
2960        } catch (Exception e) {
2961             result.Error(e);
2962        }
2963    #else
2964        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2965    #endif
2966        return result.Produce();
2967    }
2968    
2969    String LSCPServer::MoveDbInstrumentDirectory(String Dir, String Dst) {
2970        dmsg(2,("LSCPServer: MoveDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2971        LSCPResultSet result;
2972    #if HAVE_SQLITE3
2973        try {
2974            InstrumentsDb::GetInstrumentsDb()->MoveDirectory(Dir, Dst);
2975        } catch (Exception e) {
2976             result.Error(e);
2977        }
2978    #else
2979        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2980    #endif
2981        return result.Produce();
2982    }
2983    
2984    String LSCPServer::CopyDbInstrumentDirectory(String Dir, String Dst) {
2985        dmsg(2,("LSCPServer: CopyDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2986        LSCPResultSet result;
2987    #if HAVE_SQLITE3
2988        try {
2989            InstrumentsDb::GetInstrumentsDb()->CopyDirectory(Dir, Dst);
2990        } catch (Exception e) {
2991             result.Error(e);
2992        }
2993    #else
2994        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2995    #endif
2996        return result.Produce();
2997    }
2998    
2999    String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {
3000        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
3001        LSCPResultSet result;
3002    #if HAVE_SQLITE3
3003        try {
3004            InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);
3005        } catch (Exception e) {
3006             result.Error(e);
3007        }
3008    #else
3009        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3010    #endif
3011        return result.Produce();
3012    }
3013    
3014    String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
3015        dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
3016        LSCPResultSet result;
3017    #if HAVE_SQLITE3
3018        try {
3019            int id;
3020            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
3021            id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
3022            if (bBackground) result = id;
3023        } catch (Exception e) {
3024             result.Error(e);
3025        }
3026    #else
3027        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3028    #endif
3029        return result.Produce();
3030    }
3031    
3032    String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground, bool insDir) {
3033        dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d,insDir=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground, insDir));
3034        LSCPResultSet result;
3035    #if HAVE_SQLITE3
3036        try {
3037            int id;
3038            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
3039            if (ScanMode.compare("RECURSIVE") == 0) {
3040                id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground, insDir);
3041            } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
3042                id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground, insDir);
3043            } else if (ScanMode.compare("FLAT") == 0) {
3044                id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground, insDir);
3045            } else {
3046                throw Exception("Unknown scan mode: " + ScanMode);
3047            }
3048    
3049            if (bBackground) result = id;
3050        } catch (Exception e) {
3051             result.Error(e);
3052        }
3053    #else
3054        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3055    #endif
3056        return result.Produce();
3057    }
3058    
3059    String LSCPServer::RemoveDbInstrument(String Instr) {
3060        dmsg(2,("LSCPServer: RemoveDbInstrument(Instr=%s)\n", Instr.c_str()));
3061        LSCPResultSet result;
3062    #if HAVE_SQLITE3
3063        try {
3064            InstrumentsDb::GetInstrumentsDb()->RemoveInstrument(Instr);
3065        } catch (Exception e) {
3066             result.Error(e);
3067        }
3068    #else
3069        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3070    #endif
3071        return result.Produce();
3072    }
3073    
3074    String LSCPServer::GetDbInstrumentCount(String Dir, bool Recursive) {
3075        dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
3076        LSCPResultSet result;
3077    #if HAVE_SQLITE3
3078        try {
3079            result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir, Recursive));
3080        } catch (Exception e) {
3081             result.Error(e);
3082        }
3083    #else
3084        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3085    #endif
3086        return result.Produce();
3087  }  }
3088    
3089  String LSCPServer::QueryDatabase(String query) {  String LSCPServer::GetDbInstruments(String Dir, bool Recursive) {
3090        dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
3091      LSCPResultSet result;      LSCPResultSet result;
3092  #if HAVE_SQLITE3  #if HAVE_SQLITE3
3093      char* zErrMsg = NULL;      try {
3094      sqlite3 *db;          String list;
3095      String selectStr = "SELECT " + query;          StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir, Recursive);
3096    
3097      int rc = sqlite3_open("linuxsampler.db", &db);          for (int i = 0; i < instrs->size(); i++) {
3098      if (rc == SQLITE_OK)              if (list != "") list += ",";
3099      {              list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
3100              rc = sqlite3_exec(db, selectStr.c_str(), select_callback, &result, &zErrMsg);          }
3101    
3102            result.Add(list);
3103        } catch (Exception e) {
3104             result.Error(e);
3105      }      }
3106      if ( rc != SQLITE_OK )  #else
3107      {      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3108              result.Error(String(zErrMsg), rc);  #endif
3109        return result.Produce();
3110    }
3111    
3112    String LSCPServer::GetDbInstrumentInfo(String Instr) {
3113        dmsg(2,("LSCPServer: GetDbInstrumentInfo(Instr=%s)\n", Instr.c_str()));
3114        LSCPResultSet result;
3115    #if HAVE_SQLITE3
3116        try {
3117            DbInstrument info = InstrumentsDb::GetInstrumentsDb()->GetInstrumentInfo(Instr);
3118    
3119            result.Add("INSTRUMENT_FILE", info.InstrFile);
3120            result.Add("INSTRUMENT_NR", info.InstrNr);
3121            result.Add("FORMAT_FAMILY", info.FormatFamily);
3122            result.Add("FORMAT_VERSION", info.FormatVersion);
3123            result.Add("SIZE", (int)info.Size);
3124            result.Add("CREATED", info.Created);
3125            result.Add("MODIFIED", info.Modified);
3126            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
3127            result.Add("IS_DRUM", info.IsDrum);
3128            result.Add("PRODUCT", _escapeLscpResponse(info.Product));
3129            result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
3130            result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
3131        } catch (Exception e) {
3132             result.Error(e);
3133      }      }
     sqlite3_close(db);  
3134  #else  #else
3135      result.Error(String("SQLITE3 was not installed when linuxsampler was built. SELECT statement is not available."), 0);      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3136  #endif  #endif
3137      return result.Produce();      return result.Produce();
3138  }  }
3139    
3140    String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
3141        dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
3142        LSCPResultSet result;
3143    #if HAVE_SQLITE3
3144        try {
3145            ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
3146    
3147            result.Add("FILES_TOTAL", job.FilesTotal);
3148            result.Add("FILES_SCANNED", job.FilesScanned);
3149            result.Add("SCANNING", job.Scanning);
3150            result.Add("STATUS", job.Status);
3151        } catch (Exception e) {
3152             result.Error(e);
3153        }
3154    #else
3155        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3156    #endif
3157        return result.Produce();
3158    }
3159    
3160    String LSCPServer::SetDbInstrumentName(String Instr, String Name) {
3161        dmsg(2,("LSCPServer: SetDbInstrumentName(Instr=%s,Name=%s)\n", Instr.c_str(), Name.c_str()));
3162        LSCPResultSet result;
3163    #if HAVE_SQLITE3
3164        try {
3165            InstrumentsDb::GetInstrumentsDb()->RenameInstrument(Instr, Name);
3166        } catch (Exception e) {
3167             result.Error(e);
3168        }
3169    #else
3170        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3171    #endif
3172        return result.Produce();
3173    }
3174    
3175    String LSCPServer::MoveDbInstrument(String Instr, String Dst) {
3176        dmsg(2,("LSCPServer: MoveDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3177        LSCPResultSet result;
3178    #if HAVE_SQLITE3
3179        try {
3180            InstrumentsDb::GetInstrumentsDb()->MoveInstrument(Instr, Dst);
3181        } catch (Exception e) {
3182             result.Error(e);
3183        }
3184    #else
3185        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3186    #endif
3187        return result.Produce();
3188    }
3189    
3190    String LSCPServer::CopyDbInstrument(String Instr, String Dst) {
3191        dmsg(2,("LSCPServer: CopyDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3192        LSCPResultSet result;
3193    #if HAVE_SQLITE3
3194        try {
3195            InstrumentsDb::GetInstrumentsDb()->CopyInstrument(Instr, Dst);
3196        } catch (Exception e) {
3197             result.Error(e);
3198        }
3199    #else
3200        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3201    #endif
3202        return result.Produce();
3203    }
3204    
3205    String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {
3206        dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
3207        LSCPResultSet result;
3208    #if HAVE_SQLITE3
3209        try {
3210            InstrumentsDb::GetInstrumentsDb()->SetInstrumentDescription(Instr, Desc);
3211        } catch (Exception e) {
3212             result.Error(e);
3213        }
3214    #else
3215        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3216    #endif
3217        return result.Produce();
3218    }
3219    
3220    String LSCPServer::SetDbInstrumentFilePath(String OldPath, String NewPath) {
3221        dmsg(2,("LSCPServer: SetDbInstrumentFilePath(OldPath=%s,NewPath=%s)\n", OldPath.c_str(), NewPath.c_str()));
3222        LSCPResultSet result;
3223    #if HAVE_SQLITE3
3224        try {
3225            InstrumentsDb::GetInstrumentsDb()->SetInstrumentFilePath(OldPath, NewPath);
3226        } catch (Exception e) {
3227             result.Error(e);
3228        }
3229    #else
3230        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3231    #endif
3232        return result.Produce();
3233    }
3234    
3235    String LSCPServer::FindLostDbInstrumentFiles() {
3236        dmsg(2,("LSCPServer: FindLostDbInstrumentFiles()\n"));
3237        LSCPResultSet result;
3238    #if HAVE_SQLITE3
3239        try {
3240            String list;
3241            StringListPtr pLostFiles = InstrumentsDb::GetInstrumentsDb()->FindLostInstrumentFiles();
3242    
3243            for (int i = 0; i < pLostFiles->size(); i++) {
3244                if (list != "") list += ",";
3245                list += "'" + pLostFiles->at(i) + "'";
3246            }
3247    
3248            result.Add(list);
3249        } catch (Exception e) {
3250             result.Error(e);
3251        }
3252    #else
3253        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3254    #endif
3255        return result.Produce();
3256    }
3257    
3258    String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
3259        dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
3260        LSCPResultSet result;
3261    #if HAVE_SQLITE3
3262        try {
3263            SearchQuery Query;
3264            std::map<String,String>::iterator iter;
3265            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3266                if (iter->first.compare("NAME") == 0) {
3267                    Query.Name = iter->second;
3268                } else if (iter->first.compare("CREATED") == 0) {
3269                    Query.SetCreated(iter->second);
3270                } else if (iter->first.compare("MODIFIED") == 0) {
3271                    Query.SetModified(iter->second);
3272                } else if (iter->first.compare("DESCRIPTION") == 0) {
3273                    Query.Description = iter->second;
3274                } else {
3275                    throw Exception("Unknown search criteria: " + iter->first);
3276                }
3277            }
3278    
3279            String list;
3280            StringListPtr pDirectories =
3281                InstrumentsDb::GetInstrumentsDb()->FindDirectories(Dir, &Query, Recursive);
3282    
3283            for (int i = 0; i < pDirectories->size(); i++) {
3284                if (list != "") list += ",";
3285                list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
3286            }
3287    
3288            result.Add(list);
3289        } catch (Exception e) {
3290             result.Error(e);
3291        }
3292    #else
3293        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3294    #endif
3295        return result.Produce();
3296    }
3297    
3298    String LSCPServer::FindDbInstruments(String Dir, std::map<String,String> Parameters, bool Recursive) {
3299        dmsg(2,("LSCPServer: FindDbInstruments(Dir=%s)\n", Dir.c_str()));
3300        LSCPResultSet result;
3301    #if HAVE_SQLITE3
3302        try {
3303            SearchQuery Query;
3304            std::map<String,String>::iterator iter;
3305            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3306                if (iter->first.compare("NAME") == 0) {
3307                    Query.Name = iter->second;
3308                } else if (iter->first.compare("FORMAT_FAMILIES") == 0) {
3309                    Query.SetFormatFamilies(iter->second);
3310                } else if (iter->first.compare("SIZE") == 0) {
3311                    Query.SetSize(iter->second);
3312                } else if (iter->first.compare("CREATED") == 0) {
3313                    Query.SetCreated(iter->second);
3314                } else if (iter->first.compare("MODIFIED") == 0) {
3315                    Query.SetModified(iter->second);
3316                } else if (iter->first.compare("DESCRIPTION") == 0) {
3317                    Query.Description = iter->second;
3318                } else if (iter->first.compare("IS_DRUM") == 0) {
3319                    if (!strcasecmp(iter->second.c_str(), "true")) {
3320                        Query.InstrType = SearchQuery::DRUM;
3321                    } else {
3322                        Query.InstrType = SearchQuery::CHROMATIC;
3323                    }
3324                } else if (iter->first.compare("PRODUCT") == 0) {
3325                     Query.Product = iter->second;
3326                } else if (iter->first.compare("ARTISTS") == 0) {
3327                     Query.Artists = iter->second;
3328                } else if (iter->first.compare("KEYWORDS") == 0) {
3329                     Query.Keywords = iter->second;
3330                } else {
3331                    throw Exception("Unknown search criteria: " + iter->first);
3332                }
3333            }
3334    
3335            String list;
3336            StringListPtr pInstruments =
3337                InstrumentsDb::GetInstrumentsDb()->FindInstruments(Dir, &Query, Recursive);
3338    
3339            for (int i = 0; i < pInstruments->size(); i++) {
3340                if (list != "") list += ",";
3341                list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
3342            }
3343    
3344            result.Add(list);
3345        } catch (Exception e) {
3346             result.Error(e);
3347        }
3348    #else
3349        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3350    #endif
3351        return result.Produce();
3352    }
3353    
3354    String LSCPServer::FormatInstrumentsDb() {
3355        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3356        LSCPResultSet result;
3357    #if HAVE_SQLITE3
3358        try {
3359            InstrumentsDb::GetInstrumentsDb()->Format();
3360        } catch (Exception e) {
3361             result.Error(e);
3362        }
3363    #else
3364        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3365    #endif
3366        return result.Produce();
3367    }
3368    
3369    
3370  /**  /**
3371   * 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
3372   * mode is enabled, all commands from the client will (immediately) be   * mode is enabled, all commands from the client will (immediately) be
# Line 1817  String LSCPServer::SetEcho(yyparse_param Line 3385  String LSCPServer::SetEcho(yyparse_param
3385      }      }
3386      return result.Produce();      return result.Produce();
3387  }  }
3388    
3389    }

Legend:
Removed from v.951  
changed lines
  Added in v.1848

  ViewVC Help
Powered by ViewVC