/[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 1047 by schoenebeck, Mon Feb 19 19:38:04 2007 UTC revision 1850 by persson, Sun Mar 1 16:33:22 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 - 2007 Christian Schoenebeck                       *   *   Copyright (C) 2005 - 2009 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        CloseAllConnections();
145        InstrumentManager::StopBackgroundThread();
146    #if defined(WIN32)
147        if (hSocket >= 0) closesocket(hSocket);
148    #else
149      if (hSocket >= 0) close(hSocket);      if (hSocket >= 0) close(hSocket);
150    #endif
151    }
152    
153    LSCPServer::EventHandler::EventHandler(LSCPServer* pParent) {
154        this->pParent = pParent;
155    }
156    
157    LSCPServer::EventHandler::~EventHandler() {
158        std::vector<midi_listener_entry> l = channelMidiListeners;
159        channelMidiListeners.clear();
160        for (int i = 0; i < l.size(); i++)
161            delete l[i].pMidiListener;
162    }
163    
164    void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
165        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
166    }
167    
168    void LSCPServer::EventHandler::ChannelAdded(SamplerChannel* pChannel) {
169        pChannel->AddEngineChangeListener(this);
170    }
171    
172    void LSCPServer::EventHandler::ChannelToBeRemoved(SamplerChannel* pChannel) {
173        if (!pChannel->GetEngineChannel()) return;
174        EngineToBeChanged(pChannel->Index());
175    }
176    
177    void LSCPServer::EventHandler::EngineToBeChanged(int ChannelId) {
178        SamplerChannel* pSamplerChannel =
179            pParent->pSampler->GetSamplerChannel(ChannelId);
180        if (!pSamplerChannel) return;
181        EngineChannel* pEngineChannel =
182            pSamplerChannel->GetEngineChannel();
183        if (!pEngineChannel) return;
184        for (std::vector<midi_listener_entry>::iterator iter = channelMidiListeners.begin(); iter != channelMidiListeners.end(); ++iter) {
185            if ((*iter).pEngineChannel == pEngineChannel) {
186                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
187                pEngineChannel->Disconnect(pMidiListener);
188                channelMidiListeners.erase(iter);
189                delete pMidiListener;
190                return;
191            }
192        }
193    }
194    
195    void LSCPServer::EventHandler::EngineChanged(int ChannelId) {
196        SamplerChannel* pSamplerChannel =
197            pParent->pSampler->GetSamplerChannel(ChannelId);
198        if (!pSamplerChannel) return;
199        EngineChannel* pEngineChannel =
200            pSamplerChannel->GetEngineChannel();
201        if (!pEngineChannel) return;
202        VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
203        pEngineChannel->Connect(pMidiListener);
204        midi_listener_entry entry = {
205            pSamplerChannel, pEngineChannel, pMidiListener
206        };
207        channelMidiListeners.push_back(entry);
208    }
209    
210    void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
211        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
212    }
213    
214    void LSCPServer::EventHandler::MidiDeviceCountChanged(int NewCount) {
215        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));
216    }
217    
218    void LSCPServer::EventHandler::MidiDeviceToBeDestroyed(MidiInputDevice* pDevice) {
219        pDevice->RemoveMidiPortCountListener(this);
220        for (int i = 0; i < pDevice->PortCount(); ++i)
221            MidiPortToBeRemoved(pDevice->GetPort(i));
222    }
223    
224    void LSCPServer::EventHandler::MidiDeviceCreated(MidiInputDevice* pDevice) {
225        pDevice->AddMidiPortCountListener(this);
226        for (int i = 0; i < pDevice->PortCount(); ++i)
227            MidiPortAdded(pDevice->GetPort(i));
228    }
229    
230    void LSCPServer::EventHandler::MidiPortCountChanged(int NewCount) {
231        // yet unused
232    }
233    
234    void LSCPServer::EventHandler::MidiPortToBeRemoved(MidiInputPort* pPort) {
235        for (std::vector<device_midi_listener_entry>::iterator iter = deviceMidiListeners.begin(); iter != deviceMidiListeners.end(); ++iter) {
236            if ((*iter).pPort == pPort) {
237                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
238                pPort->Disconnect(pMidiListener);
239                deviceMidiListeners.erase(iter);
240                delete pMidiListener;
241                return;
242            }
243        }
244    }
245    
246    void LSCPServer::EventHandler::MidiPortAdded(MidiInputPort* pPort) {
247        // find out the device ID
248        std::map<uint, MidiInputDevice*> devices =
249            pParent->pSampler->GetMidiInputDevices();
250        for (
251            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
252            iter != devices.end(); ++iter
253        ) {
254            if (iter->second == pPort->GetDevice()) { // found
255                VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
256                pPort->Connect(pMidiListener);
257                device_midi_listener_entry entry = {
258                    pPort, pMidiListener, iter->first
259                };
260                deviceMidiListeners.push_back(entry);
261                return;
262            }
263        }
264    }
265    
266    void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {
267        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));
268    }
269    
270    void LSCPServer::EventHandler::MidiInstrumentInfoChanged(int MapId, int Bank, int Program) {
271        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_info, MapId, Bank, Program));
272    }
273    
274    void LSCPServer::EventHandler::MidiInstrumentMapCountChanged(int NewCount) {
275        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_count, NewCount));
276    }
277    
278    void LSCPServer::EventHandler::MidiInstrumentMapInfoChanged(int MapId) {
279        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_info, MapId));
280    }
281    
282    void LSCPServer::EventHandler::FxSendCountChanged(int ChannelId, int NewCount) {
283        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_count, ChannelId, NewCount));
284    }
285    
286    void LSCPServer::EventHandler::VoiceCountChanged(int ChannelId, int NewCount) {
287        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_voice_count, ChannelId, NewCount));
288    }
289    
290    void LSCPServer::EventHandler::StreamCountChanged(int ChannelId, int NewCount) {
291        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_stream_count, ChannelId, NewCount));
292    }
293    
294    void LSCPServer::EventHandler::BufferFillChanged(int ChannelId, String FillData) {
295        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_buffer_fill, ChannelId, FillData));
296    }
297    
298    void LSCPServer::EventHandler::TotalVoiceCountChanged(int NewCount) {
299        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
300    }
301    
302    void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
303        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
304    }
305    
306    #if HAVE_SQLITE3
307    void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
308        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
309    }
310    
311    void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {
312        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, InstrumentsDb::toEscapedPath(Dir)));
313    }
314    
315    void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {
316        Dir = "'" + InstrumentsDb::toEscapedPath(Dir) + "'";
317        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
318        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));
319    }
320    
321    void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {
322        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, InstrumentsDb::toEscapedPath(Dir)));
323    }
324    
325    void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {
326        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, InstrumentsDb::toEscapedPath(Instr)));
327    }
328    
329    void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {
330        Instr = "'" + InstrumentsDb::toEscapedPath(Instr) + "'";
331        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
332        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));
333    }
334    
335    void LSCPServer::DbInstrumentsEventHandler::JobStatusChanged(int JobId) {
336        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instrs_job_info, JobId));
337    }
338    #endif // HAVE_SQLITE3
339    
340    void LSCPServer::RemoveListeners() {
341        pSampler->RemoveChannelCountListener(&eventHandler);
342        pSampler->RemoveAudioDeviceCountListener(&eventHandler);
343        pSampler->RemoveMidiDeviceCountListener(&eventHandler);
344        pSampler->RemoveVoiceCountListener(&eventHandler);
345        pSampler->RemoveStreamCountListener(&eventHandler);
346        pSampler->RemoveBufferFillListener(&eventHandler);
347        pSampler->RemoveTotalStreamCountListener(&eventHandler);
348        pSampler->RemoveTotalVoiceCountListener(&eventHandler);
349        pSampler->RemoveFxSendCountListener(&eventHandler);
350        MidiInstrumentMapper::RemoveMidiInstrumentCountListener(&eventHandler);
351        MidiInstrumentMapper::RemoveMidiInstrumentInfoListener(&eventHandler);
352        MidiInstrumentMapper::RemoveMidiInstrumentMapCountListener(&eventHandler);
353        MidiInstrumentMapper::RemoveMidiInstrumentMapInfoListener(&eventHandler);
354    #if HAVE_SQLITE3
355        InstrumentsDb::GetInstrumentsDb()->RemoveInstrumentsDbListener(&dbInstrumentsEventHandler);
356    #endif
357  }  }
358    
359  /**  /**
# Line 103  int LSCPServer::WaitUntilInitialized(lon Line 371  int LSCPServer::WaitUntilInitialized(lon
371  }  }
372    
373  int LSCPServer::Main() {  int LSCPServer::Main() {
374            #if defined(WIN32)
375            WSADATA wsaData;
376            int iResult;
377            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
378            if (iResult != 0) {
379                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
380                    exit(EXIT_FAILURE);
381            }
382            #endif
383      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
384      if (hSocket < 0) {      if (hSocket < 0) {
385          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 393  int LSCPServer::Main() {
393              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
394                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
395                      std::cerr << "gave up!" << std::endl;                      std::cerr << "gave up!" << std::endl;
396                        #if defined(WIN32)
397                        closesocket(hSocket);
398                        #else
399                      close(hSocket);                      close(hSocket);
400                        #endif
401                      //return -1;                      //return -1;
402                      exit(EXIT_FAILURE);                      exit(EXIT_FAILURE);
403                  }                  }
# Line 129  int LSCPServer::Main() { Line 410  int LSCPServer::Main() {
410      listen(hSocket, 1);      listen(hSocket, 1);
411      Initialized.Set(true);      Initialized.Set(true);
412    
413        // Registering event listeners
414        pSampler->AddChannelCountListener(&eventHandler);
415        pSampler->AddAudioDeviceCountListener(&eventHandler);
416        pSampler->AddMidiDeviceCountListener(&eventHandler);
417        pSampler->AddVoiceCountListener(&eventHandler);
418        pSampler->AddStreamCountListener(&eventHandler);
419        pSampler->AddBufferFillListener(&eventHandler);
420        pSampler->AddTotalStreamCountListener(&eventHandler);
421        pSampler->AddTotalVoiceCountListener(&eventHandler);
422        pSampler->AddFxSendCountListener(&eventHandler);
423        MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
424        MidiInstrumentMapper::AddMidiInstrumentInfoListener(&eventHandler);
425        MidiInstrumentMapper::AddMidiInstrumentMapCountListener(&eventHandler);
426        MidiInstrumentMapper::AddMidiInstrumentMapInfoListener(&eventHandler);
427    #if HAVE_SQLITE3
428        InstrumentsDb::GetInstrumentsDb()->AddInstrumentsDbListener(&dbInstrumentsEventHandler);
429    #endif
430      // now wait for client connections and handle their requests      // now wait for client connections and handle their requests
431      sockaddr_in client;      sockaddr_in client;
432      int length = sizeof(client);      int length = sizeof(client);
# Line 139  int LSCPServer::Main() { Line 437  int LSCPServer::Main() {
437      timeval timeout;      timeval timeout;
438    
439      while (true) {      while (true) {
440            #if CONFIG_PTHREAD_TESTCANCEL
441                    TestCancel();
442            #endif
443          // 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
444          {          {
445              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
# Line 146  int LSCPServer::Main() { Line 447  int LSCPServer::Main() {
447              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();              std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
448              for (; itEngineChannel != itEnd; ++itEngineChannel) {              for (; itEngineChannel != itEnd; ++itEngineChannel) {
449                  if ((*itEngineChannel)->StatusChanged()) {                  if ((*itEngineChannel)->StatusChanged()) {
450                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->iSamplerChannelIndex));                      SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->GetSamplerChannel()->Index()));
451                    }
452    
453                    for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
454                        FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
455                        if(fxs != NULL && fxs->IsInfoChanged()) {
456                            int chn = (*itEngineChannel)->GetSamplerChannel()->Index();
457                            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
458                            fxs->SetInfoChanged(false);
459                        }
460                    }
461                }
462            }
463    
464            // check if MIDI data arrived on some engine channel
465            for (int i = 0; i < eventHandler.channelMidiListeners.size(); ++i) {
466                const EventHandler::midi_listener_entry entry =
467                    eventHandler.channelMidiListeners[i];
468                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
469                if (pMidiListener->NotesChanged()) {
470                    for (int iNote = 0; iNote < 128; iNote++) {
471                        if (pMidiListener->NoteChanged(iNote)) {
472                            const bool bActive = pMidiListener->NoteIsActive(iNote);
473                            LSCPServer::SendLSCPNotify(
474                                LSCPEvent(
475                                    LSCPEvent::event_channel_midi,
476                                    entry.pSamplerChannel->Index(),
477                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
478                                    iNote,
479                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
480                                            : pMidiListener->NoteOffVelocity(iNote)
481                                )
482                            );
483                        }
484                    }
485                }
486            }
487    
488            // check if MIDI data arrived on some MIDI device
489            for (int i = 0; i < eventHandler.deviceMidiListeners.size(); ++i) {
490                const EventHandler::device_midi_listener_entry entry =
491                    eventHandler.deviceMidiListeners[i];
492                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
493                if (pMidiListener->NotesChanged()) {
494                    for (int iNote = 0; iNote < 128; iNote++) {
495                        if (pMidiListener->NoteChanged(iNote)) {
496                            const bool bActive = pMidiListener->NoteIsActive(iNote);
497                            LSCPServer::SendLSCPNotify(
498                                LSCPEvent(
499                                    LSCPEvent::event_device_midi,
500                                    entry.uiDeviceID,
501                                    entry.pPort->GetPortNumber(),
502                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
503                                    iNote,
504                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
505                                            : pMidiListener->NoteOffVelocity(iNote)
506                                )
507                            );
508                        }
509                  }                  }
510              }              }
511          }          }
# Line 169  int LSCPServer::Main() { Line 528  int LSCPServer::Main() {
528    
529          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);          int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);
530    
531          if (retval == 0)          if (retval == 0 || (retval == -1 && errno == EINTR))
532                  continue; //Nothing try again                  continue; //Nothing try again
533          if (retval == -1) {          if (retval == -1) {
534                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
535                    #if defined(WIN32)
536                    closesocket(hSocket);
537                    #else
538                  close(hSocket);                  close(hSocket);
539                    #endif
540                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
541          }          }
542    
# Line 185  int LSCPServer::Main() { Line 548  int LSCPServer::Main() {
548                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
549                  }                  }
550    
551                    #if defined(WIN32)
552                    u_long nonblock_io = 1;
553                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
554                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
555                      exit(EXIT_FAILURE);
556                    }
557            #else
558                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
559                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
560                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
561                  }                  }
562                    #endif
563    
564                  // Parser initialization                  // Parser initialization
565                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 212  int LSCPServer::Main() { Line 583  int LSCPServer::Main() {
583                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
584                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
585                                  currentSocket = (*iter).hSession;  //a hack                                  currentSocket = (*iter).hSession;  //a hack
586                                    itCurrentSession = iter; // another hack
587                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));                                  dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
588                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
589                                      AnswerClient(bufferedCommands[currentSocket]);                                      AnswerClient(bufferedCommands[currentSocket]);
590                                  }                                  }
591                                  int result = yyparse(&(*iter));                                  int result = yyparse(&(*iter));
592                                  currentSocket = -1;     //continuation of a hack                                  currentSocket = -1;     //continuation of a hack
593                                    itCurrentSession = Sessions.end(); // hack as well
594                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
595                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?
596                                          CloseConnection(iter);                                          CloseConnection(iter);
# Line 245  void LSCPServer::CloseConnection( std::v Line 618  void LSCPServer::CloseConnection( std::v
618          NotifyMutex.Lock();          NotifyMutex.Lock();
619          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
620          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
621            #if defined(WIN32)
622            closesocket(socket);
623            #else
624          close(socket);          close(socket);
625            #endif
626          NotifyMutex.Unlock();          NotifyMutex.Unlock();
627  }  }
628    
629    void LSCPServer::CloseAllConnections() {
630        std::vector<yyparse_param_t>::iterator iter = Sessions.begin();
631        while(iter != Sessions.end()) {
632            CloseConnection(iter);
633            iter = Sessions.begin();
634        }
635    }
636    
637    void LSCPServer::LockRTNotify() {
638        RTNotifyMutex.Lock();
639    }
640    
641    void LSCPServer::UnlockRTNotify() {
642        RTNotifyMutex.Unlock();
643    }
644    
645  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
646          int subs = 0;          int subs = 0;
647          SubscriptionMutex.Lock();          SubscriptionMutex.Lock();
# Line 310  extern int GetLSCPCommand( void *buf, in Line 703  extern int GetLSCPCommand( void *buf, in
703          return command.size();          return command.size();
704  }  }
705    
706    extern yyparse_param_t* GetCurrentYaccSession() {
707        return &(*itCurrentSession);
708    }
709    
710  /**  /**
711   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
712   * 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 717  bool LSCPServer::GetLSCPCommand( std::ve
717          char c;          char c;
718          int i = 0;          int i = 0;
719          while (true) {          while (true) {
720                    #if defined(WIN32)
721                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
722                    #else
723                  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
724                    #endif
725                  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
726                          CloseConnection(iter);                          CloseConnection(iter);
727                          break;                          break;
# Line 335  bool LSCPServer::GetLSCPCommand( std::ve Line 736  bool LSCPServer::GetLSCPCommand( std::ve
736                          }                          }
737                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
738                  }                  }
739                    #if defined(WIN32)
740                    if (result == SOCKET_ERROR) {
741                        int wsa_lasterror = WSAGetLastError();
742                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
743                                    return false;
744                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
745                            CloseConnection(iter);
746                            break;
747                    }
748                    #else
749                  if (result == -1) {                  if (result == -1) {
750                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
751                                  return false;                                  return false;
# Line 373  bool LSCPServer::GetLSCPCommand( std::ve Line 784  bool LSCPServer::GetLSCPCommand( std::ve
784                          CloseConnection(iter);                          CloseConnection(iter);
785                          break;                          break;
786                  }                  }
787                    #endif
788          }          }
789          return false;          return false;
790  }  }
# Line 490  String LSCPServer::DestroyMidiInputDevic Line 902  String LSCPServer::DestroyMidiInputDevic
902      return result.Produce();      return result.Produce();
903  }  }
904    
905    EngineChannel* LSCPServer::GetEngineChannel(uint uiSamplerChannel) {
906        SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
907        if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
908    
909        EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
910        if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
911    
912        return pEngineChannel;
913    }
914    
915  /**  /**
916   * Will be called by the parser to load an instrument.   * Will be called by the parser to load an instrument.
917   */   */
# Line 636  String LSCPServer::GetEngineInfo(String Line 1058  String LSCPServer::GetEngineInfo(String
1058      LockRTNotify();      LockRTNotify();
1059      try {      try {
1060          Engine* pEngine = EngineFactory::Create(EngineName);          Engine* pEngine = EngineFactory::Create(EngineName);
1061          result.Add("DESCRIPTION", pEngine->Description());          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
1062          result.Add("VERSION",     pEngine->Version());          result.Add("VERSION",     pEngine->Version());
1063          EngineFactory::Destroy(pEngine);          EngineFactory::Destroy(pEngine);
1064      }      }
# Line 670  String LSCPServer::GetChannelInfo(uint u Line 1092  String LSCPServer::GetChannelInfo(uint u
1092          String AudioRouting;          String AudioRouting;
1093          int Mute = 0;          int Mute = 0;
1094          bool Solo = false;          bool Solo = false;
1095          String MidiInstrumentMap;          String MidiInstrumentMap = "NONE";
1096    
1097          if (pEngineChannel) {          if (pEngineChannel) {
1098              EngineName          = pEngineChannel->EngineName();              EngineName          = pEngineChannel->EngineName();
# Line 709  String LSCPServer::GetChannelInfo(uint u Line 1131  String LSCPServer::GetChannelInfo(uint u
1131          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
1132          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
1133    
1134            // convert the filename into the correct encoding as defined for LSCP
1135            // (especially in terms of special characters -> escape sequences)
1136            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
1137    #if WIN32
1138                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
1139    #else
1140                // assuming POSIX
1141                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
1142    #endif
1143            }
1144    
1145          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
1146          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
1147          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
1148          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
1149          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));          result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
1150          result.Add("SOLO", Solo);          result.Add("SOLO", Solo);
# Line 731  String LSCPServer::GetVoiceCount(uint ui Line 1164  String LSCPServer::GetVoiceCount(uint ui
1164      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));
1165      LSCPResultSet result;      LSCPResultSet result;
1166      try {      try {
1167          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");  
1168          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");
1169          result.Add(pEngineChannel->GetEngine()->VoiceCount());          result.Add(pEngineChannel->GetEngine()->VoiceCount());
1170      }      }
# Line 752  String LSCPServer::GetStreamCount(uint u Line 1182  String LSCPServer::GetStreamCount(uint u
1182      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));
1183      LSCPResultSet result;      LSCPResultSet result;
1184      try {      try {
1185          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");  
1186          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");
1187          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());
1188      }      }
# Line 773  String LSCPServer::GetBufferFill(fill_re Line 1200  String LSCPServer::GetBufferFill(fill_re
1200      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));
1201      LSCPResultSet result;      LSCPResultSet result;
1202      try {      try {
1203          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");  
1204          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");
1205          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");
1206          else {          else {
# Line 864  String LSCPServer::GetMidiInputDriverInf Line 1288  String LSCPServer::GetMidiInputDriverInf
1288              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1289                  if (s != "") s += ",";                  if (s != "") s += ",";
1290                  s += iter->first;                  s += iter->first;
1291                    delete iter->second;
1292              }              }
1293              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1294          }          }
# Line 888  String LSCPServer::GetAudioOutputDriverI Line 1313  String LSCPServer::GetAudioOutputDriverI
1313              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1314                  if (s != "") s += ",";                  if (s != "") s += ",";
1315                  s += iter->first;                  s += iter->first;
1316                    delete iter->second;
1317              }              }
1318              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1319          }          }
# Line 918  String LSCPServer::GetMidiInputDriverPar Line 1344  String LSCPServer::GetMidiInputDriverPar
1344          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1345          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1346          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1347            delete pParameter;
1348      }      }
1349      catch (Exception e) {      catch (Exception e) {
1350          result.Error(e);          result.Error(e);
# Line 945  String LSCPServer::GetAudioOutputDriverP Line 1372  String LSCPServer::GetAudioOutputDriverP
1372          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1373          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1374          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1375            delete pParameter;
1376      }      }
1377      catch (Exception e) {      catch (Exception e) {
1378          result.Error(e);          result.Error(e);
# Line 1454  String LSCPServer::SetVolume(double dVol Line 1882  String LSCPServer::SetVolume(double dVol
1882      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));
1883      LSCPResultSet result;      LSCPResultSet result;
1884      try {      try {
1885          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");  
1886          pEngineChannel->Volume(dVolume);          pEngineChannel->Volume(dVolume);
1887      }      }
1888      catch (Exception e) {      catch (Exception e) {
# Line 1473  String LSCPServer::SetChannelMute(bool b Line 1898  String LSCPServer::SetChannelMute(bool b
1898      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));
1899      LSCPResultSet result;      LSCPResultSet result;
1900      try {      try {
1901          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");  
1902    
1903          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);          if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);
1904          else pEngineChannel->SetMute(1);          else pEngineChannel->SetMute(1);
# Line 1494  String LSCPServer::SetChannelSolo(bool b Line 1915  String LSCPServer::SetChannelSolo(bool b
1915      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));      dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));
1916      LSCPResultSet result;      LSCPResultSet result;
1917      try {      try {
1918          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");  
1919    
1920          bool oldSolo = pEngineChannel->GetSolo();          bool oldSolo = pEngineChannel->GetSolo();
1921          bool hadSoloChannel = HasSoloChannel();          bool hadSoloChannel = HasSoloChannel();
# Line 1618  String LSCPServer::GetMidiInstrumentMapp Line 2035  String LSCPServer::GetMidiInstrumentMapp
2035      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));
2036      LSCPResultSet result;      LSCPResultSet result;
2037      try {      try {
2038          result.Add(MidiInstrumentMapper::Entries(MidiMapID).size());          result.Add(MidiInstrumentMapper::GetInstrumentCount(MidiMapID));
2039      } catch (Exception e) {      } catch (Exception e) {
2040          result.Error(e);          result.Error(e);
2041      }      }
# Line 1629  String LSCPServer::GetMidiInstrumentMapp Line 2046  String LSCPServer::GetMidiInstrumentMapp
2046  String LSCPServer::GetAllMidiInstrumentMappings() {  String LSCPServer::GetAllMidiInstrumentMappings() {
2047      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));      dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));
2048      LSCPResultSet result;      LSCPResultSet result;
2049      std::vector<int> maps = MidiInstrumentMapper::Maps();      try {
2050      int totalMappings = 0;          result.Add(MidiInstrumentMapper::GetInstrumentCount());
2051      for (int i = 0; i < maps.size(); i++) {      } catch (Exception e) {
2052          try {          result.Error(e);
             totalMappings += MidiInstrumentMapper::Entries(maps[i]).size();  
         } catch (Exception e) { /*NOOP*/ }  
2053      }      }
     result.Add(totalMappings);  
