/[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 981 by iliev, Sun Dec 17 22:35:01 2006 UTC revision 1835 by iliev, Mon Feb 16 17:56:50 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;
# Line 75  LSCPServer::LSCPServer(Sampler* pSampler Line 120  LSCPServer::LSCPServer(Sampler* pSampler
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");      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");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");
127      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");
128      LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");      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    #if defined(WIN32)
145        if (hSocket >= 0) closesocket(hSocket);
146    #else
147      if (hSocket >= 0) close(hSocket);      if (hSocket >= 0) close(hSocket);
148    #endif
149    }
150    
151    LSCPServer::EventHandler::EventHandler(LSCPServer* pParent) {
152        this->pParent = pParent;
153    }
154    
155    LSCPServer::EventHandler::~EventHandler() {
156        std::vector<midi_listener_entry> l = channelMidiListeners;
157        channelMidiListeners.clear();
158        for (int i = 0; i < l.size(); i++)
159            delete l[i].pMidiListener;
160    }
161    
162    void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
163        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
164    }
165    
166    void LSCPServer::EventHandler::ChannelAdded(SamplerChannel* pChannel) {
167        pChannel->AddEngineChangeListener(this);
168    }
169    
170    void LSCPServer::EventHandler::ChannelToBeRemoved(SamplerChannel* pChannel) {
171        if (!pChannel->GetEngineChannel()) return;
172        EngineToBeChanged(pChannel->Index());
173    }
174    
175    void LSCPServer::EventHandler::EngineToBeChanged(int ChannelId) {
176        SamplerChannel* pSamplerChannel =
177            pParent->pSampler->GetSamplerChannel(ChannelId);
178        if (!pSamplerChannel) return;
179        EngineChannel* pEngineChannel =
180            pSamplerChannel->GetEngineChannel();
181        if (!pEngineChannel) return;
182        for (std::vector<midi_listener_entry>::iterator iter = channelMidiListeners.begin(); iter != channelMidiListeners.end(); ++iter) {
183            if ((*iter).pEngineChannel == pEngineChannel) {
184                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
185                pEngineChannel->Disconnect(pMidiListener);
186                channelMidiListeners.erase(iter);
187                delete pMidiListener;
188                return;
189            }
190        }
191    }
192    
193    void LSCPServer::EventHandler::EngineChanged(int ChannelId) {
194        SamplerChannel* pSamplerChannel =
195            pParent->pSampler->GetSamplerChannel(ChannelId);
196        if (!pSamplerChannel) return;
197        EngineChannel* pEngineChannel =
198            pSamplerChannel->GetEngineChannel();
199        if (!pEngineChannel) return;
200        VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
201        pEngineChannel->Connect(pMidiListener);
202        midi_listener_entry entry = {
203            pSamplerChannel, pEngineChannel, pMidiListener
204        };
205        channelMidiListeners.push_back(entry);
206    }
207    
208    void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
209        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
210    }
211    
212    void LSCPServer::EventHandler::MidiDeviceCountChanged(int NewCount) {
213        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));
214    }
215    
216    void LSCPServer::EventHandler::MidiDeviceToBeDestroyed(MidiInputDevice* pDevice) {
217        pDevice->RemoveMidiPortCountListener(this);
218        for (int i = 0; i < pDevice->PortCount(); ++i)
219            MidiPortToBeRemoved(pDevice->GetPort(i));
220    }
221    
222    void LSCPServer::EventHandler::MidiDeviceCreated(MidiInputDevice* pDevice) {
223        pDevice->AddMidiPortCountListener(this);
224        for (int i = 0; i < pDevice->PortCount(); ++i)
225            MidiPortAdded(pDevice->GetPort(i));
226    }
227    
228    void LSCPServer::EventHandler::MidiPortCountChanged(int NewCount) {
229        // yet unused
230    }
231    
232    void LSCPServer::EventHandler::MidiPortToBeRemoved(MidiInputPort* pPort) {
233        for (std::vector<device_midi_listener_entry>::iterator iter = deviceMidiListeners.begin(); iter != deviceMidiListeners.end(); ++iter) {
234            if ((*iter).pPort == pPort) {
235                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
236                pPort->Disconnect(pMidiListener);
237                deviceMidiListeners.erase(iter);
238                delete pMidiListener;
239                return;
240            }
241        }
242    }
243    
244    void LSCPServer::EventHandler::MidiPortAdded(MidiInputPort* pPort) {
245        // find out the device ID
246        std::map<uint, MidiInputDevice*> devices =
247            pParent->pSampler->GetMidiInputDevices();
248        for (
249            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
250            iter != devices.end(); ++iter
251        ) {
252            if (iter->second == pPort->GetDevice()) { // found
253                VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
254                pPort->Connect(pMidiListener);
255                device_midi_listener_entry entry = {
256                    pPort, pMidiListener, iter->first
257                };
258                deviceMidiListeners.push_back(entry);
259                return;
260            }
261        }
262    }
263    
264    void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {
265        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));
266    }
267    
268    void LSCPServer::EventHandler::MidiInstrumentInfoChanged(int MapId, int Bank, int Program) {
269        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_info, MapId, Bank, Program));
270    }
271    
272    void LSCPServer::EventHandler::MidiInstrumentMapCountChanged(int NewCount) {
273        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_count, NewCount));
274    }
275    
276    void LSCPServer::EventHandler::MidiInstrumentMapInfoChanged(int MapId) {
277        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_info, MapId));
278    }
279    
280    void LSCPServer::EventHandler::FxSendCountChanged(int ChannelId, int NewCount) {
281        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_count, ChannelId, NewCount));
282    }
283    
284    void LSCPServer::EventHandler::VoiceCountChanged(int ChannelId, int NewCount) {
285        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_voice_count, ChannelId, NewCount));
286    }
287    
288    void LSCPServer::EventHandler::StreamCountChanged(int ChannelId, int NewCount) {
289        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_stream_count, ChannelId, NewCount));
290    }
291    
292    void LSCPServer::EventHandler::BufferFillChanged(int ChannelId, String FillData) {
293        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_buffer_fill, ChannelId, FillData));
294    }
295    
296    void LSCPServer::EventHandler::TotalVoiceCountChanged(int NewCount) {
297        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
298    }
299    
300    void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
301        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
302    }
303    
304    #if HAVE_SQLITE3
305    void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
306        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
307    }
308    
309    void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {
310        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, InstrumentsDb::toEscapedPath(Dir)));
311    }
312    
313    void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {
314        Dir = "'" + InstrumentsDb::toEscapedPath(Dir) + "'";
315        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
316        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));
317    }
318    
319    void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {
320        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, InstrumentsDb::toEscapedPath(Dir)));
321    }
322    
323    void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {
324        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, InstrumentsDb::toEscapedPath(Instr)));
325    }
326    
327    void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {
328        Instr = "'" + InstrumentsDb::toEscapedPath(Instr) + "'";
329        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
330        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));
331    }
332    
333    void LSCPServer::DbInstrumentsEventHandler::JobStatusChanged(int JobId) {
334        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instrs_job_info, JobId));
335    }
336    #endif // HAVE_SQLITE3
337    
338    void LSCPServer::RemoveListeners() {
339        pSampler->RemoveChannelCountListener(&eventHandler);
340        pSampler->RemoveAudioDeviceCountListener(&eventHandler);
341        pSampler->RemoveMidiDeviceCountListener(&eventHandler);
342        pSampler->RemoveVoiceCountListener(&eventHandler);
343        pSampler->RemoveStreamCountListener(&eventHandler);
344        pSampler->RemoveBufferFillListener(&eventHandler);
345        pSampler->RemoveTotalStreamCountListener(&eventHandler);
346        pSampler->RemoveTotalVoiceCountListener(&eventHandler);
347        pSampler->RemoveFxSendCountListener(&eventHandler);
348        MidiInstrumentMapper::RemoveMidiInstrumentCountListener(&eventHandler);
349        MidiInstrumentMapper::RemoveMidiInstrumentInfoListener(&eventHandler);
350        MidiInstrumentMapper::RemoveMidiInstrumentMapCountListener(&eventHandler);
351        MidiInstrumentMapper::RemoveMidiInstrumentMapInfoListener(&eventHandler);
352    #if HAVE_SQLITE3
353        InstrumentsDb::GetInstrumentsDb()->RemoveInstrumentsDbListener(&dbInstrumentsEventHandler);
354    #endif
355  }  }
356    
357  /**  /**
# Line 103  int LSCPServer::WaitUntilInitialized(lon Line 369  int LSCPServer::WaitUntilInitialized(lon
369  }  }
370    
371  int LSCPServer::Main() {  int LSCPServer::Main() {
372            #if defined(WIN32)
373            WSADATA wsaData;
374            int iResult;
375            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
376            if (iResult != 0) {
377                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
378                    exit(EXIT_FAILURE);
379            }
380            #endif
381      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
382      if (hSocket < 0) {      if (hSocket < 0) {
383          std::cerr << "LSCPServer: Could not create server socket." << std::endl;          std::cerr << "LSCPServer: Could not create server socket." << std::endl;
# Line 116  int LSCPServer::Main() { Line 391  int LSCPServer::Main() {
391              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
392                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
393                      std::cerr << "gave up!" << std::endl;                      std::cerr << "gave up!" << std::endl;
394                        #if defined(WIN32)
395                        closesocket(hSocket);
396                        #else
397                      close(hSocket);                      close(hSocket);
398                        #endif
399                      //return -1;                      //return -1;
400                      exit(EXIT_FAILURE);                      exit(EXIT_FAILURE);
401                  }                  }
# Line 129  int LSCPServer::Main() { Line 408  int LSCPServer::Main() {
408      listen(hSocket, 1);      listen(hSocket, 1);
409      Initialized.Set(true);      Initialized.Set(true);
410    
411        // Registering event listeners
412        pSampler->AddChannelCountListener(&eventHandler);
413        pSampler->AddAudioDeviceCountListener(&eventHandler);
414        pSampler->AddMidiDeviceCountListener(&eventHandler);
415        pSampler->AddVoiceCountListener(&eventHandler);
416        pSampler->AddStreamCountListener(&eventHandler);
417        pSampler->AddBufferFillListener(&eventHandler);
418        pSampler->AddTotalStreamCountListener(&eventHandler);
419        pSampler->AddTotalVoiceCountListener(&eventHandler);
420        pSampler->AddFxSendCountListener(&eventHandler);
421        MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
422        MidiInstrumentMapper::AddMidiInstrumentInfoListener(&eventHandler);
423        MidiInstrumentMapper::AddMidiInstrumentMapCountListener(&eventHandler);
424        MidiInstrumentMapper::AddMidiInstrumentMapInfoListener(&eventHandler);
425    #if HAVE_SQLITE3
426        InstrumentsDb::GetInstrumentsDb()->AddInstrumentsDbListener(&dbInstrumentsEventHandler);
427    #endif
428      // now wait for client connections and handle their requests      // now wait for client connections and handle their requests
429      sockaddr_in client;      sockaddr_in client;
430      int length = sizeof(client);      int length = sizeof(client);
# Line 139  int LSCPServer::Main() { Line 435  int LSCPServer::Main() {
435      timeval timeout;      timeval timeout;
436    
437      while (true) {      while (true) {
438            #if CONFIG_PTHREAD_TESTCANCEL
439                    TestCancel();
440            #endif
441          // 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
442          {          {
443              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
# Line 146  int LSCPServer::Main() { Line 445  int LSCPServer::Main() {
445              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
446              for (; itEngineChannel != itEnd; ++itEngineChannel) {              for (; itEngineChannel != itEnd; ++itEngineChannel) {
447                  if ((*itEngineChannel)->StatusChanged()) {                  if ((*itEngineChannel)->StatusChanged()) {
448                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->GetSamplerChannel()->Index()));
449                    }
450    
451                    for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
452                        FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
453                        if(fxs != NULL && fxs->IsInfoChanged()) {
454                            int chn = (*itEngineChannel)->GetSamplerChannel()->Index();
455                            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
456                            fxs->SetInfoChanged(false);
457                        }
458                    }
459                }
460            }
461    
462            // check if MIDI data arrived on some engine channel
463            for (int i = 0; i < eventHandler.channelMidiListeners.size(); ++i) {
464                const EventHandler::midi_listener_entry entry =
465                    eventHandler.channelMidiListeners[i];
466                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
467                if (pMidiListener->NotesChanged()) {
468                    for (int iNote = 0; iNote < 128; iNote++) {
469                        if (pMidiListener->NoteChanged(iNote)) {
470                            const bool bActive = pMidiListener->NoteIsActive(iNote);
471                            LSCPServer::SendLSCPNotify(
472                                LSCPEvent(
473                                    LSCPEvent::event_channel_midi,
474                                    entry.pSamplerChannel->Index(),
475                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
476                                    iNote,
477                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
478                                            : pMidiListener->NoteOffVelocity(iNote)
479                                )
480                            );
481                        }
482                    }
483                }
484            }
485    
486            // check if MIDI data arrived on some MIDI device
487            for (int i = 0; i < eventHandler.deviceMidiListeners.size(); ++i) {
488                const EventHandler::device_midi_listener_entry entry =
489                    eventHandler.deviceMidiListeners[i];
490                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
491                if (pMidiListener->NotesChanged()) {
492                    for (int iNote = 0; iNote < 128; iNote++) {
493                        if (pMidiListener->NoteChanged(iNote)) {
494                            const bool bActive = pMidiListener->NoteIsActive(iNote);
495                            LSCPServer::SendLSCPNotify(
496                                LSCPEvent(
497                                    LSCPEvent::event_device_midi,
498                                    entry.uiDeviceID,
499                                    entry.pPort->GetPortNumber(),
500                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
501                                    iNote,
502                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
503                                            : pMidiListener->NoteOffVelocity(iNote)
504                                )
505                            );
506                        }
507                  }                  }
508              }              }
509          }          }
# Line 169  int LSCPServer::Main() { Line 526  int LSCPServer::Main() {
526    
527          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);
528    
529          if (retval == 0)          if (retval == 0 || (retval == -1 && errno == EINTR))
530                  continue; //Nothing try again                  continue; //Nothing try again
531          if (retval == -1) {          if (retval == -1) {
532                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
533                    #if defined(WIN32)
534                    closesocket(hSocket);
535                    #else
536                  close(hSocket);                  close(hSocket);
537                    #endif
538                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
539          }          }
540    
# Line 185  int LSCPServer::Main() { Line 546  int LSCPServer::Main() {
546                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
547                  }                  }
548    
549                    #if defined(WIN32)
550                    u_long nonblock_io = 1;
551                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
552                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
553                      exit(EXIT_FAILURE);
554                    }
555            #else
556                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
557                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
558                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
559                  }                  }
560                    #endif
561    
562                  // Parser initialization                  // Parser initialization
563                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 212  int LSCPServer::Main() { Line 581  int LSCPServer::Main() {
581                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
582                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
583                                  currentSocket = (*iter).hSession;  //a hack                                  currentSocket = (*iter).hSession;  //a hack
584                                    itCurrentSession = iter; // another hack
585                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
586                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
587                                      AnswerClient(bufferedCommands[currentSocket]);                                      AnswerClient(bufferedCommands[currentSocket]);
588                                  }                                  }
589                                  int result = yyparse(&(*iter));                                  int result = yyparse(&(*iter));
590                                  currentSocket = -1;     //continuation of a hack                                  currentSocket = -1;     //continuation of a hack
591                                    itCurrentSession = Sessions.end(); // hack as well
592                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
593                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?
594                                          CloseConnection(iter);                                          CloseConnection(iter);
# Line 245  void LSCPServer::CloseConnection( std::v Line 616  void LSCPServer::CloseConnection( std::v
616          NotifyMutex.Lock();          NotifyMutex.Lock();
617          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
618          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
619            #if defined(WIN32)
620            closesocket(socket);
621            #else
622          close(socket);          close(socket);
623            #endif
624          NotifyMutex.Unlock();          NotifyMutex.Unlock();
625  }  }
626    
627    void LSCPServer::LockRTNotify() {
628        RTNotifyMutex.Lock();
629    }
630    
631    void LSCPServer::UnlockRTNotify() {
632        RTNotifyMutex.Unlock();
633    }
634    
635  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
636          int subs = 0;          int subs = 0;
637          SubscriptionMutex.Lock();          SubscriptionMutex.Lock();
# Line 310  extern int GetLSCPCommand( void *buf, in Line 693  extern int GetLSCPCommand( void *buf, in
693          return command.size();          return command.size();
694  }  }
695    
696    extern yyparse_param_t* GetCurrentYaccSession() {
697        return &(*itCurrentSession);
698    }
699    
700  /**  /**
701   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
702   * If command is read, it will return true. Otherwise false is returned.   * If command is read, it will return true. Otherwise false is returned.
# Line 320  bool LSCPServer::GetLSCPCommand( std::ve Line 707  bool LSCPServer::GetLSCPCommand( std::ve
707          char c;          char c;
708          int i = 0;          int i = 0;
709          while (true) {          while (true) {
710                    #if defined(WIN32)
711                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
712                    #else
713                  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
714                    #endif
715                  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
716                          CloseConnection(iter);                          CloseConnection(iter);
717                          break;                          break;
# Line 335  bool LSCPServer::GetLSCPCommand( std::ve Line 726  bool LSCPServer::GetLSCPCommand( std::ve
726                          }                          }
727                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
728                  }                  }
729                    #if defined(WIN32)
730                    if (result == SOCKET_ERROR) {
731                        int wsa_lasterror = WSAGetLastError();
732                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
733                                    return false;
734                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
735                            CloseConnection(iter);
736                            break;
737                    }
738                    #else
739                  if (result == -1) {                  if (result == -1) {
740                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
741                                  return false;                                  return false;
# Line 373  bool LSCPServer::GetLSCPCommand( std::ve Line 774  bool LSCPServer::GetLSCPCommand( std::ve
774                          CloseConnection(iter);                          CloseConnection(iter);
775                          break;                          break;
776                  }                  }
777                    #endif
778          }          }
779          return false;          return false;
780  }  }
# Line 490  String LSCPServer::DestroyMidiInputDevic Line 892  String LSCPServer::DestroyMidiInputDevic
892      return result.Produce();      return result.Produce();
893  }  }
894    
895    EngineChannel* LSCPServer::GetEngineChannel(uint uiSamplerChannel) {
896        SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
897        if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
898    
899        EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
900        if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
901    
902        return pEngineChannel;
903    }
904    
905  /**  /**
906   * Will be called by the parser to load an instrument.   * Will be called by the parser to load an instrument.
907   */   */
# Line 636  String LSCPServer::GetEngineInfo(String Line 1048  String LSCPServer::GetEngineInfo(String
1048      LockRTNotify();      LockRTNotify();
1049      try {      try {
1050          Engine* pEngine = EngineFactory::Create(EngineName);          Engine* pEngine = EngineFactory::Create(EngineName);
1051          result.Add("DESCRIPTION", pEngine->Description());          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
1052          result.Add("VERSION",     pEngine->Version());          result.Add("VERSION",     pEngine->Version());
1053          EngineFactory::Destroy(pEngine);          EngineFactory::Destroy(pEngine);
1054      }      }
# Line 670  String LSCPServer::GetChannelInfo(uint u Line 1082  String LSCPServer::GetChannelInfo(uint u
1082          String AudioRouting;          String AudioRouting;
1083          int Mute = 0;          int Mute = 0;
1084          bool Solo = false;          bool Solo = false;
1085          String MidiInstrumentMap;          String MidiInstrumentMap = "NONE";
1086    
1087          if (pEngineChannel) {          if (pEngineChannel) {
1088              EngineName          = pEngineChannel->EngineName();              EngineName          = pEngineChannel->EngineName();
# Line 709  String LSCPServer::GetChannelInfo(uint u Line 1121  String LSCPServer::GetChannelInfo(uint u
1121          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
1122          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
1123    
1124            // convert the filename into the correct encoding as defined for LSCP
1125            // (especially in terms of special characters -> escape sequences)
1126            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
1127    #if WIN32
1128                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
1129    #else
1130                // assuming POSIX
1131                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
1132    #endif
1133            }
1134    
1135          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
1136          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
1137          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
1138          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
1139          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
1140          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
# Line 731  String LSCPServer::GetVoiceCount(uint ui Line 1154  String LSCPServer::GetVoiceCount(uint ui
1154      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));
1155      LSCPResultSet result;      LSCPResultSet result;
1156      try {      try {
1157          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");  
1158          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");
1159          result.Add(pEngineChannel->GetEngine()->VoiceCount());          result.Add(pEngineChannel->GetEngine()->VoiceCount());
1160      }      }
# Line 752  String LSCPServer::GetStreamCount(uint u Line 1172  String LSCPServer::GetStreamCount(uint u
1172      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));
1173      LSCPResultSet result;      LSCPResultSet result;
1174      try {      try {
1175          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");  
1176          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");
1177          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());
1178      }      }
# Line 773  String LSCPServer::GetBufferFill(fill_re Line 1190  String LSCPServer::GetBufferFill(fill_re
1190      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));
1191      LSCPResultSet result;      LSCPResultSet result;
1192      try {      try {
1193          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");  
1194          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");
1195          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");
1196          else {          else {
# Line 864  String LSCPServer::GetMidiInputDriverInf Line 1278  String LSCPServer::GetMidiInputDriverInf
1278              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1279                  if (s != "") s += ",";                  if (s != "") s += ",";
1280                  s += iter->first;                  s += iter->first;
1281                    delete iter->second;
1282              }              }
1283              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1284          }          }
# Line 888  String LSCPServer::GetAudioOutputDriverI Line 1303  String LSCPServer::GetAudioOutputDriverI
1303              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1304                  if (s != "") s += ",";                  if (s != "") s += ",";
1305                  s += iter->first;                  s += iter->first;
1306                    delete iter->second;
1307              }              }
1308              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1309          }          }
# Line 918  String LSCPServer::GetMidiInputDriverPar Line 1334  String LSCPServer::GetMidiInputDriverPar
1334          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1335          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1336          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1337            delete pParameter;
1338      }      }
1339      catch (Exception e) {      catch (Exception e) {
1340          result.Error(e);          result.Error(e);
# Line 945  String LSCPServer::GetAudioOutputDriverP Line 1362  String LSCPServer::GetAudioOutputDriverP
1362          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1363          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1364          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1365            delete pParameter;
1366      }      }
1367      catch (Exception e) {      catch (Exception e) {
1368          result.Error(e);          result.Error(e);
# Line 1454  String LSCPServer::SetVolume(double dVol Line 1872  String LSCPServer::SetVolume(double dVol
1872      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));
1873      LSCPResultSet result;      LSCPResultSet result;
1874      try {      try {
1875          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");  
1876          pEngineChannel->Volume(dVolume);          pEngineChannel->Volume(dVolume);
1877      }      }
1878      catch (Exception e) {      catch (Exception e) {
# Line 1473  String LSCPServer::SetChannelMute(bool b Line 1888  String LSCPServer::SetChannelMute(bool b
1888      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));
1889      LSCPResultSet result;      LSCPResultSet result;
1890      try {      try {
1891          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");  
1892    
1893          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);
1894          else pEngineChannel->SetMute(1);          else pEngineChannel->SetMute(1);
# Line 1494  String LSCPServer::SetChannelSolo(bool b Line 1905  String LSCPServer::SetChannelSolo(bool b
1905      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));
1906      LSCPResultSet result;      LSCPResultSet result;
1907      try {      try {
1908          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");  
1909    
1910          bool oldSolo = pEngineChannel->GetSolo();          bool oldSolo = pEngineChannel->GetSolo();
1911          bool hadSoloChannel = HasSoloChannel();          bool hadSoloChannel = HasSoloChannel();
1912            
1913          pEngineChannel->SetSolo(bSolo);          pEngineChannel->SetSolo(bSolo);
1914            
1915          if(!oldSolo && bSolo) {          if(!oldSolo && bSolo) {
1916              if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);              if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);
1917              if(!hadSoloChannel) MuteNonSoloChannels();              if(!hadSoloChannel) MuteNonSoloChannels();
1918          }          }
1919            
1920          if(oldSolo && !bSolo) {          if(oldSolo && !bSolo) {
1921              if(!HasSoloChannel()) UnmuteChannels();              if(!HasSoloChannel()) UnmuteChannels();
1922              else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);              else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);
# Line 1567  void  LSCPServer::UnmuteChannels() { Line 1974  void  LSCPServer::UnmuteChannels() {
1974      }      }
1975  }  }
1976    
1977  String LSCPServer::AddOrReplaceMIDIInstrumentMapping(uint MidiMapID, uint MidiBank, uint MidiProg, String EngineType, String InstrumentFile, uint InstrumentIndex, float Volume, MidiInstrumentMapper::mode_t LoadMode, String Name) {  String LSCPServer::AddOrReplaceMIDIInstrumentMapping(uint MidiMapID, uint MidiBank, uint MidiProg, String EngineType, String InstrumentFile, uint InstrumentIndex, float Volume, MidiInstrumentMapper::mode_t LoadMode, String Name, bool bModal) {
1978      dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));      dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));
1979    
1980      midi_prog_index_t idx;      midi_prog_index_t idx;
# Line 1585  String LSCPServer::AddOrReplaceMIDIInstr Line 1992  String LSCPServer::AddOrReplaceMIDIInstr
1992    
1993      LSCPResultSet result;      LSCPResultSet result;
1994      try {      try {
1995          // PERSISTENT mapping commands might bloock for a long time, so in          // PERSISTENT mapping commands might block for a long time, so in
1996          // that case we add/replace the mapping in another thread          // that case we add/replace the mapping in another thread in case
1997          bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT);          // the NON_MODAL argument was supplied, non persistent mappings
1998            // should return immediately, so we don't need to do that for them
1999            bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT && !bModal);
2000          MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);          MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);
2001      } catch (Exception e) {      } catch (Exception e) {
2002          result.Error(e);          result.Error(e);
# Line 1616  String LSCPServer::GetMidiInstrumentMapp Line 2025  String LSCPServer::GetMidiInstrumentMapp
2025      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));
2026      LSCPResultSet result;      LSCPResultSet result;
2027      try {      try {
2028          result.Add(MidiInstrumentMapper::Entries(MidiMapID).size());          result.Add(MidiInstrumentMapper::GetInstrumentCount(MidiMapID));
2029      } catch (Exception e) {      } catch (Exception e) {
2030          result.Error(e);          result.Error(e);
2031      }      }
# Line 1627  String LSCPServer::GetMidiInstrumentMapp Line 2036  String LSCPServer::GetMidiInstrumentMapp
2036  String LSCPServer::GetAllMidiInstrumentMappings() {  String LSCPServer::GetAllMidiInstrumentMappings() {
2037      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));
2038      LSCPResultSet result;      LSCPResultSet result;
2039      std::vector<int> maps = MidiInstrumentMapper::Maps();      try {
2040      int totalMappings = 0;          result.Add(MidiInstrumentMapper::GetInstrumentCount());
2041      for (int i = 0; i < maps.size(); i++) {      } catch (Exception e) {
2042          try {          result.Error(e);
             totalMappings += MidiInstrumentMapper::Entries(maps[i]).size();  
         } catch (Exception e) { /*NOOP*/ }  
2043      }      }
     result.Add(totalMappings);  