2054      return result.Produce();      return result.Produce();
2055  }  }
2056    
# Line 1644  String LSCPServer::GetMidiInstrumentMapp Line 2058  String LSCPServer::GetMidiInstrumentMapp
2058      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));      dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));
2059      LSCPResultSet result;      LSCPResultSet result;
2060      try {      try {
2061          midi_prog_index_t idx;          MidiInstrumentMapper::entry_t entry = MidiInstrumentMapper::GetEntry(MidiMapID, MidiBank, MidiProg);
2062          idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;          // convert the filename into the correct encoding as defined for LSCP
2063          idx.midi_bank_lsb = MidiBank & 0x7f;          // (especially in terms of special characters -> escape sequences)
2064          idx.midi_prog     = MidiProg;  #if WIN32
2065            const String instrumentFileName = Path::fromWindows(entry.InstrumentFile).toLscp();
2066    #else
2067            // assuming POSIX
2068            const String instrumentFileName = Path::fromPosix(entry.InstrumentFile).toLscp();
2069    #endif
2070    
2071          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(MidiMapID);          result.Add("NAME", _escapeLscpResponse(entry.Name));
2072          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);          result.Add("ENGINE_NAME", entry.EngineName);
2073          if (iter == mappings.end()) result.Error("there is no map entry with that index");          result.Add("INSTRUMENT_FILE", instrumentFileName);
2074          else { // found          result.Add("INSTRUMENT_NR", (int) entry.InstrumentIndex);
2075              result.Add("NAME", iter->second.Name);          String instrumentName;
2076              result.Add("ENGINE_NAME", iter->second.EngineName);          Engine* pEngine = EngineFactory::Create(entry.EngineName);
2077              result.Add("INSTRUMENT_FILE", iter->second.InstrumentFile);          if (pEngine) {
2078              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);              if (pEngine->GetInstrumentManager()) {
2079              String instrumentName;                  InstrumentManager::instrument_id_t instrID;
2080              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);                  instrID.FileName = entry.InstrumentFile;
2081              if (pEngine) {                  instrID.Index    = entry.InstrumentIndex;
2082                  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);  
             }  
             result.Add("INSTRUMENT_NAME", instrumentName);  
             switch (iter->second.LoadMode) {  
                 case MidiInstrumentMapper::ON_DEMAND:  
                     result.Add("LOAD_MODE", "ON_DEMAND");  
                     break;  
                 case MidiInstrumentMapper::ON_DEMAND_HOLD:  
                     result.Add("LOAD_MODE", "ON_DEMAND_HOLD");  
                     break;  
                 case MidiInstrumentMapper::PERSISTENT:  
                     result.Add("LOAD_MODE", "PERSISTENT");  
                     break;  
                 default:  
                     throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");  
2083              }              }
2084              result.Add("VOLUME", iter->second.Volume);              EngineFactory::Destroy(pEngine);
2085            }
2086            result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
2087            switch (entry.LoadMode) {
2088                case MidiInstrumentMapper::ON_DEMAND:
2089                    result.Add("LOAD_MODE", "ON_DEMAND");
2090                    break;
2091                case MidiInstrumentMapper::ON_DEMAND_HOLD:
2092                    result.Add("LOAD_MODE", "ON_DEMAND_HOLD");
2093                    break;
2094                case MidiInstrumentMapper::PERSISTENT:
2095                    result.Add("LOAD_MODE", "PERSISTENT");
2096                    break;
2097                default:
2098                    throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");
2099          }          }
2100            result.Add("VOLUME", entry.Volume);
2101      } catch (Exception e) {      } catch (Exception e) {
2102          result.Error(e);          result.Error(e);
2103      }      }
# Line 1823  String LSCPServer::GetMidiInstrumentMap( Line 2237  String LSCPServer::GetMidiInstrumentMap(
2237      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));      dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2238      LSCPResultSet result;      LSCPResultSet result;
2239      try {      try {
2240          result.Add("NAME", MidiInstrumentMapper::MapName(MidiMapID));          result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2241            result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2242      } catch (Exception e) {      } catch (Exception e) {
2243          result.Error(e);          result.Error(e);
2244      }      }
# Line 1853  String LSCPServer::SetChannelMap(uint ui Line 2268  String LSCPServer::SetChannelMap(uint ui
2268      dmsg(2,("LSCPServer: SetChannelMap()\n"));      dmsg(2,("LSCPServer: SetChannelMap()\n"));
2269      LSCPResultSet result;      LSCPResultSet result;
2270      try {      try {
2271          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");  
2272    
2273          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();          if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();
2274          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();          else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();
# Line 1872  String LSCPServer::CreateFxSend(uint uiS Line 2283  String LSCPServer::CreateFxSend(uint uiS
2283      dmsg(2,("LSCPServer: CreateFxSend()\n"));      dmsg(2,("LSCPServer: CreateFxSend()\n"));
2284      LSCPResultSet result;      LSCPResultSet result;
2285      try {      try {
2286          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");  
2287    
2288          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);          FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2289          if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");          if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");
# Line 1892  String LSCPServer::DestroyFxSend(uint ui Line 2299  String LSCPServer::DestroyFxSend(uint ui
2299      dmsg(2,("LSCPServer: DestroyFxSend()\n"));      dmsg(2,("LSCPServer: DestroyFxSend()\n"));
2300      LSCPResultSet result;      LSCPResultSet result;
2301      try {      try {
2302          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");  
2303    
2304          FxSend* pFxSend = NULL;          FxSend* pFxSend = NULL;
2305          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
# Line 1917  String LSCPServer::GetFxSends(uint uiSam Line 2320  String LSCPServer::GetFxSends(uint uiSam
2320      dmsg(2,("LSCPServer: GetFxSends()\n"));      dmsg(2,("LSCPServer: GetFxSends()\n"));
2321      LSCPResultSet result;      LSCPResultSet result;
2322      try {      try {
2323          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");  
2324    
2325          result.Add(pEngineChannel->GetFxSendCount());          result.Add(pEngineChannel->GetFxSendCount());
2326      } catch (Exception e) {      } catch (Exception e) {
# Line 1935  String LSCPServer::ListFxSends(uint uiSa Line 2334  String LSCPServer::ListFxSends(uint uiSa
2334      LSCPResultSet result;      LSCPResultSet result;
2335      String list;      String list;
2336      try {      try {
2337          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");  
2338    
2339          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2340              FxSend* pFxSend = pEngineChannel->GetFxSend(i);              FxSend* pFxSend = pEngineChannel->GetFxSend(i);
# Line 1953  String LSCPServer::ListFxSends(uint uiSa Line 2348  String LSCPServer::ListFxSends(uint uiSa
2348      return result.Produce();      return result.Produce();
2349  }  }
2350    
2351    FxSend* LSCPServer::GetFxSend(uint uiSamplerChannel, uint FxSendID) {
2352        EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2353    
2354        FxSend* pFxSend = NULL;
2355        for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2356            if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2357                pFxSend = pEngineChannel->GetFxSend(i);
2358                break;
2359            }
2360        }
2361        if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2362        return pFxSend;
2363    }
2364    
2365  String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {  String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {
2366      dmsg(2,("LSCPServer: GetFxSendInfo()\n"));      dmsg(2,("LSCPServer: GetFxSendInfo()\n"));
2367      LSCPResultSet result;      LSCPResultSet result;
2368      try {      try {
2369          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2370          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");  
   
         FxSend* pFxSend = NULL;  
         for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {  
             if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {  
                 pFxSend = pEngineChannel->GetFxSend(i);  
                 break;  
             }  
         }  
         if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");  
2371    
2372          // gather audio routing informations          // gather audio routing informations
2373          String AudioRouting;          String AudioRouting;
# Line 1980  String LSCPServer::GetFxSendInfo(uint ui Line 2377  String LSCPServer::GetFxSendInfo(uint ui
2377          }          }
2378    
2379          // success          // success
2380          result.Add("NAME", pFxSend->Name());          result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2381          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());          result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2382          result.Add("LEVEL", ToString(pFxSend->Level()));          result.Add("LEVEL", ToString(pFxSend->Level()));
2383          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
# Line 1990  String LSCPServer::GetFxSendInfo(uint ui Line 2387  String LSCPServer::GetFxSendInfo(uint ui
2387      return result.Produce();      return result.Produce();
2388  }  }
2389    
2390  String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {  String LSCPServer::SetFxSendName(uint uiSamplerChannel, uint FxSendID, String Name) {
2391      dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));      dmsg(2,("LSCPServer: SetFxSendName()\n"));
2392      LSCPResultSet result;      LSCPResultSet result;
2393      try {      try {
2394          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
2395    
2396          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();          pFxSend->SetName(Name);
2397          if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2398        } catch (Exception e) {
2399            result.Error(e);
2400        }
2401        return result.Produce();
2402    }
2403    
2404          FxSend* pFxSend = NULL;  String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {
2405          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {      dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));
2406              if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {      LSCPResultSet result;
2407                  pFxSend = pEngineChannel->GetFxSend(i);      try {
2408                  break;          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
             }  
         }  
         if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");  
2409    
2410          pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);          pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);
2411            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2412      } catch (Exception e) {      } catch (Exception e) {
2413          result.Error(e);          result.Error(e);
2414      }      }
# Line 2020  String LSCPServer::SetFxSendMidiControll Line 2419  String LSCPServer::SetFxSendMidiControll
2419      dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));      dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));
2420      LSCPResultSet result;      LSCPResultSet result;
2421      try {      try {
2422          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
   
         EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();  
         if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");  
   
         FxSend* pFxSend = NULL;  
         for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {  
             if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {  
                 pFxSend = pEngineChannel->GetFxSend(i);  
                 break;  
             }  
         }  
         if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");  
2423    
2424          pFxSend->SetMidiController(MidiController);          pFxSend->SetMidiController(MidiController);
2425            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2426      } catch (Exception e) {      } catch (Exception e) {
2427          result.Error(e);          result.Error(e);
2428      }      }
# Line 2046  String LSCPServer::SetFxSendLevel(uint u Line 2433  String LSCPServer::SetFxSendLevel(uint u
2433      dmsg(2,("LSCPServer: SetFxSendLevel()\n"));      dmsg(2,("LSCPServer: SetFxSendLevel()\n"));
2434      LSCPResultSet result;      LSCPResultSet result;
2435      try {      try {
2436          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
         if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));  