2044      return result.Produce();      return result.Produce();
2045  }  }
2046    
# Line 1642  String LSCPServer::GetMidiInstrumentMapp Line 2048  String LSCPServer::GetMidiInstrumentMapp
2048      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));
2049      LSCPResultSet result;      LSCPResultSet result;
2050      try {      try {
2051          midi_prog_index_t idx;          MidiInstrumentMapper::entry_t entry = MidiInstrumentMapper::GetEntry(MidiMapID, MidiBank, MidiProg);
2052          idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;          // convert the filename into the correct encoding as defined for LSCP
2053          idx.midi_bank_lsb = MidiBank & 0x7f;          // (especially in terms of special characters -> escape sequences)
2054          idx.midi_prog     = MidiProg;  #if WIN32
2055            const String instrumentFileName = Path::fromWindows(entry.InstrumentFile).toLscp();
2056    #else
2057            // assuming POSIX
2058            const String instrumentFileName = Path::fromPosix(entry.InstrumentFile).toLscp();
2059    #endif
2060    
2061          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(MidiMapID);          result.Add("NAME", _escapeLscpResponse(entry.Name));
2062          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);          result.Add("ENGINE_NAME", entry.EngineName);
2063          if (iter == mappings.end()) result.Error("there is no map entry with that index");          result.Add("INSTRUMENT_FILE", instrumentFileName);
2064          else { // found          result.Add("INSTRUMENT_NR", (int) entry.InstrumentIndex);
2065              result.Add("NAME", iter->second.Name);          String instrumentName;
2066              result.Add("ENGINE_NAME", iter->second.EngineName);          Engine* pEngine = EngineFactory::Create(entry.EngineName);
2067              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);          if (pEngine) {
2068              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);              if (pEngine->GetInstrumentManager()) {
2069              String instrumentName;                  InstrumentManager::instrument_id_t instrID;
2070              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);                  instrID.FileName = entry.InstrumentFile;
2071              if (pEngine) {                  instrID.Index    = entry.InstrumentIndex;
2072                  if (pEngine->GetInstrumentManager()) {                  instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);
                     InstrumentManager::instrument_id_t instrID;  
                     instrID.FileName = iter->second.InstrumentFile;  
                     instrID.Index    = iter->second.InstrumentIndex;  
                     instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);  
                 }  
                 EngineFactory::Destroy(pEngine);  
2073              }              }
2074              result.Add("INSTRUMENT_NAME", instrumentName);              EngineFactory::Destroy(pEngine);
             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!");  
             }  
             result.Add("VOLUME", iter->second.Volume);  
2075          }          }
2076            result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
2077            switch (entry.LoadMode) {
2078                case MidiInstrumentMapper::ON_DEMAND:
2079                    result.Add("LOAD_MODE", "ON_DEMAND");
2080                    break;
2081                case MidiInstrumentMapper::ON_DEMAND_HOLD:
2082                    result.Add("LOAD_MODE", "ON_DEMAND_HOLD");
2083                    break;
2084                case MidiInstrumentMapper::PERSISTENT:
2085                    result.Add("LOAD_MODE", "PERSISTENT");
2086                    break;
2087                default:
2088                    throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");
2089            }
2090            result.Add("VOLUME", entry.Volume);
2091      } catch (Exception e) {      } catch (Exception e) {
2092          result.Error(e);          result.Error(e);
2093      }      }
# Line 1698  String LSCPServer::ListMidiInstrumentMap Line 2104  String LSCPServer::ListMidiInstrumentMap
2104          for (; iter != mappings.end(); iter++) {          for (; iter != mappings.end(); iter++) {
2105              if (s.size()) s += ",";              if (s.size()) s += ",";
2106              s += "{" + ToString(MidiMapID) + ","              s += "{" + ToString(MidiMapID) + ","
2107                       + ToString((int(iter->first.midi_bank_msb) << 7) & int(iter->first.midi_bank_lsb)) + ","                       + ToString((int(iter->first.midi_bank_msb) << 7) | int(iter->first.midi_bank_lsb)) + ","
2108                       + ToString(int(iter->first.midi_prog)) + "}";                       + ToString(int(iter->first.midi_prog)) + "}";
2109          }          }
2110          result.Add(s);          result.Add(s);
# Line 1720  String LSCPServer::ListAllMidiInstrument Line 2126  String LSCPServer::ListAllMidiInstrument
2126              for (; iter != mappings.end(); iter++) {              for (; iter != mappings.end(); iter++) {
2127                  if (s.size()) s += ",";                  if (s.size()) s += ",";
2128                  s += "{" + ToString(maps[i]) + ","                  s += "{" + ToString(maps[i]) + ","
2129                           + ToString((int(iter->first.midi_bank_msb) << 7) & int(iter->first.midi_bank_lsb)) + ","                           + ToString((int(iter->first.midi_bank_msb) << 7) | int(iter->first.midi_bank_lsb)) + ","
2130                           + ToString(int(iter->first.midi_prog)) + "}";                           + ToString(int(iter->first.midi_prog)) + "}";
2131              }              }
2132          }          }
# Line 1821  String LSCPServer::GetMidiInstrumentMap( Line 2227  String LSCPServer::GetMidiInstrumentMap(
2227      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2228      LSCPResultSet result;      LSCPResultSet result;
2229      try {      try {
2230          result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID));          result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2231            result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2232      } catch (Exception e) {      } catch (Exception e) {
2233          result.Error(e);          result.Error(e);
2234      }      }
# Line 1851  String LSCPServer::SetChannelMap(uint ui Line 2258  String LSCPServer::SetChannelMap(uint ui
2258      dmsg(2,("LSCPServer: SetChannelMap()\n"));      dmsg(2,("LSCPServer: SetChannelMap()\n"));
2259      LSCPResultSet result;      LSCPResultSet result;
2260      try {      try {
2261          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");  
2262    
2263          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();
2264          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();
# Line 1866  String LSCPServer::SetChannelMap(uint ui Line 2269  String LSCPServer::SetChannelMap(uint ui
2269      return result.Produce();      return result.Produce();
2270  }  }
2271    
2272    String LSCPServer::CreateFxSend(uint uiSamplerChannel, uint MidiCtrl, String Name) {
2273        dmsg(2,("LSCPServer: CreateFxSend()\n"));
2274        LSCPResultSet result;
2275        try {
2276            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2277    
2278            FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2279            if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");
2280    
2281            result = LSCPResultSet(pFxSend->Id()); // success
2282        } catch (Exception e) {
2283            result.Error(e);
2284        }
2285        return result.Produce();
2286    }
2287    
2288    String LSCPServer::DestroyFxSend(uint uiSamplerChannel, uint FxSendID) {
2289        dmsg(2,("LSCPServer: DestroyFxSend()\n"));
2290        LSCPResultSet result;
2291        try {
2292            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2293    
2294            FxSend* pFxSend = NULL;
2295            for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2296                if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2297                    pFxSend = pEngineChannel->GetFxSend(i);
2298                    break;
2299                }
2300            }
2301            if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2302            pEngineChannel->RemoveFxSend(pFxSend);
2303        } catch (Exception e) {
2304            result.Error(e);
2305        }
2306        return result.Produce();
2307    }
2308    
2309    String LSCPServer::GetFxSends(uint uiSamplerChannel) {
2310        dmsg(2,("LSCPServer: GetFxSends()\n"));
2311        LSCPResultSet result;
2312        try {
2313            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2314    
2315            result.Add(pEngineChannel->GetFxSendCount());
2316        } catch (Exception e) {
2317            result.Error(e);
2318        }
2319        return result.Produce();
2320    }
2321    
2322    String LSCPServer::ListFxSends(uint uiSamplerChannel) {
2323        dmsg(2,("LSCPServer: ListFxSends()\n"));
2324        LSCPResultSet result;
2325        String list;
2326        try {
2327            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2328    
2329            for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2330                FxSend* pFxSend = pEngineChannel->GetFxSend(i);
2331                if (list != "") list += ",";
2332                list += ToString(pFxSend->Id());
2333            }
2334            result.Add(list);
2335        } catch (Exception e) {
2336            result.Error(e);
2337        }
2338        return result.Produce();
2339    }
2340    
2341    FxSend* LSCPServer::GetFxSend(uint uiSamplerChannel, uint FxSendID) {
2342        EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2343    
2344        FxSend* pFxSend = NULL;
2345        for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2346            if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2347                pFxSend = pEngineChannel->GetFxSend(i);
2348                break;
2349            }
2350        }
2351        if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2352        return pFxSend;
2353    }
2354    
2355    String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {
2356        dmsg(2,("LSCPServer: GetFxSendInfo()\n"));
2357        LSCPResultSet result;
2358        try {
2359            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2360            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2361    
2362            // gather audio routing informations
2363            String AudioRouting;
2364            for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {
2365                if (AudioRouting != "") AudioRouting += ",";
2366                AudioRouting += ToString(pFxSend->DestinationChannel(chan));
2367            }
2368    
2369            // success
2370            result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2371            result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2372            result.Add("LEVEL", ToString(pFxSend->Level()));
2373            result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
2374        } catch (Exception e) {
2375            result.Error(e);
2376        }
2377        return result.Produce();
2378    }
2379    
2380    String LSCPServer::SetFxSendName(uint uiSamplerChannel, uint FxSendID, String Name) {
2381        dmsg(2,("LSCPServer: SetFxSendName()\n"));
2382        LSCPResultSet result;
2383        try {
2384            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2385    
2386            pFxSend->SetName(Name);
2387            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2388        } catch (Exception e) {
2389            result.Error(e);
2390        }
2391        return result.Produce();
2392    }
2393    
2394    String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {
2395        dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));
2396        LSCPResultSet result;
2397        try {
2398            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2399    
2400            pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);
2401            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2402        } catch (Exception e) {
2403            result.Error(e);
2404        }
2405        return result.Produce();
2406    }
2407    
2408    String LSCPServer::SetFxSendMidiController(uint uiSamplerChannel, uint FxSendID, uint MidiController) {
2409        dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));
2410        LSCPResultSet result;
2411        try {
2412            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2413    
2414            pFxSend->SetMidiController(MidiController);
2415            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2416        } catch (Exception e) {
2417            result.Error(e);
2418        }
2419        return result.Produce();
2420    }
2421    
2422    String LSCPServer::SetFxSendLevel(uint uiSamplerChannel, uint FxSendID, double dLevel) {
2423        dmsg(2,("LSCPServer: SetFxSendLevel()\n"));
2424        LSCPResultSet result;
2425        try {
2426            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2427    
2428            pFxSend->SetLevel((float)dLevel);
2429            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2430        } catch (Exception e) {
2431            result.Error(e);
2432        }
2433        return result.Produce();
2434    }
2435    
2436    String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2437        dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2438        LSCPResultSet result;
2439        try {
2440            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2441            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2442            Engine* pEngine = pEngineChannel->GetEngine();
2443            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2444            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2445            InstrumentManager::instrument_id_t instrumentID;
2446            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2447            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2448            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2449        } catch (Exception e) {
2450            result.Error(e);
2451        }
2452        return result.Produce();
2453    }
2454    
2455    String LSCPServer::SendChannelMidiData(String MidiMsg, uint uiSamplerChannel, uint Arg1, uint Arg2) {
2456        dmsg(2,("LSCPServer: SendChannelMidiData(MidiMsg=%s,uiSamplerChannel=%d,Arg1=%d,Arg2=%d)\n", MidiMsg.c_str(), uiSamplerChannel, Arg1, Arg2));
2457        LSCPResultSet result;
2458        try {
2459            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2460    
2461            if (Arg1 > 127 || Arg2 > 127) {
2462                throw Exception("Invalid MIDI message");
2463            }
2464    
2465            VirtualMidiDevice* pMidiDevice = NULL;
2466            std::vector<EventHandler::midi_listener_entry>::iterator iter = eventHandler.channelMidiListeners.begin();
2467            for (; iter != eventHandler.channelMidiListeners.end(); ++iter) {
2468                if ((*iter).pEngineChannel == pEngineChannel) {
2469                    pMidiDevice = (*iter).pMidiListener;
2470                    break;
2471                }
2472            }
2473            
2474            if(pMidiDevice == NULL) throw Exception("Couldn't find virtual MIDI device");
2475    
2476            if (MidiMsg == "NOTE_ON") {
2477                pMidiDevice->SendNoteOnToDevice(Arg1, Arg2);
2478                bool b = pMidiDevice->SendNoteOnToSampler(Arg1, Arg2);
2479                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2480            } else if (MidiMsg == "NOTE_OFF") {
2481                pMidiDevice->SendNoteOffToDevice(Arg1, Arg2);
2482                bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2);
2483                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2484            } else {
2485                throw Exception("Unknown MIDI message type: " + MidiMsg);
2486            }
2487        } catch (Exception e) {
2488            result.Error(e);
2489        }
2490        return result.Produce();
2491    }
2492    
2493  /**  /**
2494   * Will be called by the parser to reset a particular sampler channel.   * Will be called by the parser to reset a particular sampler channel.
2495   */   */
# Line 1873  String LSCPServer::ResetChannel(uint uiS Line 2497  String LSCPServer::ResetChannel(uint uiS
2497      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));
2498      LSCPResultSet result;      LSCPResultSet result;
2499      try {      try {
2500          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");  
2501          pEngineChannel->Reset();          pEngineChannel->Reset();
2502      }      }
2503      catch (Exception e) {      catch (Exception e) {
# Line 1901  String LSCPServer::ResetSampler() { Line 2522  String LSCPServer::ResetSampler() {
2522   */   */
2523  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
2524      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
2525        const std::string description =
2526            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2527      LSCPResultSet result;      LSCPResultSet result;
2528      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
2529      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
2530      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2531    #if HAVE_SQLITE3
2532        result.Add("INSTRUMENTS_DB_SUPPORT", "yes");
2533    #else
2534        result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2535    #endif
2536    
2537        return result.Produce();
2538    }
2539    
2540    /**
2541     * Will be called by the parser to return the current number of all active streams.
2542     */
2543    String LSCPServer::GetTotalStreamCount() {
2544        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2545        LSCPResultSet result;
2546        result.Add(pSampler->GetDiskStreamCount());
2547      return result.Produce();      return result.Produce();
2548  }  }
2549    
# Line 1924  String LSCPServer::GetTotalVoiceCount() Line 2563  String LSCPServer::GetTotalVoiceCount()
2563  String LSCPServer::GetTotalVoiceCountMax() {  String LSCPServer::GetTotalVoiceCountMax() {
2564      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));
2565      LSCPResultSet result;      LSCPResultSet result;
2566      result.Add(EngineFactory::EngineInstances().size() * CONFIG_MAX_VOICES);      result.Add(EngineFactory::EngineInstances().size() * GLOBAL_MAX_VOICES);
2567        return result.Produce();
2568    }
2569    
2570    /**
2571     * Will be called by the parser to return the sampler global maximum
2572     * allowed number of voices.
2573     */
2574    String LSCPServer::GetGlobalMaxVoices() {
2575        dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n"));
2576        LSCPResultSet result;
2577        result.Add(GLOBAL_MAX_VOICES);
2578        return result.Produce();
2579    }
2580    
2581    /**
2582     * Will be called by the parser to set the sampler global maximum number of
2583     * voices.
2584     */
2585    String LSCPServer::SetGlobalMaxVoices(int iVoices) {
2586        dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices));
2587        LSCPResultSet result;
2588        try {
2589            if (iVoices < 1) throw Exception("Maximum voices may not be less than 1");
2590            GLOBAL_MAX_VOICES = iVoices; // see common/global_private.cpp
2591            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
2592            if (engines.size() > 0) {
2593                std::set<Engine*>::iterator iter = engines.begin();
2594                std::set<Engine*>::iterator end  = engines.end();
2595                for (; iter != end; ++iter) {
2596                    (*iter)->SetMaxVoices(iVoices);
2597                }
2598            }
2599            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOICES", GLOBAL_MAX_VOICES));
2600        } catch (Exception e) {
2601            result.Error(e);
2602        }
2603        return result.Produce();
2604    }
2605    
2606    /**
2607     * Will be called by the parser to return the sampler global maximum
2608     * allowed number of disk streams.
2609     */
2610    String LSCPServer::GetGlobalMaxStreams() {
2611        dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n"));
2612        LSCPResultSet result;
2613        result.Add(GLOBAL_MAX_STREAMS);
2614        return result.Produce();
2615    }
2616    
2617    /**
2618     * Will be called by the parser to set the sampler global maximum number of
2619     * disk streams.
2620     */
2621    String LSCPServer::SetGlobalMaxStreams(int iStreams) {
2622        dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams));
2623        LSCPResultSet result;
2624        try {
2625            if (iStreams < 0) throw Exception("Maximum disk streams may not be negative");
2626            GLOBAL_MAX_STREAMS = iStreams; // see common/global_private.cpp
2627            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
2628            if (engines.size() > 0) {
2629                std::set<Engine*>::iterator iter = engines.begin();
2630                std::set<Engine*>::iterator end  = engines.end();
2631                for (; iter != end; ++iter) {
2632                    (*iter)->SetMaxDiskStreams(iStreams);
2633                }
2634            }
2635            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "STREAMS", GLOBAL_MAX_STREAMS));
2636        } catch (Exception e) {
2637            result.Error(e);
2638        }
2639        return result.Produce();
2640    }
2641    
2642    String LSCPServer::GetGlobalVolume() {
2643        LSCPResultSet result;
2644        result.Add(ToString(GLOBAL_VOLUME)); // see common/global.cpp
2645      return result.Produce();      return result.Produce();
2646  }  }
2647    
2648    String LSCPServer::SetGlobalVolume(double dVolume) {
2649        LSCPResultSet result;
2650        try {
2651            if (dVolume < 0) throw Exception("Volume may not be negative");
2652            GLOBAL_VOLUME = dVolume; // see common/global_private.cpp
2653            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
2654        } catch (Exception e) {
2655            result.Error(e);
2656        }
2657        return result.Produce();
2658    }
2659    
2660    String LSCPServer::GetFileInstruments(String Filename) {
2661        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2662        LSCPResultSet result;
2663        try {
2664            VerifyFile(Filename);
2665        } catch (Exception e) {
2666            result.Error(e);
2667            return result.Produce();
2668        }
2669        // try to find a sampler engine that can handle the file
2670        bool bFound = false;
2671        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2672        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2673            Engine* pEngine = NULL;
2674            try {
2675                pEngine = EngineFactory::Create(engineTypes[i]);
2676                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2677                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2678                if (pManager) {
2679                    std::vector<InstrumentManager::instrument_id_t> IDs =
2680                        pManager->GetInstrumentFileContent(Filename);
2681                    // return the amount of instruments in the file
2682                    result.Add(IDs.size());
2683                    // no more need to ask other engine types
2684                    bFound = true;
2685                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2686            } catch (Exception e) {
2687                // NOOP, as exception is thrown if engine doesn't support file
2688            }
2689            if (pEngine) EngineFactory::Destroy(pEngine);
2690        }
2691    
2692        if (!bFound) result.Error("Unknown file format");
2693        return result.Produce();
2694    }
2695    
2696    String LSCPServer::ListFileInstruments(String Filename) {
2697        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2698        LSCPResultSet result;
2699        try {
2700            VerifyFile(Filename);
2701        } catch (Exception e) {
2702            result.Error(e);
2703            return result.Produce();
2704        }
2705        // try to find a sampler engine that can handle the file
2706        bool bFound = false;
2707        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2708        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2709            Engine* pEngine = NULL;
2710            try {
2711                pEngine = EngineFactory::Create(engineTypes[i]);
2712                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2713                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2714                if (pManager) {
2715                    std::vector<InstrumentManager::instrument_id_t> IDs =
2716                        pManager->GetInstrumentFileContent(Filename);
2717                    // return a list of IDs of the instruments in the file
2718                    String s;
2719                    for (int j = 0; j < IDs.size(); j++) {
2720                        if (s.size()) s += ",";
2721                        s += ToString(IDs[j].Index);
2722                    }
2723                    result.Add(s);
2724                    // no more need to ask other engine types
2725                    bFound = true;
2726                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2727            } catch (Exception e) {
2728                // NOOP, as exception is thrown if engine doesn't support file
2729            }
2730            if (pEngine) EngineFactory::Destroy(pEngine);
2731        }
2732    
2733        if (!bFound) result.Error("Unknown file format");
2734        return result.Produce();
2735    }
2736    
2737    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2738        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2739        LSCPResultSet result;
2740        try {
2741            VerifyFile(Filename);
2742        } catch (Exception e) {
2743            result.Error(e);
2744            return result.Produce();
2745        }
2746        InstrumentManager::instrument_id_t id;
2747        id.FileName = Filename;
2748        id.Index    = InstrumentID;
2749        // try to find a sampler engine that can handle the file
2750        bool bFound = false;
2751        bool bFatalErr = false;
2752        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2753        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2754            Engine* pEngine = NULL;
2755            try {
2756                pEngine = EngineFactory::Create(engineTypes[i]);
2757                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2758                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2759                if (pManager) {
2760                    // check if the instrument index is valid
2761                    // FIXME: this won't work if an engine only supports parts of the instrument file
2762                    std::vector<InstrumentManager::instrument_id_t> IDs =
2763                        pManager->GetInstrumentFileContent(Filename);
2764                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2765                        std::stringstream ss;
2766                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2767                        bFatalErr = true;
2768                        throw Exception(ss.str());
2769                    }
2770                    // get the info of the requested instrument
2771                    InstrumentManager::instrument_info_t info =
2772                        pManager->GetInstrumentInfo(id);
2773                    // return detailed informations about the file
2774                    result.Add("NAME", info.InstrumentName);
2775                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2776                    result.Add("FORMAT_VERSION", info.FormatVersion);
2777                    result.Add("PRODUCT", info.Product);
2778                    result.Add("ARTISTS", info.Artists);
2779    
2780                    std::stringstream ss;
2781                    bool b = false;
2782                    for (int i = 0; i < 128; i++) {
2783                        if (info.KeyBindings[i]) {
2784                            if (b) ss << ',';
2785                            ss << i; b = true;
2786                        }
2787                    }
2788                    result.Add("KEY_BINDINGS", ss.str());
2789    
2790                    b = false;
2791                    std::stringstream ss2;
2792                    for (int i = 0; i < 128; i++) {
2793                        if (info.KeySwitchBindings[i]) {
2794                            if (b) ss2 << ',';
2795                            ss2 << i; b = true;
2796                        }
2797                    }
2798                    result.Add("KEYSWITCH_BINDINGS", ss2.str());
2799                    // no more need to ask other engine types
2800                    bFound = true;
2801                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2802            } catch (Exception e) {
2803                // usually NOOP, as exception is thrown if engine doesn't support file
2804                if (bFatalErr) result.Error(e);
2805            }
2806            if (pEngine) EngineFactory::Destroy(pEngine);
2807        }
2808    
2809        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2810        return result.Produce();
2811    }
2812    
2813    void LSCPServer::VerifyFile(String Filename) {
2814        #if WIN32
2815        WIN32_FIND_DATA win32FileAttributeData;
2816        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2817        if (!res) {
2818            std::stringstream ss;
2819            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2820            throw Exception(ss.str());
2821        }
2822        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2823            throw Exception("Directory is specified");
2824        }
2825        #else
2826        File f(Filename);
2827        if(!f.Exist()) throw Exception(f.GetErrorMsg());
2828        if (f.IsDirectory()) throw Exception("Directory is specified");
2829        #endif
2830    }
2831    
2832  /**  /**
2833   * 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
2834   * server for receiving event messages.   * server for receiving event messages.
# Line 1954  String LSCPServer::UnsubscribeNotificati Line 2855  String LSCPServer::UnsubscribeNotificati
2855      return result.Produce();      return result.Produce();
2856  }  }
2857    
2858  static int select_callback(void * lscpResultSet, int argc,  String LSCPServer::AddDbInstrumentDirectory(String Dir) {
2859                          char **argv, char **azColName)      dmsg(2,("LSCPServer: AddDbInstrumentDirectory(Dir=%s)\n", Dir.c_str()));
2860  {      LSCPResultSet result;
2861      LSCPResultSet* resultSet = (LSCPResultSet*) lscpResultSet;  #if HAVE_SQLITE3
2862      resultSet->Add(argc, argv);      try {
2863      return 0;          InstrumentsDb::GetInstrumentsDb()->AddDirectory(Dir);
2864        } catch (Exception e) {
2865             result.Error(e);
2866        }
2867    #else
2868        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2869    #endif
2870        return result.Produce();
2871    }
2872    
2873    String LSCPServer::RemoveDbInstrumentDirectory(String Dir, bool Force) {
2874        dmsg(2,("LSCPServer: RemoveDbInstrumentDirectory(Dir=%s,Force=%d)\n", Dir.c_str(), Force));
2875        LSCPResultSet result;
2876    #if HAVE_SQLITE3
2877        try {
2878            InstrumentsDb::GetInstrumentsDb()->RemoveDirectory(Dir, Force);
2879        } catch (Exception e) {
2880             result.Error(e);
2881        }
2882    #else
2883        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2884    #endif
2885        return result.Produce();
2886    }
2887    
2888    String LSCPServer::GetDbInstrumentDirectoryCount(String Dir, bool Recursive) {
2889        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2890        LSCPResultSet result;
2891    #if HAVE_SQLITE3
2892        try {
2893            result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir, Recursive));
2894        } catch (Exception e) {
2895             result.Error(e);
2896        }
2897    #else
2898        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2899    #endif
2900        return result.Produce();
2901    }
2902    
2903    String LSCPServer::GetDbInstrumentDirectories(String Dir, bool Recursive) {
2904        dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2905        LSCPResultSet result;
2906    #if HAVE_SQLITE3
2907        try {
2908            String list;
2909            StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir, Recursive);
2910    
2911            for (int i = 0; i < dirs->size(); i++) {
2912                if (list != "") list += ",";
2913                list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2914            }
2915    
2916            result.Add(list);
2917        } catch (Exception e) {
2918             result.Error(e);
2919        }
2920    #else
2921        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2922    #endif
2923        return result.Produce();
2924    }
2925    
2926    String LSCPServer::GetDbInstrumentDirectoryInfo(String Dir) {
2927        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryInfo(Dir=%s)\n", Dir.c_str()));
2928        LSCPResultSet result;
2929    #if HAVE_SQLITE3
2930        try {
2931            DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2932    
2933            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2934            result.Add("CREATED", info.Created);
2935            result.Add("MODIFIED", info.Modified);
2936        } catch (Exception e) {
2937             result.Error(e);
2938        }
2939    #else
2940        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2941    #endif
2942        return result.Produce();
2943    }
2944    
2945    String LSCPServer::SetDbInstrumentDirectoryName(String Dir, String Name) {
2946        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryName(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
2947        LSCPResultSet result;
2948    #if HAVE_SQLITE3
2949        try {
2950            InstrumentsDb::GetInstrumentsDb()->RenameDirectory(Dir, Name);
2951        } catch (Exception e) {
2952             result.Error(e);
2953        }
2954    #else
2955        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2956    #endif
2957        return result.Produce();
2958    }
2959    
2960    String LSCPServer::MoveDbInstrumentDirectory(String Dir, String Dst) {
2961        dmsg(2,("LSCPServer: MoveDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2962        LSCPResultSet result;
2963    #if HAVE_SQLITE3
2964        try {
2965            InstrumentsDb::GetInstrumentsDb()->MoveDirectory(Dir, Dst);
2966        } catch (Exception e) {
2967             result.Error(e);
2968        }
2969    #else
2970        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2971    #endif
2972        return result.Produce();
2973    }
2974    
2975    String LSCPServer::CopyDbInstrumentDirectory(String Dir, String Dst) {
2976        dmsg(2,("LSCPServer: CopyDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2977        LSCPResultSet result;
2978    #if HAVE_SQLITE3
2979        try {
2980            InstrumentsDb::GetInstrumentsDb()->CopyDirectory(Dir, Dst);
2981        } catch (Exception e) {
2982             result.Error(e);
2983        }
2984    #else
2985        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2986    #endif
2987        return result.Produce();
2988    }
2989    
2990    String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {
2991        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
2992        LSCPResultSet result;
2993    #if HAVE_SQLITE3
2994        try {
2995            InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);
2996        } catch (Exception e) {
2997             result.Error(e);
2998        }
2999    #else
3000        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3001    #endif
3002        return result.Produce();
3003    }
3004    
3005    String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
3006        dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
3007        LSCPResultSet result;
3008    #if HAVE_SQLITE3
3009        try {
3010            int id;
3011            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
3012            id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
3013            if (bBackground) result = id;
3014        } catch (Exception e) {
3015             result.Error(e);
3016        }
3017    #else
3018        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3019    #endif
3020        return result.Produce();
3021    }
3022    
3023    String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground, bool insDir) {
3024        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));
3025        LSCPResultSet result;
3026    #if HAVE_SQLITE3
3027        try {
3028            int id;
3029            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
3030            if (ScanMode.compare("RECURSIVE") == 0) {
3031                id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground, insDir);
3032            } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
3033                id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground, insDir);
3034            } else if (ScanMode.compare("FLAT") == 0) {
3035                id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground, insDir);
3036            } else {
3037                throw Exception("Unknown scan mode: " + ScanMode);
3038            }
3039    
3040            if (bBackground) result = id;
3041        } catch (Exception e) {
3042             result.Error(e);
3043        }
3044    #else
3045        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3046    #endif
3047        return result.Produce();
3048    }
3049    
3050    String LSCPServer::RemoveDbInstrument(String Instr) {
3051        dmsg(2,("LSCPServer: RemoveDbInstrument(Instr=%s)\n", Instr.c_str()));
3052        LSCPResultSet result;
3053    #if HAVE_SQLITE3
3054        try {
3055            InstrumentsDb::GetInstrumentsDb()->RemoveInstrument(Instr);
3056        } catch (Exception e) {
3057             result.Error(e);
3058        }
3059    #else
3060        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3061    #endif
3062        return result.Produce();
3063    }
3064    
3065    String LSCPServer::GetDbInstrumentCount(String Dir, bool Recursive) {
3066        dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
3067        LSCPResultSet result;
3068    #if HAVE_SQLITE3
3069        try {
3070            result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir, Recursive));
3071        } catch (Exception e) {
3072             result.Error(e);
3073        }
3074    #else
3075        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3076    #endif
3077        return result.Produce();
3078    }
3079    
3080    String LSCPServer::GetDbInstruments(String Dir, bool Recursive) {
3081        dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
3082        LSCPResultSet result;
3083    #if HAVE_SQLITE3
3084        try {
3085            String list;
3086            StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir, Recursive);
3087    
3088            for (int i = 0; i < instrs->size(); i++) {
3089                if (list != "") list += ",";
3090                list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
3091            }
3092    
3093            result.Add(list);
3094        } catch (Exception e) {
3095             result.Error(e);
3096        }
3097    #else
3098        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3099    #endif
3100        return result.Produce();
3101    }
3102    
3103    String LSCPServer::GetDbInstrumentInfo(String Instr) {
3104        dmsg(2,("LSCPServer: GetDbInstrumentInfo(Instr=%s)\n", Instr.c_str()));
3105        LSCPResultSet result;
3106    #if HAVE_SQLITE3
3107        try {
3108            DbInstrument info = InstrumentsDb::GetInstrumentsDb()->GetInstrumentInfo(Instr);
3109    
3110            result.Add("INSTRUMENT_FILE", info.InstrFile);
3111            result.Add("INSTRUMENT_NR", info.InstrNr);
3112            result.Add("FORMAT_FAMILY", info.FormatFamily);
3113            result.Add("FORMAT_VERSION", info.FormatVersion);
3114            result.Add("SIZE", (int)info.Size);
3115            result.Add("CREATED", info.Created);
3116            result.Add("MODIFIED", info.Modified);
3117            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
3118            result.Add("IS_DRUM", info.IsDrum);
3119            result.Add("PRODUCT", _escapeLscpResponse(info.Product));
3120            result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
3121            result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
3122        } catch (Exception e) {
3123             result.Error(e);
3124        }
3125    #else
3126        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3127    #endif
3128        return result.Produce();
3129  }  }
3130    
3131  String LSCPServer::QueryDatabase(String query) {  String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
3132        dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
3133      LSCPResultSet result;      LSCPResultSet result;
3134  #if HAVE_SQLITE3  #if HAVE_SQLITE3
3135      char* zErrMsg = NULL;      try {
3136      sqlite3 *db;          ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
3137      String selectStr = "SELECT " + query;  
3138            result.Add("FILES_TOTAL", job.FilesTotal);
3139            result.Add("FILES_SCANNED", job.FilesScanned);
3140            result.Add("SCANNING", job.Scanning);
3141            result.Add("STATUS", job.Status);
3142        } catch (Exception e) {
3143             result.Error(e);
3144        }
3145    #else
3146        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3147    #endif
3148        return result.Produce();
3149    }
3150    
3151      int rc = sqlite3_open("linuxsampler.db", &db);  String LSCPServer::SetDbInstrumentName(String Instr, String Name) {
3152      if (rc == SQLITE_OK)      dmsg(2,("LSCPServer: SetDbInstrumentName(Instr=%s,Name=%s)\n", Instr.c_str(), Name.c_str()));
3153      {      LSCPResultSet result;
3154              rc = sqlite3_exec(db, selectStr.c_str(), select_callback, &result, &zErrMsg);  #if HAVE_SQLITE3
3155        try {
3156            InstrumentsDb::GetInstrumentsDb()->RenameInstrument(Instr, Name);
3157        } catch (Exception e) {
3158             result.Error(e);
3159      }      }
3160      if ( rc != SQLITE_OK )  #else
3161      {      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3162              result.Error(String(zErrMsg), rc);  #endif
3163        return result.Produce();
3164    }
3165    
3166    String LSCPServer::MoveDbInstrument(String Instr, String Dst) {
3167        dmsg(2,("LSCPServer: MoveDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3168        LSCPResultSet result;
3169    #if HAVE_SQLITE3
3170        try {
3171            InstrumentsDb::GetInstrumentsDb()->MoveInstrument(Instr, Dst);
3172        } catch (Exception e) {
3173             result.Error(e);
3174        }
3175    #else
3176        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3177    #endif
3178        return result.Produce();
3179    }
3180    
3181    String LSCPServer::CopyDbInstrument(String Instr, String Dst) {
3182        dmsg(2,("LSCPServer: CopyDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3183        LSCPResultSet result;
3184    #if HAVE_SQLITE3
3185        try {
3186            InstrumentsDb::GetInstrumentsDb()->CopyInstrument(Instr, Dst);
3187        } catch (Exception e) {
3188             result.Error(e);
3189      }      }
     sqlite3_close(db);  
3190  #else  #else
3191      result.Error(String("SQLITE3 was not installed when linuxsampler was built. SELECT statement is not available."), 0);      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3192  #endif  #endif
3193      return result.Produce();      return result.Produce();
3194  }  }
3195    
3196    String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {
3197        dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
3198        LSCPResultSet result;
3199    #if HAVE_SQLITE3
3200        try {
3201            InstrumentsDb::GetInstrumentsDb()->SetInstrumentDescription(Instr, Desc);
3202        } catch (Exception e) {
3203             result.Error(e);
3204        }
3205    #else
3206        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3207    #endif
3208        return result.Produce();
3209    }
3210    
3211    String LSCPServer::SetDbInstrumentFilePath(String OldPath, String NewPath) {
3212        dmsg(2,("LSCPServer: SetDbInstrumentFilePath(OldPath=%s,NewPath=%s)\n", OldPath.c_str(), NewPath.c_str()));
3213        LSCPResultSet result;
3214    #if HAVE_SQLITE3
3215        try {
3216            InstrumentsDb::GetInstrumentsDb()->SetInstrumentFilePath(OldPath, NewPath);
3217        } catch (Exception e) {
3218             result.Error(e);
3219        }
3220    #else
3221        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3222    #endif
3223        return result.Produce();
3224    }
3225    
3226    String LSCPServer::FindLostDbInstrumentFiles() {
3227        dmsg(2,("LSCPServer: FindLostDbInstrumentFiles()\n"));
3228        LSCPResultSet result;
3229    #if HAVE_SQLITE3
3230        try {
3231            String list;
3232            StringListPtr pLostFiles = InstrumentsDb::GetInstrumentsDb()->FindLostInstrumentFiles();
3233    
3234            for (int i = 0; i < pLostFiles->size(); i++) {
3235                if (list != "") list += ",";
3236                list += "'" + pLostFiles->at(i) + "'";
3237            }
3238    
3239            result.Add(list);
3240        } catch (Exception e) {
3241             result.Error(e);
3242        }
3243    #else
3244        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3245    #endif
3246        return result.Produce();
3247    }
3248    
3249    String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
3250        dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
3251        LSCPResultSet result;
3252    #if HAVE_SQLITE3
3253        try {
3254            SearchQuery Query;
3255            std::map<String,String>::iterator iter;
3256            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3257                if (iter->first.compare("NAME") == 0) {
3258                    Query.Name = iter->second;
3259                } else if (iter->first.compare("CREATED") == 0) {
3260                    Query.SetCreated(iter->second);
3261                } else if (iter->first.compare("MODIFIED") == 0) {
3262                    Query.SetModified(iter->second);
3263                } else if (iter->first.compare("DESCRIPTION") == 0) {
3264                    Query.Description = iter->second;
3265                } else {
3266                    throw Exception("Unknown search criteria: " + iter->first);
3267                }
3268            }
3269    
3270            String list;
3271            StringListPtr pDirectories =
3272                InstrumentsDb::GetInstrumentsDb()->FindDirectories(Dir, &Query, Recursive);
3273    
3274            for (int i = 0; i < pDirectories->size(); i++) {
3275                if (list != "") list += ",";
3276                list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
3277            }
3278    
3279            result.Add(list);
3280        } catch (Exception e) {
3281             result.Error(e);
3282        }
3283    #else
3284        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3285    #endif
3286        return result.Produce();
3287    }
3288    
3289    String LSCPServer::FindDbInstruments(String Dir, std::map<String,String> Parameters, bool Recursive) {
3290        dmsg(2,("LSCPServer: FindDbInstruments(Dir=%s)\n", Dir.c_str()));
3291        LSCPResultSet result;
3292    #if HAVE_SQLITE3
3293        try {
3294            SearchQuery Query;
3295            std::map<String,String>::iterator iter;
3296            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3297                if (iter->first.compare("NAME") == 0) {
3298                    Query.Name = iter->second;
3299                } else if (iter->first.compare("FORMAT_FAMILIES") == 0) {
3300                    Query.SetFormatFamilies(iter->second);
3301                } else if (iter->first.compare("SIZE") == 0) {
3302                    Query.SetSize(iter->second);
3303                } else if (iter->first.compare("CREATED") == 0) {
3304                    Query.SetCreated(iter->second);
3305                } else if (iter->first.compare("MODIFIED") == 0) {
3306                    Query.SetModified(iter->second);
3307                } else if (iter->first.compare("DESCRIPTION") == 0) {
3308                    Query.Description = iter->second;
3309                } else if (iter->first.compare("IS_DRUM") == 0) {
3310                    if (!strcasecmp(iter->second.c_str(), "true")) {
3311                        Query.InstrType = SearchQuery::DRUM;
3312                    } else {
3313                        Query.InstrType = SearchQuery::CHROMATIC;
3314                    }
3315                } else if (iter->first.compare("PRODUCT") == 0) {
3316                     Query.Product = iter->second;
3317                } else if (iter->first.compare("ARTISTS") == 0) {
3318                     Query.Artists = iter->second;
3319                } else if (iter->first.compare("KEYWORDS") == 0) {
3320                     Query.Keywords = iter->second;
3321                } else {
3322                    throw Exception("Unknown search criteria: " + iter->first);
3323                }
3324            }
3325    
3326            String list;
3327            StringListPtr pInstruments =
3328                InstrumentsDb::GetInstrumentsDb()->FindInstruments(Dir, &Query, Recursive);
3329    
3330            for (int i = 0; i < pInstruments->size(); i++) {
3331                if (list != "") list += ",";
3332                list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
3333            }
3334    
3335            result.Add(list);
3336        } catch (Exception e) {
3337             result.Error(e);
3338        }
3339    #else
3340        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3341    #endif
3342        return result.Produce();
3343    }
3344    
3345    String LSCPServer::FormatInstrumentsDb() {
3346        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3347        LSCPResultSet result;
3348    #if HAVE_SQLITE3
3349        try {
3350            InstrumentsDb::GetInstrumentsDb()->Format();
3351        } catch (Exception e) {
3352             result.Error(e);
3353        }
3354    #else
3355        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3356    #endif
3357        return result.Produce();
3358    }
3359    
3360    
3361  /**  /**
3362   * 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
3363   * mode is enabled, all commands from the client will (immediately) be   * mode is enabled, all commands from the client will (immediately) be
# Line 2003  String LSCPServer::SetEcho(yyparse_param Line 3376  String LSCPServer::SetEcho(yyparse_param
3376      }      }
3377      return result.Produce();      return result.Produce();
3378  }  }
3379    
3380    }

Legend:
Removed from v.981  
changed lines
  Added in v.1835

  ViewVC Help
Powered by ViewVC