2437    
2438          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();          pFxSend->SetLevel((float)dLevel);
2439          if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2440        } catch (Exception e) {
2441            result.Error(e);
2442        }
2443        return result.Produce();
2444    }
2445    
2446          FxSend* pFxSend = NULL;  String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2447          for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {      dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2448              if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {      LSCPResultSet result;
2449                  pFxSend = pEngineChannel->GetFxSend(i);      try {
2450            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2451            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2452            Engine* pEngine = pEngineChannel->GetEngine();
2453            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2454            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2455            InstrumentManager::instrument_id_t instrumentID;
2456            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2457            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2458            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2459        } catch (Exception e) {
2460            result.Error(e);
2461        }
2462        return result.Produce();
2463    }
2464    
2465    String LSCPServer::SendChannelMidiData(String MidiMsg, uint uiSamplerChannel, uint Arg1, uint Arg2) {
2466        dmsg(2,("LSCPServer: SendChannelMidiData(MidiMsg=%s,uiSamplerChannel=%d,Arg1=%d,Arg2=%d)\n", MidiMsg.c_str(), uiSamplerChannel, Arg1, Arg2));
2467        LSCPResultSet result;
2468        try {
2469            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2470    
2471            if (Arg1 > 127 || Arg2 > 127) {
2472                throw Exception("Invalid MIDI message");
2473            }
2474    
2475            VirtualMidiDevice* pMidiDevice = NULL;
2476            std::vector<EventHandler::midi_listener_entry>::iterator iter = eventHandler.channelMidiListeners.begin();
2477            for (; iter != eventHandler.channelMidiListeners.end(); ++iter) {
2478                if ((*iter).pEngineChannel == pEngineChannel) {
2479                    pMidiDevice = (*iter).pMidiListener;
2480                  break;                  break;
2481              }              }
2482          }          }
2483          if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");          
2484            if(pMidiDevice == NULL) throw Exception("Couldn't find virtual MIDI device");
2485    
2486          pFxSend->SetLevel((float)dLevel);          if (MidiMsg == "NOTE_ON") {
2487                pMidiDevice->SendNoteOnToDevice(Arg1, Arg2);
2488                bool b = pMidiDevice->SendNoteOnToSampler(Arg1, Arg2);
2489                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2490            } else if (MidiMsg == "NOTE_OFF") {
2491                pMidiDevice->SendNoteOffToDevice(Arg1, Arg2);
2492                bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2);
2493                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2494            } else {
2495                throw Exception("Unknown MIDI message type: " + MidiMsg);
2496            }
2497      } catch (Exception e) {      } catch (Exception e) {
2498          result.Error(e);          result.Error(e);
2499      }      }
# Line 2075  String LSCPServer::ResetChannel(uint uiS Line 2507  String LSCPServer::ResetChannel(uint uiS
2507      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));
2508      LSCPResultSet result;      LSCPResultSet result;
2509      try {      try {
2510          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");  
2511          pEngineChannel->Reset();          pEngineChannel->Reset();
2512      }      }
2513      catch (Exception e) {      catch (Exception e) {
# Line 2103  String LSCPServer::ResetSampler() { Line 2532  String LSCPServer::ResetSampler() {
2532   */   */
2533  String LSCPServer::GetServerInfo() {  String LSCPServer::GetServerInfo() {
2534      dmsg(2,("LSCPServer: GetServerInfo()\n"));      dmsg(2,("LSCPServer: GetServerInfo()\n"));
2535        const std::string description =
2536            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2537      LSCPResultSet result;      LSCPResultSet result;
2538      result.Add("DESCRIPTION", "LinuxSampler - modular, streaming capable sampler");      result.Add("DESCRIPTION", description);
2539      result.Add("VERSION", VERSION);      result.Add("VERSION", VERSION);
2540      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));      result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2541    #if HAVE_SQLITE3
2542        result.Add("INSTRUMENTS_DB_SUPPORT", "yes");
2543    #else
2544        result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2545    #endif
2546    
2547        return result.Produce();
2548    }
2549    
2550    /**
2551     * Will be called by the parser to return the current number of all active streams.
2552     */
2553    String LSCPServer::GetTotalStreamCount() {
2554        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2555        LSCPResultSet result;
2556        result.Add(pSampler->GetDiskStreamCount());
2557      return result.Produce();      return result.Produce();
2558  }  }
2559    
# Line 2126  String LSCPServer::GetTotalVoiceCount() Line 2573  String LSCPServer::GetTotalVoiceCount()
2573  String LSCPServer::GetTotalVoiceCountMax() {  String LSCPServer::GetTotalVoiceCountMax() {
2574      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));      dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));
2575      LSCPResultSet result;      LSCPResultSet result;
2576      result.Add(EngineFactory::EngineInstances().size() * CONFIG_MAX_VOICES);      result.Add(EngineFactory::EngineInstances().size() * GLOBAL_MAX_VOICES);
2577        return result.Produce();
2578    }
2579    
2580    /**
2581     * Will be called by the parser to return the sampler global maximum
2582     * allowed number of voices.
2583     */
2584    String LSCPServer::GetGlobalMaxVoices() {
2585        dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n"));
2586        LSCPResultSet result;
2587        result.Add(GLOBAL_MAX_VOICES);
2588        return result.Produce();
2589    }
2590    
2591    /**
2592     * Will be called by the parser to set the sampler global maximum number of
2593     * voices.
2594     */
2595    String LSCPServer::SetGlobalMaxVoices(int iVoices) {
2596        dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices));
2597        LSCPResultSet result;
2598        try {
2599            if (iVoices < 1) throw Exception("Maximum voices may not be less than 1");
2600            GLOBAL_MAX_VOICES = iVoices; // see common/global_private.cpp
2601            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
2602            if (engines.size() > 0) {
2603                std::set<Engine*>::iterator iter = engines.begin();
2604                std::set<Engine*>::iterator end  = engines.end();
2605                for (; iter != end; ++iter) {
2606                    (*iter)->SetMaxVoices(iVoices);
2607                }
2608            }
2609            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOICES", GLOBAL_MAX_VOICES));
2610        } catch (Exception e) {
2611            result.Error(e);
2612        }
2613        return result.Produce();
2614    }
2615    
2616    /**
2617     * Will be called by the parser to return the sampler global maximum
2618     * allowed number of disk streams.
2619     */
2620    String LSCPServer::GetGlobalMaxStreams() {
2621        dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n"));
2622        LSCPResultSet result;
2623        result.Add(GLOBAL_MAX_STREAMS);
2624        return result.Produce();
2625    }
2626    
2627    /**
2628     * Will be called by the parser to set the sampler global maximum number of
2629     * disk streams.
2630     */
2631    String LSCPServer::SetGlobalMaxStreams(int iStreams) {
2632        dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams));
2633        LSCPResultSet result;
2634        try {
2635            if (iStreams < 0) throw Exception("Maximum disk streams may not be negative");
2636            GLOBAL_MAX_STREAMS = iStreams; // see common/global_private.cpp
2637            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
2638            if (engines.size() > 0) {
2639                std::set<Engine*>::iterator iter = engines.begin();
2640                std::set<Engine*>::iterator end  = engines.end();
2641                for (; iter != end; ++iter) {
2642                    (*iter)->SetMaxDiskStreams(iStreams);
2643                }
2644            }
2645            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "STREAMS", GLOBAL_MAX_STREAMS));
2646        } catch (Exception e) {
2647            result.Error(e);
2648        }
2649      return result.Produce();      return result.Produce();
2650  }  }
2651    
# Line 2140  String LSCPServer::SetGlobalVolume(doubl Line 2659  String LSCPServer::SetGlobalVolume(doubl
2659      LSCPResultSet result;      LSCPResultSet result;
2660      try {      try {
2661          if (dVolume < 0) throw Exception("Volume may not be negative");          if (dVolume < 0) throw Exception("Volume may not be negative");
2662          GLOBAL_VOLUME = dVolume; // see common/global.cpp          GLOBAL_VOLUME = dVolume; // see common/global_private.cpp
2663            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
2664        } catch (Exception e) {
2665            result.Error(e);
2666        }
2667        return result.Produce();
2668    }
2669    
2670    String LSCPServer::GetFileInstruments(String Filename) {
2671        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2672        LSCPResultSet result;
2673        try {
2674            VerifyFile(Filename);
2675        } catch (Exception e) {
2676            result.Error(e);
2677            return result.Produce();
2678        }
2679        // try to find a sampler engine that can handle the file
2680        bool bFound = false;
2681        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2682        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2683            Engine* pEngine = NULL;
2684            try {
2685                pEngine = EngineFactory::Create(engineTypes[i]);
2686                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2687                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2688                if (pManager) {
2689                    std::vector<InstrumentManager::instrument_id_t> IDs =
2690                        pManager->GetInstrumentFileContent(Filename);
2691                    // return the amount of instruments in the file
2692                    result.Add(IDs.size());
2693                    // no more need to ask other engine types
2694                    bFound = true;
2695                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2696            } catch (Exception e) {
2697                // NOOP, as exception is thrown if engine doesn't support file
2698            }
2699            if (pEngine) EngineFactory::Destroy(pEngine);
2700        }
2701    
2702        if (!bFound) result.Error("Unknown file format");
2703        return result.Produce();
2704    }
2705    
2706    String LSCPServer::ListFileInstruments(String Filename) {
2707        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2708        LSCPResultSet result;
2709        try {
2710            VerifyFile(Filename);
2711      } catch (Exception e) {      } catch (Exception e) {
2712          result.Error(e);          result.Error(e);
2713            return result.Produce();
2714      }      }
2715        // try to find a sampler engine that can handle the file
2716        bool bFound = false;
2717        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2718        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2719            Engine* pEngine = NULL;
2720            try {
2721                pEngine = EngineFactory::Create(engineTypes[i]);
2722                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2723                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2724                if (pManager) {
2725                    std::vector<InstrumentManager::instrument_id_t> IDs =
2726                        pManager->GetInstrumentFileContent(Filename);
2727                    // return a list of IDs of the instruments in the file
2728                    String s;
2729                    for (int j = 0; j < IDs.size(); j++) {
2730                        if (s.size()) s += ",";
2731                        s += ToString(IDs[j].Index);
2732                    }
2733                    result.Add(s);
2734                    // no more need to ask other engine types
2735                    bFound = true;
2736                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2737            } catch (Exception e) {
2738                // NOOP, as exception is thrown if engine doesn't support file
2739            }
2740            if (pEngine) EngineFactory::Destroy(pEngine);
2741        }
2742    
2743        if (!bFound) result.Error("Unknown file format");
2744      return result.Produce();      return result.Produce();
2745  }  }
2746    
2747    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2748        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2749        LSCPResultSet result;
2750        try {
2751            VerifyFile(Filename);
2752        } catch (Exception e) {
2753            result.Error(e);
2754            return result.Produce();
2755        }
2756        InstrumentManager::instrument_id_t id;
2757        id.FileName = Filename;
2758        id.Index    = InstrumentID;
2759        // try to find a sampler engine that can handle the file
2760        bool bFound = false;
2761        bool bFatalErr = false;
2762        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2763        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2764            Engine* pEngine = NULL;
2765            try {
2766                pEngine = EngineFactory::Create(engineTypes[i]);
2767                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2768                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2769                if (pManager) {
2770                    // check if the instrument index is valid
2771                    // FIXME: this won't work if an engine only supports parts of the instrument file
2772                    std::vector<InstrumentManager::instrument_id_t> IDs =
2773                        pManager->GetInstrumentFileContent(Filename);
2774                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2775                        std::stringstream ss;
2776                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2777                        bFatalErr = true;
2778                        throw Exception(ss.str());
2779                    }
2780                    // get the info of the requested instrument
2781                    InstrumentManager::instrument_info_t info =
2782                        pManager->GetInstrumentInfo(id);
2783                    // return detailed informations about the file
2784                    result.Add("NAME", info.InstrumentName);
2785                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2786                    result.Add("FORMAT_VERSION", info.FormatVersion);
2787                    result.Add("PRODUCT", info.Product);
2788                    result.Add("ARTISTS", info.Artists);
2789    
2790                    std::stringstream ss;
2791                    bool b = false;
2792                    for (int i = 0; i < 128; i++) {
2793                        if (info.KeyBindings[i]) {
2794                            if (b) ss << ',';
2795                            ss << i; b = true;
2796                        }
2797                    }
2798                    result.Add("KEY_BINDINGS", ss.str());
2799    
2800                    b = false;
2801                    std::stringstream ss2;
2802                    for (int i = 0; i < 128; i++) {
2803                        if (info.KeySwitchBindings[i]) {
2804                            if (b) ss2 << ',';
2805                            ss2 << i; b = true;
2806                        }
2807                    }
2808                    result.Add("KEYSWITCH_BINDINGS", ss2.str());
2809                    // no more need to ask other engine types
2810                    bFound = true;
2811                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2812            } catch (Exception e) {
2813                // usually NOOP, as exception is thrown if engine doesn't support file
2814                if (bFatalErr) result.Error(e);
2815            }
2816            if (pEngine) EngineFactory::Destroy(pEngine);
2817        }
2818    
2819        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2820        return result.Produce();
2821    }
2822    
2823    void LSCPServer::VerifyFile(String Filename) {
2824        #if WIN32
2825        WIN32_FIND_DATA win32FileAttributeData;
2826        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2827        if (!res) {
2828            std::stringstream ss;
2829            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2830            throw Exception(ss.str());
2831        }
2832        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2833            throw Exception("Directory is specified");
2834        }
2835        #else
2836        File f(Filename);
2837        if(!f.Exist()) throw Exception(f.GetErrorMsg());
2838        if (f.IsDirectory()) throw Exception("Directory is specified");
2839        #endif
2840    }
2841    
2842  /**  /**
2843   * 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
2844   * server for receiving event messages.   * server for receiving event messages.
# Line 2173  String LSCPServer::UnsubscribeNotificati Line 2865  String LSCPServer::UnsubscribeNotificati
2865      return result.Produce();      return result.Produce();
2866  }  }
2867    
2868  static int select_callback(void * lscpResultSet, int argc,  String LSCPServer::AddDbInstrumentDirectory(String Dir) {
2869                          char **argv, char **azColName)      dmsg(2,("LSCPServer: AddDbInstrumentDirectory(Dir=%s)\n", Dir.c_str()));
2870  {      LSCPResultSet result;
2871      LSCPResultSet* resultSet = (LSCPResultSet*) lscpResultSet;  #if HAVE_SQLITE3
2872      resultSet->Add(argc, argv);      try {
2873      return 0;          InstrumentsDb::GetInstrumentsDb()->AddDirectory(Dir);
2874        } catch (Exception e) {
2875             result.Error(e);
2876        }
2877    #else
2878        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2879    #endif
2880        return result.Produce();
2881    }
2882    
2883    String LSCPServer::RemoveDbInstrumentDirectory(String Dir, bool Force) {
2884        dmsg(2,("LSCPServer: RemoveDbInstrumentDirectory(Dir=%s,Force=%d)\n", Dir.c_str(), Force));
2885        LSCPResultSet result;
2886    #if HAVE_SQLITE3
2887        try {
2888            InstrumentsDb::GetInstrumentsDb()->RemoveDirectory(Dir, Force);
2889        } catch (Exception e) {
2890             result.Error(e);
2891        }
2892    #else
2893        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2894    #endif
2895        return result.Produce();
2896    }
2897    
2898    String LSCPServer::GetDbInstrumentDirectoryCount(String Dir, bool Recursive) {
2899        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2900        LSCPResultSet result;
2901    #if HAVE_SQLITE3
2902        try {
2903            result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir, Recursive));
2904        } catch (Exception e) {
2905             result.Error(e);
2906        }
2907    #else
2908        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2909    #endif
2910        return result.Produce();
2911    }
2912    
2913    String LSCPServer::GetDbInstrumentDirectories(String Dir, bool Recursive) {
2914        dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2915        LSCPResultSet result;
2916    #if HAVE_SQLITE3
2917        try {
2918            String list;
2919            StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir, Recursive);
2920    
2921            for (int i = 0; i < dirs->size(); i++) {
2922                if (list != "") list += ",";
2923                list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2924            }
2925    
2926            result.Add(list);
2927        } catch (Exception e) {
2928             result.Error(e);
2929        }
2930    #else
2931        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2932    #endif
2933        return result.Produce();
2934    }
2935    
2936    String LSCPServer::GetDbInstrumentDirectoryInfo(String Dir) {
2937        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryInfo(Dir=%s)\n", Dir.c_str()));
2938        LSCPResultSet result;
2939    #if HAVE_SQLITE3
2940        try {
2941            DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2942    
2943            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2944            result.Add("CREATED", info.Created);
2945            result.Add("MODIFIED", info.Modified);
2946        } catch (Exception e) {
2947             result.Error(e);
2948        }
2949    #else
2950        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2951    #endif
2952        return result.Produce();
2953    }
2954    
2955    String LSCPServer::SetDbInstrumentDirectoryName(String Dir, String Name) {
2956        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryName(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
2957        LSCPResultSet result;
2958    #if HAVE_SQLITE3
2959        try {
2960            InstrumentsDb::GetInstrumentsDb()->RenameDirectory(Dir, Name);
2961        } catch (Exception e) {
2962             result.Error(e);
2963        }
2964    #else
2965        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2966    #endif
2967        return result.Produce();
2968    }
2969    
2970    String LSCPServer::MoveDbInstrumentDirectory(String Dir, String Dst) {
2971        dmsg(2,("LSCPServer: MoveDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2972        LSCPResultSet result;
2973    #if HAVE_SQLITE3
2974        try {
2975            InstrumentsDb::GetInstrumentsDb()->MoveDirectory(Dir, Dst);
2976        } catch (Exception e) {
2977             result.Error(e);
2978        }
2979    #else
2980        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2981    #endif
2982        return result.Produce();
2983    }
2984    
2985    String LSCPServer::CopyDbInstrumentDirectory(String Dir, String Dst) {
2986        dmsg(2,("LSCPServer: CopyDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2987        LSCPResultSet result;
2988    #if HAVE_SQLITE3
2989        try {
2990            InstrumentsDb::GetInstrumentsDb()->CopyDirectory(Dir, Dst);
2991        } catch (Exception e) {
2992             result.Error(e);
2993        }
2994    #else
2995        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2996    #endif
2997        return result.Produce();
2998    }
2999    
3000    String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {
3001        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
3002        LSCPResultSet result;
3003    #if HAVE_SQLITE3
3004        try {
3005            InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);
3006        } catch (Exception e) {
3007             result.Error(e);
3008        }
3009    #else
3010        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3011    #endif
3012        return result.Produce();
3013    }
3014    
3015    String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
3016        dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
3017        LSCPResultSet result;
3018    #if HAVE_SQLITE3
3019        try {
3020            int id;
3021            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
3022            id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
3023            if (bBackground) result = id;
3024        } catch (Exception e) {
3025             result.Error(e);
3026        }
3027    #else
3028        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3029    #endif
3030        return result.Produce();
3031    }
3032    
3033    String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground, bool insDir) {
3034        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));
3035        LSCPResultSet result;
3036    #if HAVE_SQLITE3
3037        try {
3038            int id;
3039            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
3040            if (ScanMode.compare("RECURSIVE") == 0) {
3041                id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground, insDir);
3042            } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
3043                id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground, insDir);
3044            } else if (ScanMode.compare("FLAT") == 0) {
3045                id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground, insDir);
3046            } else {
3047                throw Exception("Unknown scan mode: " + ScanMode);
3048            }
3049    
3050            if (bBackground) result = id;
3051        } catch (Exception e) {
3052             result.Error(e);
3053        }
3054    #else
3055        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3056    #endif
3057        return result.Produce();
3058    }
3059    
3060    String LSCPServer::RemoveDbInstrument(String Instr) {
3061        dmsg(2,("LSCPServer: RemoveDbInstrument(Instr=%s)\n", Instr.c_str()));
3062        LSCPResultSet result;
3063    #if HAVE_SQLITE3
3064        try {
3065            InstrumentsDb::GetInstrumentsDb()->RemoveInstrument(Instr);
3066        } catch (Exception e) {
3067             result.Error(e);
3068        }
3069    #else
3070        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3071    #endif
3072        return result.Produce();
3073    }
3074    
3075    String LSCPServer::GetDbInstrumentCount(String Dir, bool Recursive) {
3076        dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
3077        LSCPResultSet result;
3078    #if HAVE_SQLITE3
3079        try {
3080            result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir, Recursive));
3081        } catch (Exception e) {
3082             result.Error(e);
3083        }
3084    #else
3085        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3086    #endif
3087        return result.Produce();
3088    }
3089    
3090    String LSCPServer::GetDbInstruments(String Dir, bool Recursive) {
3091        dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
3092        LSCPResultSet result;
3093    #if HAVE_SQLITE3
3094        try {
3095            String list;
3096            StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir, Recursive);
3097    
3098            for (int i = 0; i < instrs->size(); i++) {
3099                if (list != "") list += ",";
3100                list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
3101            }
3102    
3103            result.Add(list);
3104        } catch (Exception e) {
3105             result.Error(e);
3106        }
3107    #else
3108        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3109    #endif
3110        return result.Produce();
3111    }
3112    
3113    String LSCPServer::GetDbInstrumentInfo(String Instr) {
3114        dmsg(2,("LSCPServer: GetDbInstrumentInfo(Instr=%s)\n", Instr.c_str()));
3115        LSCPResultSet result;
3116    #if HAVE_SQLITE3
3117        try {
3118            DbInstrument info = InstrumentsDb::GetInstrumentsDb()->GetInstrumentInfo(Instr);
3119    
3120            result.Add("INSTRUMENT_FILE", info.InstrFile);
3121            result.Add("INSTRUMENT_NR", info.InstrNr);
3122            result.Add("FORMAT_FAMILY", info.FormatFamily);
3123            result.Add("FORMAT_VERSION", info.FormatVersion);
3124            result.Add("SIZE", (int)info.Size);
3125            result.Add("CREATED", info.Created);
3126            result.Add("MODIFIED", info.Modified);
3127            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
3128            result.Add("IS_DRUM", info.IsDrum);
3129            result.Add("PRODUCT", _escapeLscpResponse(info.Product));
3130            result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
3131            result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
3132        } catch (Exception e) {
3133             result.Error(e);
3134        }
3135    #else
3136        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3137    #endif
3138        return result.Produce();
3139    }
3140    
3141    String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
3142        dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
3143        LSCPResultSet result;
3144    #if HAVE_SQLITE3
3145        try {
3146            ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
3147    
3148            result.Add("FILES_TOTAL", job.FilesTotal);
3149            result.Add("FILES_SCANNED", job.FilesScanned);
3150            result.Add("SCANNING", job.Scanning);
3151            result.Add("STATUS", job.Status);
3152        } catch (Exception e) {
3153             result.Error(e);
3154        }
3155    #else
3156        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3157    #endif
3158        return result.Produce();
3159    }
3160    
3161    String LSCPServer::SetDbInstrumentName(String Instr, String Name) {
3162        dmsg(2,("LSCPServer: SetDbInstrumentName(Instr=%s,Name=%s)\n", Instr.c_str(), Name.c_str()));
3163        LSCPResultSet result;
3164    #if HAVE_SQLITE3
3165        try {
3166            InstrumentsDb::GetInstrumentsDb()->RenameInstrument(Instr, Name);
3167        } catch (Exception e) {
3168             result.Error(e);
3169        }
3170    #else
3171        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3172    #endif
3173        return result.Produce();
3174    }
3175    
3176    String LSCPServer::MoveDbInstrument(String Instr, String Dst) {
3177        dmsg(2,("LSCPServer: MoveDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3178        LSCPResultSet result;
3179    #if HAVE_SQLITE3
3180        try {
3181            InstrumentsDb::GetInstrumentsDb()->MoveInstrument(Instr, Dst);
3182        } catch (Exception e) {
3183             result.Error(e);
3184        }
3185    #else
3186        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3187    #endif
3188        return result.Produce();
3189    }
3190    
3191    String LSCPServer::CopyDbInstrument(String Instr, String Dst) {
3192        dmsg(2,("LSCPServer: CopyDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3193        LSCPResultSet result;
3194    #if HAVE_SQLITE3
3195        try {
3196            InstrumentsDb::GetInstrumentsDb()->CopyInstrument(Instr, Dst);
3197        } catch (Exception e) {
3198             result.Error(e);
3199        }
3200    #else
3201        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3202    #endif
3203        return result.Produce();
3204    }
3205    
3206    String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {
3207        dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
3208        LSCPResultSet result;
3209    #if HAVE_SQLITE3
3210        try {
3211            InstrumentsDb::GetInstrumentsDb()->SetInstrumentDescription(Instr, Desc);
3212        } catch (Exception e) {
3213             result.Error(e);
3214        }
3215    #else
3216        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3217    #endif
3218        return result.Produce();
3219    }
3220    
3221    String LSCPServer::SetDbInstrumentFilePath(String OldPath, String NewPath) {
3222        dmsg(2,("LSCPServer: SetDbInstrumentFilePath(OldPath=%s,NewPath=%s)\n", OldPath.c_str(), NewPath.c_str()));
3223        LSCPResultSet result;
3224    #if HAVE_SQLITE3
3225        try {
3226            InstrumentsDb::GetInstrumentsDb()->SetInstrumentFilePath(OldPath, NewPath);
3227        } catch (Exception e) {
3228             result.Error(e);
3229        }
3230    #else
3231        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3232    #endif
3233        return result.Produce();
3234    }
3235    
3236    String LSCPServer::FindLostDbInstrumentFiles() {
3237        dmsg(2,("LSCPServer: FindLostDbInstrumentFiles()\n"));
3238        LSCPResultSet result;
3239    #if HAVE_SQLITE3
3240        try {
3241            String list;
3242            StringListPtr pLostFiles = InstrumentsDb::GetInstrumentsDb()->FindLostInstrumentFiles();
3243    
3244            for (int i = 0; i < pLostFiles->size(); i++) {
3245                if (list != "") list += ",";
3246                list += "'" + pLostFiles->at(i) + "'";
3247            }
3248    
3249            result.Add(list);
3250        } catch (Exception e) {
3251             result.Error(e);
3252        }
3253    #else
3254        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3255    #endif
3256        return result.Produce();
3257    }
3258    
3259    String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
3260        dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
3261        LSCPResultSet result;
3262    #if HAVE_SQLITE3
3263        try {
3264            SearchQuery Query;
3265            std::map<String,String>::iterator iter;
3266            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3267                if (iter->first.compare("NAME") == 0) {
3268                    Query.Name = iter->second;
3269                } else if (iter->first.compare("CREATED") == 0) {
3270                    Query.SetCreated(iter->second);
3271                } else if (iter->first.compare("MODIFIED") == 0) {
3272                    Query.SetModified(iter->second);
3273                } else if (iter->first.compare("DESCRIPTION") == 0) {
3274                    Query.Description = iter->second;
3275                } else {
3276                    throw Exception("Unknown search criteria: " + iter->first);
3277                }
3278            }
3279    
3280            String list;
3281            StringListPtr pDirectories =
3282                InstrumentsDb::GetInstrumentsDb()->FindDirectories(Dir, &Query, Recursive);
3283    
3284            for (int i = 0; i < pDirectories->size(); i++) {
3285                if (list != "") list += ",";
3286                list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
3287            }
3288    
3289            result.Add(list);
3290        } catch (Exception e) {
3291             result.Error(e);
3292        }
3293    #else
3294        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3295    #endif
3296        return result.Produce();
3297  }  }
3298    
3299  String LSCPServer::QueryDatabase(String query) {  String LSCPServer::FindDbInstruments(String Dir, std::map<String,String> Parameters, bool Recursive) {
3300        dmsg(2,("LSCPServer: FindDbInstruments(Dir=%s)\n", Dir.c_str()));
3301      LSCPResultSet result;      LSCPResultSet result;
3302  #if HAVE_SQLITE3  #if HAVE_SQLITE3
3303      char* zErrMsg = NULL;      try {
3304      sqlite3 *db;          SearchQuery Query;
3305      String selectStr = "SELECT " + query;          std::map<String,String>::iterator iter;
3306            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3307                if (iter->first.compare("NAME") == 0) {
3308                    Query.Name = iter->second;
3309                } else if (iter->first.compare("FORMAT_FAMILIES") == 0) {
3310                    Query.SetFormatFamilies(iter->second);
3311                } else if (iter->first.compare("SIZE") == 0) {
3312                    Query.SetSize(iter->second);
3313                } else if (iter->first.compare("CREATED") == 0) {
3314                    Query.SetCreated(iter->second);
3315                } else if (iter->first.compare("MODIFIED") == 0) {
3316                    Query.SetModified(iter->second);
3317                } else if (iter->first.compare("DESCRIPTION") == 0) {
3318                    Query.Description = iter->second;
3319                } else if (iter->first.compare("IS_DRUM") == 0) {
3320                    if (!strcasecmp(iter->second.c_str(), "true")) {
3321                        Query.InstrType = SearchQuery::DRUM;
3322                    } else {
3323                        Query.InstrType = SearchQuery::CHROMATIC;
3324                    }
3325                } else if (iter->first.compare("PRODUCT") == 0) {
3326                     Query.Product = iter->second;
3327                } else if (iter->first.compare("ARTISTS") == 0) {
3328                     Query.Artists = iter->second;
3329                } else if (iter->first.compare("KEYWORDS") == 0) {
3330                     Query.Keywords = iter->second;
3331                } else {
3332                    throw Exception("Unknown search criteria: " + iter->first);
3333                }
3334            }
3335    
3336      int rc = sqlite3_open("linuxsampler.db", &db);          String list;
3337      if (rc == SQLITE_OK)          StringListPtr pInstruments =
3338      {              InstrumentsDb::GetInstrumentsDb()->FindInstruments(Dir, &Query, Recursive);
3339              rc = sqlite3_exec(db, selectStr.c_str(), select_callback, &result, &zErrMsg);  
3340            for (int i = 0; i < pInstruments->size(); i++) {
3341                if (list != "") list += ",";
3342                list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
3343            }
3344    
3345            result.Add(list);
3346        } catch (Exception e) {
3347             result.Error(e);
3348      }      }
3349      if ( rc != SQLITE_OK )  #else
3350      {      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3351              result.Error(String(zErrMsg), rc);  #endif
3352        return result.Produce();
3353    }
3354    
3355    String LSCPServer::FormatInstrumentsDb() {
3356        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3357        LSCPResultSet result;
3358    #if HAVE_SQLITE3
3359        try {
3360            InstrumentsDb::GetInstrumentsDb()->Format();
3361        } catch (Exception e) {
3362             result.Error(e);
3363      }      }
     sqlite3_close(db);  
3364  #else  #else
3365      result.Error(String("SQLITE3 was not installed when linuxsampler was built. SELECT statement is not available."), 0);      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3366  #endif  #endif
3367      return result.Produce();      return result.Produce();
3368  }  }
3369    
3370    
3371  /**  /**
3372   * 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
3373   * mode is enabled, all commands from the client will (immediately) be   * mode is enabled, all commands from the client will (immediately) be
# Line 2222  String LSCPServer::SetEcho(yyparse_param Line 3386  String LSCPServer::SetEcho(yyparse_param
3386      }      }
3387      return result.Produce();      return result.Produce();
3388  }  }
3389    
3390    }

Legend:
Removed from v.1047  
changed lines
  Added in v.1850

  ViewVC Help
Powered by ViewVC