/[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 397 by senkov, Mon Feb 21 04:28:50 2005 UTC revision 1897 by persson, Sun May 10 09:31:51 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 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  #ifdef HAVE_SQLITE3  #if defined(WIN32)
33  #include "sqlite3.h"  #include <windows.h>
34    #else
35    #include <fcntl.h>
36    #endif
37    
38    #if ! HAVE_SQLITE3
39    #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."
40  #endif  #endif
41    
42  #include "../engines/gig/Engine.h"  #include "../engines/EngineFactory.h"
43    #include "../engines/EngineChannelFactory.h"
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 50  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 58  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) : 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;
111        SocketAddress.sin_addr.s_addr = addr;
112        SocketAddress.sin_port        = port;
113      this->pSampler = pSampler;      this->pSampler = pSampler;
114      LSCPEvent::RegisterEvent(LSCPEvent::event_channels, "CHANNELS");      LSCPEvent::RegisterEvent(LSCPEvent::event_audio_device_count, "AUDIO_OUTPUT_DEVICE_COUNT");
115        LSCPEvent::RegisterEvent(LSCPEvent::event_audio_device_info, "AUDIO_OUTPUT_DEVICE_INFO");
116        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_device_count, "MIDI_INPUT_DEVICE_COUNT");
117        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_device_info, "MIDI_INPUT_DEVICE_INFO");
118        LSCPEvent::RegisterEvent(LSCPEvent::event_channel_count, "CHANNEL_COUNT");
119      LSCPEvent::RegisterEvent(LSCPEvent::event_voice_count, "VOICE_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_voice_count, "VOICE_COUNT");
120      LSCPEvent::RegisterEvent(LSCPEvent::event_stream_count, "STREAM_COUNT");      LSCPEvent::RegisterEvent(LSCPEvent::event_stream_count, "STREAM_COUNT");
121      LSCPEvent::RegisterEvent(LSCPEvent::event_buffer_fill, "BUFFER_FILL");      LSCPEvent::RegisterEvent(LSCPEvent::event_buffer_fill, "BUFFER_FILL");
122      LSCPEvent::RegisterEvent(LSCPEvent::event_info, "INFO");      LSCPEvent::RegisterEvent(LSCPEvent::event_channel_info, "CHANNEL_INFO");
123        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_send_count, "FX_SEND_COUNT");
124        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_send_info, "FX_SEND_INFO");
125        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_count, "MIDI_INSTRUMENT_MAP_COUNT");
126        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");
127        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");
128        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");
129        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_count, "DB_INSTRUMENT_DIRECTORY_COUNT");
130        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_info, "DB_INSTRUMENT_DIRECTORY_INFO");
131        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_count, "DB_INSTRUMENT_COUNT");
132        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
133        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
134      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");      LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
135        LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT");
136        LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
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;
141    }
142    
143    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);
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 83  int LSCPServer::WaitUntilInitialized(lon Line 371  int LSCPServer::WaitUntilInitialized(lon
371  }  }
372    
373  int LSCPServer::Main() {  int LSCPServer::Main() {
374      int hSocket = socket(AF_INET, SOCK_STREAM, 0);          #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);
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;
386          //return -1;          //return -1;
387          exit(EXIT_FAILURE);          exit(EXIT_FAILURE);
388      }      }
389    
     SocketAddress.sin_family      = AF_INET;  
     SocketAddress.sin_port        = htons(LSCP_PORT);  
     SocketAddress.sin_addr.s_addr = htonl(INADDR_ANY);  
   
390      if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {      if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
391          std::cerr << "LSCPServer: Could not bind server socket, retrying for " << ToString(LSCP_SERVER_BIND_TIMEOUT) << " seconds...";          std::cerr << "LSCPServer: Could not bind server socket, retrying for " << ToString(LSCP_SERVER_BIND_TIMEOUT) << " seconds...";
392          for (int trial = 0; true; trial++) { // retry for LSCP_SERVER_BIND_TIMEOUT seconds          for (int trial = 0; true; trial++) { // retry for LSCP_SERVER_BIND_TIMEOUT seconds
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 113  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 120  int LSCPServer::Main() { Line 434  int LSCPServer::Main() {
434      FD_SET(hSocket, &fdSet);      FD_SET(hSocket, &fdSet);
435      int maxSessions = hSocket;      int maxSessions = hSocket;
436    
437        timeval timeout;
438    
439      while (true) {      while (true) {
440          fd_set selectSet = fdSet;          #if CONFIG_PTHREAD_TESTCANCEL
441          int retval = select(maxSessions+1, &selectSet, NULL, NULL, NULL);                  TestCancel();
442          if (retval == 0)          #endif
443            // 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();
446                std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();
447                std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
448                for (; itEngineChannel != itEnd; ++itEngineChannel) {
449                    if ((*itEngineChannel)->StatusChanged()) {
450                        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            }
512    
513            //Now let's deliver late notifies (if any)
514            NotifyBufferMutex.Lock();
515            for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {
516    #ifdef MSG_NOSIGNAL
517                    send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), MSG_NOSIGNAL);
518    #else
519                    send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0);
520    #endif
521            }
522            bufferedNotifies.clear();
523            NotifyBufferMutex.Unlock();
524    
525            fd_set selectSet = fdSet;
526            timeout.tv_sec  = 0;
527            timeout.tv_usec = 100000;
528    
529            int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);
530    
531            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 139  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                    struct linger linger;
559                    linger.l_onoff = 1;
560                    linger.l_linger = 0;
561                    if(setsockopt(socket, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger))) {
562                        std::cerr << "LSCPServer: Failed to set SO_LINGER\n";
563                    }
564    
565                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
566                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
567                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
568                  }                  }
569                    #endif
570    
571                  // Parser initialization                  // Parser initialization
572                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 166  int LSCPServer::Main() { Line 590  int LSCPServer::Main() {
590                                  int dummy; // just a temporary hack to fulfill the restart() function prototype                                  int dummy; // just a temporary hack to fulfill the restart() function prototype
591                                  restart(NULL, dummy); // restart the 'scanner'                                  restart(NULL, dummy); // restart the 'scanner'
592                                  currentSocket = (*iter).hSession;  //a hack                                  currentSocket = (*iter).hSession;  //a hack
593                                    itCurrentSession = iter; // another hack
594                                    dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
595                                  if ((*iter).bVerbose) { // if echo mode enabled                                  if ((*iter).bVerbose) { // if echo mode enabled
596                                      AnswerClient(bufferedCommands[currentSocket]);                                      AnswerClient(bufferedCommands[currentSocket]);
597                                  }                                  }
598                                  int result = yyparse(&(*iter));                                  int result = yyparse(&(*iter));
599                                  currentSocket = -1;     //continuation of a hack                                  currentSocket = -1;     //continuation of a hack
600                                    itCurrentSession = Sessions.end(); // hack as well
601                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));                                  dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
602                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?                                  if (result == LSCP_QUIT) { //Was it a quit command by any chance?
603                                          CloseConnection(iter);                                          CloseConnection(iter);
# Line 181  int LSCPServer::Main() { Line 608  int LSCPServer::Main() {
608                          break;                          break;
609                  }                  }
610          }          }
   
         //Now let's deliver late notifies (if any)  
         NotifyBufferMutex.Lock();  
         for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {  
                 send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0);  
                 bufferedNotifies.erase(iterNotify);  
         }  
         NotifyBufferMutex.Unlock();  
611      }      }
612  }  }
613    
# Line 206  void LSCPServer::CloseConnection( std::v Line 625  void LSCPServer::CloseConnection( std::v
625          NotifyMutex.Lock();          NotifyMutex.Lock();
626          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
627          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
628            #if defined(WIN32)
629            closesocket(socket);
630            #else
631          close(socket);          close(socket);
632            #endif
633          NotifyMutex.Unlock();          NotifyMutex.Unlock();
634  }  }
635    
636    void LSCPServer::CloseAllConnections() {
637        std::vector<yyparse_param_t>::iterator iter = Sessions.begin();
638        while(iter != Sessions.end()) {
639            CloseConnection(iter);
640            iter = Sessions.begin();
641        }
642    }
643    
644    void LSCPServer::LockRTNotify() {
645        RTNotifyMutex.Lock();
646    }
647    
648    void LSCPServer::UnlockRTNotify() {
649        RTNotifyMutex.Unlock();
650    }
651    
652  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {  int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
653          int subs = 0;          int subs = 0;
654          SubscriptionMutex.Lock();          SubscriptionMutex.Lock();
# Line 235  void LSCPServer::SendLSCPNotify( LSCPEve Line 674  void LSCPServer::SendLSCPNotify( LSCPEve
674          while (true) {          while (true) {
675                  if (NotifyMutex.Trylock()) {                  if (NotifyMutex.Trylock()) {
676                          for(;iter != end; iter++)                          for(;iter != end; iter++)
677    #ifdef MSG_NOSIGNAL
678                                    send(*iter, notify.c_str(), notify.size(), MSG_NOSIGNAL);
679    #else
680                                  send(*iter, notify.c_str(), notify.size(), 0);                                  send(*iter, notify.c_str(), notify.size(), 0);
681    #endif
682                          NotifyMutex.Unlock();                          NotifyMutex.Unlock();
683                          break;                          break;
684                  } else {                  } else {
# Line 267  extern int GetLSCPCommand( void *buf, in Line 710  extern int GetLSCPCommand( void *buf, in
710          return command.size();          return command.size();
711  }  }
712    
713    extern yyparse_param_t* GetCurrentYaccSession() {
714        return &(*itCurrentSession);
715    }
716    
717  /**  /**
718   * Will be called to try to read the command from the socket   * Will be called to try to read the command from the socket
719   * 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 277  bool LSCPServer::GetLSCPCommand( std::ve Line 724  bool LSCPServer::GetLSCPCommand( std::ve
724          char c;          char c;
725          int i = 0;          int i = 0;
726          while (true) {          while (true) {
727                    #if defined(WIN32)
728                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
729                    #else
730                  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
731                    #endif
732                  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
733                          CloseConnection(iter);                          CloseConnection(iter);
734                          break;                          break;
# Line 287  bool LSCPServer::GetLSCPCommand( std::ve Line 738  bool LSCPServer::GetLSCPCommand( std::ve
738                                  continue; //Ignore CR                                  continue; //Ignore CR
739                          if (c == '\n') {                          if (c == '\n') {
740                                  LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Received \'" + bufferedCommands[socket] + "\' on socket", socket));                                  LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Received \'" + bufferedCommands[socket] + "\' on socket", socket));
741                                  bufferedCommands[socket] += "\n";                                  bufferedCommands[socket] += "\r\n";
742                                  return true; //Complete command was read                                  return true; //Complete command was read
743                          }                          }
744                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
745                  }                  }
746                    #if defined(WIN32)
747                    if (result == SOCKET_ERROR) {
748                        int wsa_lasterror = WSAGetLastError();
749                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
750                                    return false;
751                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
752                            CloseConnection(iter);
753                            break;
754                    }
755                    #else
756                  if (result == -1) {                  if (result == -1) {
757                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
758                                  return false;                                  return false;
# Line 330  bool LSCPServer::GetLSCPCommand( std::ve Line 791  bool LSCPServer::GetLSCPCommand( std::ve
791                          CloseConnection(iter);                          CloseConnection(iter);
792                          break;                          break;
793                  }                  }
794                    #endif
795          }          }
796          return false;          return false;
797  }  }
# Line 344  void LSCPServer::AnswerClient(String Ret Line 806  void LSCPServer::AnswerClient(String Ret
806      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str()));      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str()));
807      if (currentSocket != -1) {      if (currentSocket != -1) {
808              NotifyMutex.Lock();              NotifyMutex.Lock();
809    #ifdef MSG_NOSIGNAL
810                send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), MSG_NOSIGNAL);
811    #else
812              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);              send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);
813    #endif
814              NotifyMutex.Unlock();              NotifyMutex.Unlock();
815      }      }
816  }  }
# Line 388  String LSCPServer::CreateAudioOutputDevi Line 854  String LSCPServer::CreateAudioOutputDevi
854          AudioOutputDevice* pDevice = pSampler->CreateAudioOutputDevice(Driver, Parameters);          AudioOutputDevice* pDevice = pSampler->CreateAudioOutputDevice(Driver, Parameters);
855          // search for the created device to get its index          // search for the created device to get its index
856          int index = GetAudioOutputDeviceIndex(pDevice);          int index = GetAudioOutputDeviceIndex(pDevice);
857          if (index == -1) throw LinuxSamplerException("Internal error: could not find created audio output device.");          if (index == -1) throw Exception("Internal error: could not find created audio output device.");
858          result = index; // success          result = index; // success
859      }      }
860      catch (LinuxSamplerException e) {      catch (Exception e) {
861          result.Error(e);          result.Error(e);
862      }      }
863      return result.Produce();      return result.Produce();
# Line 404  String LSCPServer::CreateMidiInputDevice Line 870  String LSCPServer::CreateMidiInputDevice
870          MidiInputDevice* pDevice = pSampler->CreateMidiInputDevice(Driver, Parameters);          MidiInputDevice* pDevice = pSampler->CreateMidiInputDevice(Driver, Parameters);
871          // search for the created device to get its index          // search for the created device to get its index
872          int index = GetMidiInputDeviceIndex(pDevice);          int index = GetMidiInputDeviceIndex(pDevice);
873          if (index == -1) throw LinuxSamplerException("Internal error: could not find created midi input device.");          if (index == -1) throw Exception("Internal error: could not find created midi input device.");
874          result = index; // success          result = index; // success
875      }      }
876      catch (LinuxSamplerException e) {      catch (Exception e) {
877          result.Error(e);          result.Error(e);
878      }      }
879      return result.Produce();      return result.Produce();
# Line 418  String LSCPServer::DestroyAudioOutputDev Line 884  String LSCPServer::DestroyAudioOutputDev
884      LSCPResultSet result;      LSCPResultSet result;
885      try {      try {
886          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
887          if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceIndex) + ".");          if (!devices.count(DeviceIndex)) throw Exception("There is no audio output device with index " + ToString(DeviceIndex) + ".");
888          AudioOutputDevice* pDevice = devices[DeviceIndex];          AudioOutputDevice* pDevice = devices[DeviceIndex];
889          pSampler->DestroyAudioOutputDevice(pDevice);          pSampler->DestroyAudioOutputDevice(pDevice);
890      }      }
891      catch (LinuxSamplerException e) {      catch (Exception e) {
892          result.Error(e);          result.Error(e);
893      }      }
894      return result.Produce();      return result.Produce();
# Line 433  String LSCPServer::DestroyMidiInputDevic Line 899  String LSCPServer::DestroyMidiInputDevic
899      LSCPResultSet result;      LSCPResultSet result;
900      try {      try {
901          std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();          std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
902          if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceIndex) + ".");          if (!devices.count(DeviceIndex)) throw Exception("There is no audio output device with index " + ToString(DeviceIndex) + ".");
903          MidiInputDevice* pDevice = devices[DeviceIndex];          MidiInputDevice* pDevice = devices[DeviceIndex];
904          pSampler->DestroyMidiInputDevice(pDevice);          pSampler->DestroyMidiInputDevice(pDevice);
905      }      }
906      catch (LinuxSamplerException e) {      catch (Exception e) {
907          result.Error(e);          result.Error(e);
908      }      }
909      return result.Produce();      return result.Produce();
910  }  }
911    
912    EngineChannel* LSCPServer::GetEngineChannel(uint uiSamplerChannel) {
913        SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
914        if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
915    
916        EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
917        if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
918    
919        return pEngineChannel;
920    }
921    
922  /**  /**
923   * Will be called by the parser to load an instrument.   * Will be called by the parser to load an instrument.
924   */   */
# Line 451  String LSCPServer::LoadInstrument(String Line 927  String LSCPServer::LoadInstrument(String
927      LSCPResultSet result;      LSCPResultSet result;
928      try {      try {
929          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
930          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
931          Engine* pEngine = pSamplerChannel->GetEngine();          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
932          if (!pEngine) throw LinuxSamplerException("No engine loaded on sampler channel");          if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel yet");
933          if (!pSamplerChannel->GetAudioOutputDevice())          if (!pSamplerChannel->GetAudioOutputDevice())
934              throw LinuxSamplerException("No audio output device connected to sampler channel");              throw Exception("No audio output device connected to sampler channel");
935          if (bBackground) {          if (bBackground) {
936              InstrumentLoader.StartNewLoad(Filename, uiInstrument, pEngine);              InstrumentManager::instrument_id_t id;
937                id.FileName = Filename;
938                id.Index    = uiInstrument;
939                InstrumentManager::LoadInstrumentInBackground(id, pEngineChannel);
940          }          }
941          else {          else {
942              // tell the engine which instrument to load              // tell the engine channel which instrument to load
943              pEngine->PrepareLoadInstrument(Filename.c_str(), uiInstrument);              pEngineChannel->PrepareLoadInstrument(Filename.c_str(), uiInstrument);
944              // actually start to load the instrument (blocks until completed)              // actually start to load the instrument (blocks until completed)
945              pEngine->LoadInstrument();              pEngineChannel->LoadInstrument();
946          }          }
947      }      }
948      catch (LinuxSamplerException e) {      catch (Exception e) {
949           result.Error(e);           result.Error(e);
950      }      }
951      return result.Produce();      return result.Produce();
952  }  }
953    
954  /**  /**
955   * Will be called by the parser to load and deploy an engine.   * Will be called by the parser to assign a sampler engine type to a
956     * sampler channel.
957   */   */
958  String LSCPServer::LoadEngine(String EngineName, uint uiSamplerChannel) {  String LSCPServer::SetEngineType(String EngineName, uint uiSamplerChannel) {
959      dmsg(2,("LSCPServer: LoadEngine(EngineName=%s,SamplerChannel=%d)\n", EngineName.c_str(), uiSamplerChannel));      dmsg(2,("LSCPServer: SetEngineType(EngineName=%s,uiSamplerChannel=%d)\n", EngineName.c_str(), uiSamplerChannel));
960      LSCPResultSet result;      LSCPResultSet result;
961      try {      try {
         Engine::type_t type;  
         if ((EngineName == "GigEngine") || (EngineName == "gig")) type = Engine::type_gig;  
         else throw LinuxSamplerException("Unknown engine type");  
962          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
963          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
964          LockRTNotify();          LockRTNotify();
965          pSamplerChannel->LoadEngine(type);          pSamplerChannel->SetEngineType(EngineName);
966            if(HasSoloChannel()) pSamplerChannel->GetEngineChannel()->SetMute(-1);
967          UnlockRTNotify();          UnlockRTNotify();
968      }      }
969      catch (LinuxSamplerException e) {      catch (Exception e) {
970           result.Error(e);           result.Error(e);
971      }      }
972      return result.Produce();      return result.Produce();
# Line 526  String LSCPServer::ListChannels() { Line 1004  String LSCPServer::ListChannels() {
1004   */   */
1005  String LSCPServer::AddChannel() {  String LSCPServer::AddChannel() {
1006      dmsg(2,("LSCPServer: AddChannel()\n"));      dmsg(2,("LSCPServer: AddChannel()\n"));
1007        LockRTNotify();
1008      SamplerChannel* pSamplerChannel = pSampler->AddSamplerChannel();      SamplerChannel* pSamplerChannel = pSampler->AddSamplerChannel();
1009        UnlockRTNotify();
1010      LSCPResultSet result(pSamplerChannel->Index());      LSCPResultSet result(pSamplerChannel->Index());
1011      return result.Produce();      return result.Produce();
1012  }  }
# Line 544  String LSCPServer::RemoveChannel(uint ui Line 1024  String LSCPServer::RemoveChannel(uint ui
1024  }  }
1025    
1026  /**  /**
1027   * Will be called by the parser to get all available engines.   * Will be called by the parser to get the amount of all available engines.
1028   */   */
1029  String LSCPServer::GetAvailableEngines() {  String LSCPServer::GetAvailableEngines() {
1030      dmsg(2,("LSCPServer: GetAvailableEngines()\n"));      dmsg(2,("LSCPServer: GetAvailableEngines()\n"));
1031      LSCPResultSet result("GigEngine");      LSCPResultSet result;
1032        try {
1033            int n = EngineFactory::AvailableEngineTypes().size();
1034            result.Add(n);
1035        }
1036        catch (Exception e) {
1037            result.Error(e);
1038        }
1039        return result.Produce();
1040    }
1041    
1042    /**
1043     * Will be called by the parser to get a list of all available engines.
1044     */
1045    String LSCPServer::ListAvailableEngines() {
1046        dmsg(2,("LSCPServer: ListAvailableEngines()\n"));
1047        LSCPResultSet result;
1048        try {
1049            String s = EngineFactory::AvailableEngineTypesAsString();
1050            result.Add(s);
1051        }
1052        catch (Exception e) {
1053            result.Error(e);
1054        }
1055      return result.Produce();      return result.Produce();
1056  }  }
1057    
1058  /**  /**
1059   * Will be called by the parser to get descriptions for a particular engine.   * Will be called by the parser to get descriptions for a particular
1060     * sampler engine.
1061   */   */
1062  String LSCPServer::GetEngineInfo(String EngineName) {  String LSCPServer::GetEngineInfo(String EngineName) {
1063      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));
1064      LSCPResultSet result;      LSCPResultSet result;
1065        LockRTNotify();
1066      try {      try {
1067          if ((EngineName == "GigEngine") || (EngineName == "gig")) {          Engine* pEngine = EngineFactory::Create(EngineName);
1068              Engine* pEngine = new LinuxSampler::gig::Engine;          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
1069              result.Add("DESCRIPTION", pEngine->Description());          result.Add("VERSION",     pEngine->Version());
1070              result.Add("VERSION",     pEngine->Version());          EngineFactory::Destroy(pEngine);
             delete pEngine;  
         }  
         else throw LinuxSamplerException("Unknown engine type");  
1071      }      }
1072      catch (LinuxSamplerException e) {      catch (Exception e) {
1073           result.Error(e);           result.Error(e);
1074      }      }
1075        UnlockRTNotify();
1076      return result.Produce();      return result.Produce();
1077  }  }
1078    
# Line 582  String LSCPServer::GetChannelInfo(uint u Line 1085  String LSCPServer::GetChannelInfo(uint u
1085      LSCPResultSet result;      LSCPResultSet result;
1086      try {      try {
1087          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1088          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1089          Engine* pEngine = pSamplerChannel->GetEngine();          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1090    
1091          //Defaults values          //Defaults values
1092          String EngineName = "NONE";          String EngineName = "NONE";
# Line 594  String LSCPServer::GetChannelInfo(uint u Line 1097  String LSCPServer::GetChannelInfo(uint u
1097          int InstrumentStatus = -1;          int InstrumentStatus = -1;
1098          int AudioOutputChannels = 0;          int AudioOutputChannels = 0;
1099          String AudioRouting;          String AudioRouting;
1100            int Mute = 0;
1101          if (pEngine) {          bool Solo = false;
1102              EngineName =  pEngine->EngineName();          String MidiInstrumentMap = "NONE";
1103              AudioOutputChannels = pEngine->Channels();  
1104              Volume = pEngine->Volume();          if (pEngineChannel) {
1105              InstrumentStatus = pEngine->InstrumentStatus();              EngineName          = pEngineChannel->EngineName();
1106              InstrumentIndex = pEngine->InstrumentIndex();              AudioOutputChannels = pEngineChannel->Channels();
1107              if (InstrumentIndex != -1)              Volume              = pEngineChannel->Volume();
1108              {              InstrumentStatus    = pEngineChannel->InstrumentStatus();
1109                  InstrumentFileName = pEngine->InstrumentFileName();              InstrumentIndex     = pEngineChannel->InstrumentIndex();
1110                  InstrumentName = pEngine->InstrumentName();              if (InstrumentIndex != -1) {
1111              }                  InstrumentFileName = pEngineChannel->InstrumentFileName();
1112              for (int chan = 0; chan < pEngine->Channels(); chan++) {                  InstrumentName     = pEngineChannel->InstrumentName();
1113                }
1114                for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {
1115                  if (AudioRouting != "") AudioRouting += ",";                  if (AudioRouting != "") AudioRouting += ",";
1116                  AudioRouting += ToString(pEngine->OutputChannel(chan));                  AudioRouting += ToString(pEngineChannel->OutputChannel(chan));
1117              }              }
1118                Mute = pEngineChannel->GetMute();
1119                Solo = pEngineChannel->GetSolo();
1120                if (pEngineChannel->UsesNoMidiInstrumentMap())
1121                    MidiInstrumentMap = "NONE";
1122                else if (pEngineChannel->UsesDefaultMidiInstrumentMap())
1123                    MidiInstrumentMap = "DEFAULT";
1124                else
1125                    MidiInstrumentMap = ToString(pEngineChannel->GetMidiInstrumentMap());
1126          }          }
1127    
1128          result.Add("ENGINE_NAME", EngineName);          result.Add("ENGINE_NAME", EngineName);
# Line 622  String LSCPServer::GetChannelInfo(uint u Line 1135  String LSCPServer::GetChannelInfo(uint u
1135    
1136          result.Add("MIDI_INPUT_DEVICE", GetMidiInputDeviceIndex(pSamplerChannel->GetMidiInputDevice()));          result.Add("MIDI_INPUT_DEVICE", GetMidiInputDeviceIndex(pSamplerChannel->GetMidiInputDevice()));
1137          result.Add("MIDI_INPUT_PORT", pSamplerChannel->GetMidiInputPort());          result.Add("MIDI_INPUT_PORT", pSamplerChannel->GetMidiInputPort());
1138          if (pSamplerChannel->GetMidiInputChannel() == MidiInputPort::midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
1139          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
1140    
1141            // convert the filename into the correct encoding as defined for LSCP
1142            // (especially in terms of special characters -> escape sequences)
1143            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
1144    #if WIN32
1145                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
1146    #else
1147                // assuming POSIX
1148                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
1149    #endif
1150            }
1151    
1152          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
1153          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
1154          result.Add("INSTRUMENT_NAME", InstrumentName);          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
1155          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
1156            result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
1157            result.Add("SOLO", Solo);
1158            result.Add("MIDI_INSTRUMENT_MAP", MidiInstrumentMap);
1159      }      }
1160      catch (LinuxSamplerException e) {      catch (Exception e) {
1161           result.Error(e);           result.Error(e);
1162      }      }
1163      return result.Produce();      return result.Produce();
# Line 644  String LSCPServer::GetVoiceCount(uint ui Line 1171  String LSCPServer::GetVoiceCount(uint ui
1171      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetVoiceCount(SamplerChannel=%d)\n", uiSamplerChannel));
1172      LSCPResultSet result;      LSCPResultSet result;
1173      try {      try {
1174          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
1175          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1176          Engine* pEngine = pSamplerChannel->GetEngine();          result.Add(pEngineChannel->GetEngine()->VoiceCount());
         if (!pEngine) throw LinuxSamplerException("No engine loaded on sampler channel");  
         result.Add(pEngine->VoiceCount());  
1177      }      }
1178      catch (LinuxSamplerException e) {      catch (Exception e) {
1179           result.Error(e);           result.Error(e);
1180      }      }
1181      return result.Produce();      return result.Produce();
# Line 664  String LSCPServer::GetStreamCount(uint u Line 1189  String LSCPServer::GetStreamCount(uint u
1189      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: GetStreamCount(SamplerChannel=%d)\n", uiSamplerChannel));
1190      LSCPResultSet result;      LSCPResultSet result;
1191      try {      try {
1192          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
1193          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1194          Engine* pEngine = pSamplerChannel->GetEngine();          result.Add(pEngineChannel->GetEngine()->DiskStreamCount());
         if (!pEngine) throw LinuxSamplerException("No engine loaded on sampler channel");  
         result.Add(pEngine->DiskStreamCount());  
1195      }      }
1196      catch (LinuxSamplerException e) {      catch (Exception e) {
1197           result.Error(e);           result.Error(e);
1198      }      }
1199      return result.Produce();      return result.Produce();
# Line 684  String LSCPServer::GetBufferFill(fill_re Line 1207  String LSCPServer::GetBufferFill(fill_re
1207      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));      dmsg(2,("LSCPServer: GetBufferFill(ResponseType=%d, SamplerChannel=%d)\n", ResponseType, uiSamplerChannel));
1208      LSCPResultSet result;      LSCPResultSet result;
1209      try {      try {
1210          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
1211          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1212          Engine* pEngine = pSamplerChannel->GetEngine();          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");
         if (!pEngine) throw LinuxSamplerException("No engine loaded on sampler channel");  
         if (!pEngine->DiskStreamSupported())  
             result.Add("NA");  
1213          else {          else {
1214              switch (ResponseType) {              switch (ResponseType) {
1215                  case fill_response_bytes:                  case fill_response_bytes:
1216                      result.Add(pEngine->DiskStreamBufferFillBytes());                      result.Add(pEngineChannel->GetEngine()->DiskStreamBufferFillBytes());
1217                      break;                      break;
1218                  case fill_response_percentage:                  case fill_response_percentage:
1219                      result.Add(pEngine->DiskStreamBufferFillPercentage());                      result.Add(pEngineChannel->GetEngine()->DiskStreamBufferFillPercentage());
1220                      break;                      break;
1221                  default:                  default:
1222                      throw LinuxSamplerException("Unknown fill response type");                      throw Exception("Unknown fill response type");
1223              }              }
1224          }          }
1225      }      }
1226      catch (LinuxSamplerException e) {      catch (Exception e) {
1227           result.Error(e);           result.Error(e);
1228      }      }
1229      return result.Produce();      return result.Produce();
# Line 713  String LSCPServer::GetAvailableAudioOutp Line 1233  String LSCPServer::GetAvailableAudioOutp
1233      dmsg(2,("LSCPServer: GetAvailableAudioOutputDrivers()\n"));      dmsg(2,("LSCPServer: GetAvailableAudioOutputDrivers()\n"));
1234      LSCPResultSet result;      LSCPResultSet result;
1235      try {      try {
1236            int n = AudioOutputDeviceFactory::AvailableDrivers().size();
1237            result.Add(n);
1238        }
1239        catch (Exception e) {
1240            result.Error(e);
1241        }
1242        return result.Produce();
1243    }
1244    
1245    String LSCPServer::ListAvailableAudioOutputDrivers() {
1246        dmsg(2,("LSCPServer: ListAvailableAudioOutputDrivers()\n"));
1247        LSCPResultSet result;
1248        try {
1249          String s = AudioOutputDeviceFactory::AvailableDriversAsString();          String s = AudioOutputDeviceFactory::AvailableDriversAsString();
1250          result.Add(s);          result.Add(s);
1251      }      }
1252      catch (LinuxSamplerException e) {      catch (Exception e) {
1253          result.Error(e);          result.Error(e);
1254      }      }
1255      return result.Produce();      return result.Produce();
# Line 726  String LSCPServer::GetAvailableMidiInput Line 1259  String LSCPServer::GetAvailableMidiInput
1259      dmsg(2,("LSCPServer: GetAvailableMidiInputDrivers()\n"));      dmsg(2,("LSCPServer: GetAvailableMidiInputDrivers()\n"));
1260      LSCPResultSet result;      LSCPResultSet result;
1261      try {      try {
1262            int n = MidiInputDeviceFactory::AvailableDrivers().size();
1263            result.Add(n);
1264        }
1265        catch (Exception e) {
1266            result.Error(e);
1267        }
1268        return result.Produce();
1269    }
1270    
1271    String LSCPServer::ListAvailableMidiInputDrivers() {
1272        dmsg(2,("LSCPServer: ListAvailableMidiInputDrivers()\n"));
1273        LSCPResultSet result;
1274        try {
1275          String s = MidiInputDeviceFactory::AvailableDriversAsString();          String s = MidiInputDeviceFactory::AvailableDriversAsString();
1276          result.Add(s);          result.Add(s);
1277      }      }
1278      catch (LinuxSamplerException e) {      catch (Exception e) {
1279          result.Error(e);          result.Error(e);
1280      }      }
1281      return result.Produce();      return result.Produce();
# Line 749  String LSCPServer::GetMidiInputDriverInf Line 1295  String LSCPServer::GetMidiInputDriverInf
1295              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1296                  if (s != "") s += ",";                  if (s != "") s += ",";
1297                  s += iter->first;                  s += iter->first;
1298                    delete iter->second;
1299              }              }
1300              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1301          }          }
1302      }      }
1303      catch (LinuxSamplerException e) {      catch (Exception e) {
1304          result.Error(e);          result.Error(e);
1305      }      }
1306      return result.Produce();      return result.Produce();
# Line 773  String LSCPServer::GetAudioOutputDriverI Line 1320  String LSCPServer::GetAudioOutputDriverI
1320              for (;iter != parameters.end(); iter++) {              for (;iter != parameters.end(); iter++) {
1321                  if (s != "") s += ",";                  if (s != "") s += ",";
1322                  s += iter->first;                  s += iter->first;
1323                    delete iter->second;
1324              }              }
1325              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1326          }          }
1327      }      }
1328      catch (LinuxSamplerException e) {      catch (Exception e) {
1329          result.Error(e);          result.Error(e);
1330      }      }
1331      return result.Produce();      return result.Produce();
# Line 803  String LSCPServer::GetMidiInputDriverPar Line 1351  String LSCPServer::GetMidiInputDriverPar
1351          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1352          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1353          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1354            delete pParameter;
1355      }      }
1356      catch (LinuxSamplerException e) {      catch (Exception e) {
1357          result.Error(e);          result.Error(e);
1358      }      }
1359      return result.Produce();      return result.Produce();
# Line 830  String LSCPServer::GetAudioOutputDriverP Line 1379  String LSCPServer::GetAudioOutputDriverP
1379          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);          if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1380          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);          if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1381          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);          if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1382            delete pParameter;
1383      }      }
1384      catch (LinuxSamplerException e) {      catch (Exception e) {
1385          result.Error(e);          result.Error(e);
1386      }      }
1387      return result.Produce();      return result.Produce();
# Line 844  String LSCPServer::GetAudioOutputDeviceC Line 1394  String LSCPServer::GetAudioOutputDeviceC
1394          uint count = pSampler->AudioOutputDevices();          uint count = pSampler->AudioOutputDevices();
1395          result.Add(count); // success          result.Add(count); // success
1396      }      }
1397      catch (LinuxSamplerException e) {      catch (Exception e) {
1398          result.Error(e);          result.Error(e);
1399      }      }
1400      return result.Produce();      return result.Produce();
# Line 857  String LSCPServer::GetMidiInputDeviceCou Line 1407  String LSCPServer::GetMidiInputDeviceCou
1407          uint count = pSampler->MidiInputDevices();          uint count = pSampler->MidiInputDevices();
1408          result.Add(count); // success          result.Add(count); // success
1409      }      }
1410      catch (LinuxSamplerException e) {      catch (Exception e) {
1411          result.Error(e);          result.Error(e);
1412      }      }
1413      return result.Produce();      return result.Produce();
# Line 876  String LSCPServer::GetAudioOutputDevices Line 1426  String LSCPServer::GetAudioOutputDevices
1426          }          }
1427          result.Add(s);          result.Add(s);
1428      }      }
1429      catch (LinuxSamplerException e) {      catch (Exception e) {
1430          result.Error(e);          result.Error(e);
1431      }      }
1432      return result.Produce();      return result.Produce();
# Line 895  String LSCPServer::GetMidiInputDevices() Line 1445  String LSCPServer::GetMidiInputDevices()
1445          }          }
1446          result.Add(s);          result.Add(s);
1447      }      }
1448      catch (LinuxSamplerException e) {      catch (Exception e) {
1449          result.Error(e);          result.Error(e);
1450      }      }
1451      return result.Produce();      return result.Produce();
# Line 906  String LSCPServer::GetAudioOutputDeviceI Line 1456  String LSCPServer::GetAudioOutputDeviceI
1456      LSCPResultSet result;      LSCPResultSet result;
1457      try {      try {
1458          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1459          if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceIndex) + ".");          if (!devices.count(DeviceIndex)) throw Exception("There is no audio output device with index " + ToString(DeviceIndex) + ".");
1460          AudioOutputDevice* pDevice = devices[DeviceIndex];          AudioOutputDevice* pDevice = devices[DeviceIndex];
1461          result.Add("DRIVER", pDevice->Driver());          result.Add("DRIVER", pDevice->Driver());
1462          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
# Line 915  String LSCPServer::GetAudioOutputDeviceI Line 1465  String LSCPServer::GetAudioOutputDeviceI
1465              result.Add(iter->first, iter->second->Value());              result.Add(iter->first, iter->second->Value());
1466          }          }
1467      }      }
1468      catch (LinuxSamplerException e) {      catch (Exception e) {
1469          result.Error(e);          result.Error(e);
1470      }      }
1471      return result.Produce();      return result.Produce();
# Line 926  String LSCPServer::GetMidiInputDeviceInf Line 1476  String LSCPServer::GetMidiInputDeviceInf
1476      LSCPResultSet result;      LSCPResultSet result;
1477      try {      try {
1478          std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();          std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1479          if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");          if (!devices.count(DeviceIndex)) throw Exception("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1480          MidiInputDevice* pDevice = devices[DeviceIndex];          MidiInputDevice* pDevice = devices[DeviceIndex];
1481          result.Add("DRIVER", pDevice->Driver());          result.Add("DRIVER", pDevice->Driver());
1482          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
# Line 935  String LSCPServer::GetMidiInputDeviceInf Line 1485  String LSCPServer::GetMidiInputDeviceInf
1485              result.Add(iter->first, iter->second->Value());              result.Add(iter->first, iter->second->Value());
1486          }          }
1487      }      }
1488      catch (LinuxSamplerException e) {      catch (Exception e) {
1489          result.Error(e);          result.Error(e);
1490      }      }
1491      return result.Produce();      return result.Produce();
# Line 946  String LSCPServer::GetMidiInputPortInfo( Line 1496  String LSCPServer::GetMidiInputPortInfo(
1496      try {      try {
1497          // get MIDI input device          // get MIDI input device
1498          std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();          std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1499          if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");          if (!devices.count(DeviceIndex)) throw Exception("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1500          MidiInputDevice* pDevice = devices[DeviceIndex];          MidiInputDevice* pDevice = devices[DeviceIndex];
1501    
1502          // get MIDI port          // get MIDI port
1503          MidiInputPort* pMidiInputPort = pDevice->GetPort(PortIndex);          MidiInputPort* pMidiInputPort = pDevice->GetPort(PortIndex);
1504          if (!pMidiInputPort) throw LinuxSamplerException("There is no MIDI input port with index " + ToString(PortIndex) + ".");          if (!pMidiInputPort) throw Exception("There is no MIDI input port with index " + ToString(PortIndex) + ".");
1505    
1506          // return the values of all MIDI port parameters          // return the values of all MIDI port parameters
1507          std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();          std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();
# Line 960  String LSCPServer::GetMidiInputPortInfo( Line 1510  String LSCPServer::GetMidiInputPortInfo(
1510              result.Add(iter->first, iter->second->Value());              result.Add(iter->first, iter->second->Value());
1511          }          }
1512      }      }
1513      catch (LinuxSamplerException e) {      catch (Exception e) {
1514          result.Error(e);          result.Error(e);
1515      }      }
1516      return result.Produce();      return result.Produce();
# Line 972  String LSCPServer::GetAudioOutputChannel Line 1522  String LSCPServer::GetAudioOutputChannel
1522      try {      try {
1523          // get audio output device          // get audio output device
1524          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1525          if (!devices.count(DeviceId)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceId) + ".");          if (!devices.count(DeviceId)) throw Exception("There is no audio output device with index " + ToString(DeviceId) + ".");
1526          AudioOutputDevice* pDevice = devices[DeviceId];          AudioOutputDevice* pDevice = devices[DeviceId];
1527    
1528          // get audio channel          // get audio channel
1529          AudioChannel* pChannel = pDevice->Channel(ChannelId);          AudioChannel* pChannel = pDevice->Channel(ChannelId);
1530          if (!pChannel) throw LinuxSamplerException("Audio output device does not have audio channel " + ToString(ChannelId) + ".");          if (!pChannel) throw Exception("Audio output device does not have audio channel " + ToString(ChannelId) + ".");
1531    
1532          // return the values of all audio channel parameters          // return the values of all audio channel parameters
1533          std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();          std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();
# Line 986  String LSCPServer::GetAudioOutputChannel Line 1536  String LSCPServer::GetAudioOutputChannel
1536              result.Add(iter->first, iter->second->Value());              result.Add(iter->first, iter->second->Value());
1537          }          }
1538      }      }
1539      catch (LinuxSamplerException e) {      catch (Exception e) {
1540          result.Error(e);          result.Error(e);
1541      }      }
1542      return result.Produce();      return result.Produce();
# Line 998  String LSCPServer::GetMidiInputPortParam Line 1548  String LSCPServer::GetMidiInputPortParam
1548      try {      try {
1549          // get MIDI input device          // get MIDI input device
1550          std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();          std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1551          if (!devices.count(DeviceId)) throw LinuxSamplerException("There is no midi input device with index " + ToString(DeviceId) + ".");          if (!devices.count(DeviceId)) throw Exception("There is no midi input device with index " + ToString(DeviceId) + ".");
1552          MidiInputDevice* pDevice = devices[DeviceId];          MidiInputDevice* pDevice = devices[DeviceId];
1553    
1554          // get midi port          // get midi port
1555          MidiInputPort* pPort = pDevice->GetPort(PortId);          MidiInputPort* pPort = pDevice->GetPort(PortId);
1556          if (!pPort) throw LinuxSamplerException("Midi input device does not have port " + ToString(PortId) + ".");          if (!pPort) throw Exception("Midi input device does not have port " + ToString(PortId) + ".");
1557    
1558          // get desired port parameter          // get desired port parameter
1559          std::map<String,DeviceRuntimeParameter*> parameters = pPort->PortParameters();          std::map<String,DeviceRuntimeParameter*> parameters = pPort->PortParameters();
1560          if (!parameters.count(ParameterName)) throw LinuxSamplerException("Midi port does not provide a parameter '" + ParameterName + "'.");          if (!parameters.count(ParameterName)) throw Exception("Midi port does not provide a parameter '" + ParameterName + "'.");
1561          DeviceRuntimeParameter* pParameter = parameters[ParameterName];          DeviceRuntimeParameter* pParameter = parameters[ParameterName];
1562    
1563          // return all fields of this audio channel parameter          // return all fields of this audio channel parameter
# Line 1019  String LSCPServer::GetMidiInputPortParam Line 1569  String LSCPServer::GetMidiInputPortParam
1569          if (pParameter->RangeMax())      result.Add("RANGE_MAX",     *pParameter->RangeMax());          if (pParameter->RangeMax())      result.Add("RANGE_MAX",     *pParameter->RangeMax());
1570          if (pParameter->Possibilities()) result.Add("POSSIBILITIES", *pParameter->Possibilities());          if (pParameter->Possibilities()) result.Add("POSSIBILITIES", *pParameter->Possibilities());
1571      }      }
1572      catch (LinuxSamplerException e) {      catch (Exception e) {
1573          result.Error(e);          result.Error(e);
1574      }      }
1575      return result.Produce();      return result.Produce();
# Line 1031  String LSCPServer::GetAudioOutputChannel Line 1581  String LSCPServer::GetAudioOutputChannel
1581      try {      try {
1582          // get audio output device          // get audio output device
1583          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1584          if (!devices.count(DeviceId)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceId) + ".");          if (!devices.count(DeviceId)) throw Exception("There is no audio output device with index " + ToString(DeviceId) + ".");
1585          AudioOutputDevice* pDevice = devices[DeviceId];          AudioOutputDevice* pDevice = devices[DeviceId];
1586    
1587          // get audio channel          // get audio channel
1588          AudioChannel* pChannel = pDevice->Channel(ChannelId);          AudioChannel* pChannel = pDevice->Channel(ChannelId);
1589          if (!pChannel) throw LinuxSamplerException("Audio output device does not have audio channel " + ToString(ChannelId) + ".");          if (!pChannel) throw Exception("Audio output device does not have audio channel " + ToString(ChannelId) + ".");
1590    
1591          // get desired audio channel parameter          // get desired audio channel parameter
1592          std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();          std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();
1593          if (!parameters.count(ParameterName)) throw LinuxSamplerException("Audio channel does not provide a parameter '" + ParameterName + "'.");          if (!parameters.count(ParameterName)) throw Exception("Audio channel does not provide a parameter '" + ParameterName + "'.");
1594          DeviceRuntimeParameter* pParameter = parameters[ParameterName];          DeviceRuntimeParameter* pParameter = parameters[ParameterName];
1595    
1596          // return all fields of this audio channel parameter          // return all fields of this audio channel parameter
# Line 1052  String LSCPServer::GetAudioOutputChannel Line 1602  String LSCPServer::GetAudioOutputChannel
1602          if (pParameter->RangeMax())      result.Add("RANGE_MAX",     *pParameter->RangeMax());          if (pParameter->RangeMax())      result.Add("RANGE_MAX",     *pParameter->RangeMax());
1603          if (pParameter->Possibilities()) result.Add("POSSIBILITIES", *pParameter->Possibilities());          if (pParameter->Possibilities()) result.Add("POSSIBILITIES", *pParameter->Possibilities());
1604      }      }
1605      catch (LinuxSamplerException e) {      catch (Exception e) {
1606          result.Error(e);          result.Error(e);
1607      }      }
1608      return result.Produce();      return result.Produce();
# Line 1064  String LSCPServer::SetAudioOutputChannel Line 1614  String LSCPServer::SetAudioOutputChannel
1614      try {      try {
1615          // get audio output device          // get audio output device
1616          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1617          if (!devices.count(DeviceId)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceId) + ".");          if (!devices.count(DeviceId)) throw Exception("There is no audio output device with index " + ToString(DeviceId) + ".");
1618          AudioOutputDevice* pDevice = devices[DeviceId];          AudioOutputDevice* pDevice = devices[DeviceId];
1619    
1620          // get audio channel          // get audio channel
1621          AudioChannel* pChannel = pDevice->Channel(ChannelId);          AudioChannel* pChannel = pDevice->Channel(ChannelId);
1622          if (!pChannel) throw LinuxSamplerException("Audio output device does not have audio channel " + ToString(ChannelId) + ".");          if (!pChannel) throw Exception("Audio output device does not have audio channel " + ToString(ChannelId) + ".");
1623    
1624          // get desired audio channel parameter          // get desired audio channel parameter
1625          std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();          std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();
1626          if (!parameters.count(ParamKey)) throw LinuxSamplerException("Audio channel does not provide a parameter '" + ParamKey + "'.");          if (!parameters.count(ParamKey)) throw Exception("Audio channel does not provide a parameter '" + ParamKey + "'.");
1627          DeviceRuntimeParameter* pParameter = parameters[ParamKey];          DeviceRuntimeParameter* pParameter = parameters[ParamKey];
1628    
1629          // set new channel parameter value          // set new channel parameter value
1630          pParameter->SetValue(ParamVal);          pParameter->SetValue(ParamVal);
1631            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_info, DeviceId));
1632      }      }
1633      catch (LinuxSamplerException e) {      catch (Exception e) {
1634          result.Error(e);          result.Error(e);
1635      }      }
1636      return result.Produce();      return result.Produce();
# Line 1090  String LSCPServer::SetAudioOutputDeviceP Line 1641  String LSCPServer::SetAudioOutputDeviceP
1641      LSCPResultSet result;      LSCPResultSet result;
1642      try {      try {
1643          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1644          if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no audio output device with index " + ToString(DeviceIndex) + ".");          if (!devices.count(DeviceIndex)) throw Exception("There is no audio output device with index " + ToString(DeviceIndex) + ".");
1645          AudioOutputDevice* pDevice = devices[DeviceIndex];          AudioOutputDevice* pDevice = devices[DeviceIndex];
1646          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1647          if (!parameters.count(ParamKey)) throw LinuxSamplerException("Audio output device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");          if (!parameters.count(ParamKey)) throw Exception("Audio output device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");
1648          parameters[ParamKey]->SetValue(ParamVal);          parameters[ParamKey]->SetValue(ParamVal);
1649            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_info, DeviceIndex));
1650      }      }
1651      catch (LinuxSamplerException e) {      catch (Exception e) {
1652          result.Error(e);          result.Error(e);
1653      }      }
1654      return result.Produce();      return result.Produce();
# Line 1107  String LSCPServer::SetMidiInputDevicePar Line 1659  String LSCPServer::SetMidiInputDevicePar
1659      LSCPResultSet result;      LSCPResultSet result;
1660      try {      try {
1661          std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();          std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1662          if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");          if (!devices.count(DeviceIndex)) throw Exception("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1663          MidiInputDevice* pDevice = devices[DeviceIndex];          MidiInputDevice* pDevice = devices[DeviceIndex];
1664          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1665          if (!parameters.count(ParamKey)) throw LinuxSamplerException("MIDI input device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");          if (!parameters.count(ParamKey)) throw Exception("MIDI input device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");
1666          parameters[ParamKey]->SetValue(ParamVal);          parameters[ParamKey]->SetValue(ParamVal);
1667            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_info, DeviceIndex));
1668      }      }
1669      catch (LinuxSamplerException e) {      catch (Exception e) {
1670          result.Error(e);          result.Error(e);
1671      }      }
1672      return result.Produce();      return result.Produce();
# Line 1125  String LSCPServer::SetMidiInputPortParam Line 1678  String LSCPServer::SetMidiInputPortParam
1678      try {      try {
1679          // get MIDI input device          // get MIDI input device
1680          std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();          std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1681          if (!devices.count(DeviceIndex)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");          if (!devices.count(DeviceIndex)) throw Exception("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1682          MidiInputDevice* pDevice = devices[DeviceIndex];          MidiInputDevice* pDevice = devices[DeviceIndex];
1683    
1684          // get MIDI port          // get MIDI port
1685          MidiInputPort* pMidiInputPort = pDevice->GetPort(PortIndex);          MidiInputPort* pMidiInputPort = pDevice->GetPort(PortIndex);
1686          if (!pMidiInputPort) throw LinuxSamplerException("There is no MIDI input port with index " + ToString(PortIndex) + ".");          if (!pMidiInputPort) throw Exception("There is no MIDI input port with index " + ToString(PortIndex) + ".");
1687    
1688          // set port parameter value          // set port parameter value
1689          std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();          std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();
1690          if (!parameters.count(ParamKey)) throw LinuxSamplerException("MIDI input device " + ToString(PortIndex) + " does not have a parameter '" + ParamKey + "'");          if (!parameters.count(ParamKey)) throw Exception("MIDI input device " + ToString(PortIndex) + " does not have a parameter '" + ParamKey + "'");
1691          parameters[ParamKey]->SetValue(ParamVal);          parameters[ParamKey]->SetValue(ParamVal);
1692            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_info, DeviceIndex));
1693      }      }
1694      catch (LinuxSamplerException e) {      catch (Exception e) {
1695          result.Error(e);          result.Error(e);
1696      }      }
1697      return result.Produce();      return result.Produce();
# Line 1152  String LSCPServer::SetAudioOutputChannel Line 1706  String LSCPServer::SetAudioOutputChannel
1706      LSCPResultSet result;      LSCPResultSet result;
1707      try {      try {
1708          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1709          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1710          Engine* pEngine = pSamplerChannel->GetEngine();          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1711          if (!pEngine) throw LinuxSamplerException("No engine deployed on sampler channel " + ToString(uiSamplerChannel));          if (!pEngineChannel) throw Exception("No engine type yet assigned to sampler channel " + ToString(uiSamplerChannel));
1712          if (!pSamplerChannel->GetAudioOutputDevice()) throw LinuxSamplerException("No audio output device connected to sampler channel " + ToString(uiSamplerChannel));          if (!pSamplerChannel->GetAudioOutputDevice()) throw Exception("No audio output device connected to sampler channel " + ToString(uiSamplerChannel));
1713          pEngine->SetOutputChannel(ChannelAudioOutputChannel, AudioOutputDeviceInputChannel);          pEngineChannel->SetOutputChannel(ChannelAudioOutputChannel, AudioOutputDeviceInputChannel);
1714      }      }
1715      catch (LinuxSamplerException e) {      catch (Exception e) {
1716           result.Error(e);           result.Error(e);
1717      }      }
1718      return result.Produce();      return result.Produce();
# Line 1167  String LSCPServer::SetAudioOutputChannel Line 1721  String LSCPServer::SetAudioOutputChannel
1721  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {
1722      dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));      dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));
1723      LSCPResultSet result;      LSCPResultSet result;
1724        LockRTNotify();
1725      try {      try {
1726          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1727          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1728          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1729          if (!devices.count(AudioDeviceId)) throw LinuxSamplerException("There is no audio output device with index " + ToString(AudioDeviceId));          if (!devices.count(AudioDeviceId)) throw Exception("There is no audio output device with index " + ToString(AudioDeviceId));
1730          AudioOutputDevice* pDevice = devices[AudioDeviceId];          AudioOutputDevice* pDevice = devices[AudioDeviceId];
1731          pSamplerChannel->SetAudioOutputDevice(pDevice);          pSamplerChannel->SetAudioOutputDevice(pDevice);
1732      }      }
1733      catch (LinuxSamplerException e) {      catch (Exception e) {
1734           result.Error(e);           result.Error(e);
1735      }      }
1736        UnlockRTNotify();
1737      return result.Produce();      return result.Produce();
1738  }  }
1739    
1740  String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {  String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {
1741      dmsg(2,("LSCPServer: SetAudioOutputType(String AudioOutputDriver=%s, SamplerChannel=%d)\n",AudioOutputDriver.c_str(),uiSamplerChannel));      dmsg(2,("LSCPServer: SetAudioOutputType(String AudioOutputDriver=%s, SamplerChannel=%d)\n",AudioOutputDriver.c_str(),uiSamplerChannel));
1742      LSCPResultSet result;      LSCPResultSet result;
1743        LockRTNotify();
1744      try {      try {
1745          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1746          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1747          // Driver type name aliasing...          // Driver type name aliasing...
1748          if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA";          if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA";
1749          if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK";          if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK";
# Line 1208  String LSCPServer::SetAudioOutputType(St Line 1765  String LSCPServer::SetAudioOutputType(St
1765          }          }
1766          // Must have a device...          // Must have a device...
1767          if (pDevice == NULL)          if (pDevice == NULL)
1768              throw LinuxSamplerException("Internal error: could not create audio output device.");              throw Exception("Internal error: could not create audio output device.");
1769          // Set it as the current channel device...          // Set it as the current channel device...
1770          pSamplerChannel->SetAudioOutputDevice(pDevice);          pSamplerChannel->SetAudioOutputDevice(pDevice);
1771      }      }
1772      catch (LinuxSamplerException e) {      catch (Exception e) {
1773           result.Error(e);           result.Error(e);
1774      }      }
1775        UnlockRTNotify();
1776      return result.Produce();      return result.Produce();
1777  }  }
1778    
# Line 1223  String LSCPServer::SetMIDIInputPort(uint Line 1781  String LSCPServer::SetMIDIInputPort(uint
1781      LSCPResultSet result;      LSCPResultSet result;
1782      try {      try {
1783          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1784          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1785          pSamplerChannel->SetMidiInputPort(MIDIPort);          pSamplerChannel->SetMidiInputPort(MIDIPort);
1786      }      }
1787      catch (LinuxSamplerException e) {      catch (Exception e) {
1788           result.Error(e);           result.Error(e);
1789      }      }
1790      return result.Produce();      return result.Produce();
# Line 1237  String LSCPServer::SetMIDIInputChannel(u Line 1795  String LSCPServer::SetMIDIInputChannel(u
1795      LSCPResultSet result;      LSCPResultSet result;
1796      try {      try {
1797          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1798          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1799          pSamplerChannel->SetMidiInputChannel((MidiInputPort::midi_chan_t) MIDIChannel);          pSamplerChannel->SetMidiInputChannel((midi_chan_t) MIDIChannel);
1800      }      }
1801      catch (LinuxSamplerException e) {      catch (Exception e) {
1802           result.Error(e);           result.Error(e);
1803      }      }
1804      return result.Produce();      return result.Produce();
# Line 1251  String LSCPServer::SetMIDIInputDevice(ui Line 1809  String LSCPServer::SetMIDIInputDevice(ui
1809      LSCPResultSet result;      LSCPResultSet result;
1810      try {      try {
1811          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1812          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1813          std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();          std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1814          if (!devices.count(MIDIDeviceId)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(MIDIDeviceId));          if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1815          MidiInputDevice* pDevice = devices[MIDIDeviceId];          MidiInputDevice* pDevice = devices[MIDIDeviceId];
1816          pSamplerChannel->SetMidiInputDevice(pDevice);          pSamplerChannel->SetMidiInputDevice(pDevice);
1817      }      }
1818      catch (LinuxSamplerException e) {      catch (Exception e) {
1819           result.Error(e);           result.Error(e);
1820      }      }
1821      return result.Produce();      return result.Produce();
# Line 1268  String LSCPServer::SetMIDIInputType(Stri Line 1826  String LSCPServer::SetMIDIInputType(Stri
1826      LSCPResultSet result;      LSCPResultSet result;
1827      try {      try {
1828          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1829          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1830          // Driver type name aliasing...          // Driver type name aliasing...
1831          if (MidiInputDriver == "Alsa") MidiInputDriver = "ALSA";          if (MidiInputDriver == "Alsa") MidiInputDriver = "ALSA";
1832          // Check if there's one MIDI input device already created          // Check if there's one MIDI input device already created
# Line 1288  String LSCPServer::SetMIDIInputType(Stri Line 1846  String LSCPServer::SetMIDIInputType(Stri
1846              pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);              pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);
1847              // Make it with at least one initial port.              // Make it with at least one initial port.
1848              std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();              std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
             parameters["PORTS"]->SetValue("1");  
1849          }          }
1850          // Must have a device...          // Must have a device...
1851          if (pDevice == NULL)          if (pDevice == NULL)
1852              throw LinuxSamplerException("Internal error: could not create MIDI input device.");              throw Exception("Internal error: could not create MIDI input device.");
1853          // Set it as the current channel device...          // Set it as the current channel device...
1854          pSamplerChannel->SetMidiInputDevice(pDevice);          pSamplerChannel->SetMidiInputDevice(pDevice);
1855      }      }
1856      catch (LinuxSamplerException e) {      catch (Exception e) {
1857           result.Error(e);           result.Error(e);
1858      }      }
1859      return result.Produce();      return result.Produce();
# Line 1311  String LSCPServer::SetMIDIInput(uint MID Line 1868  String LSCPServer::SetMIDIInput(uint MID
1868      LSCPResultSet result;      LSCPResultSet result;
1869      try {      try {
1870          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1871          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1872          std::map<uint, MidiInputDevice*> devices =  pSampler->GetMidiInputDevices();          std::map<uint, MidiInputDevice*> devices =  pSampler->GetMidiInputDevices();
1873          if (!devices.count(MIDIDeviceId)) throw LinuxSamplerException("There is no MIDI input device with index " + ToString(MIDIDeviceId));          if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1874          MidiInputDevice* pDevice = devices[MIDIDeviceId];          MidiInputDevice* pDevice = devices[MIDIDeviceId];
1875          pSamplerChannel->SetMidiInput(pDevice, MIDIPort, (MidiInputPort::midi_chan_t) MIDIChannel);          pSamplerChannel->SetMidiInput(pDevice, MIDIPort, (midi_chan_t) MIDIChannel);
1876      }      }
1877      catch (LinuxSamplerException e) {      catch (Exception e) {
1878           result.Error(e);           result.Error(e);
1879      }      }
1880      return result.Produce();      return result.Produce();
# Line 1331  String LSCPServer::SetVolume(double dVol Line 1888  String LSCPServer::SetVolume(double dVol
1888      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));
1889      LSCPResultSet result;      LSCPResultSet result;
1890      try {      try {
1891          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
1892          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          pEngineChannel->Volume(dVolume);
         Engine* pEngine = pSamplerChannel->GetEngine();  
         if (!pEngine) throw LinuxSamplerException("No engine loaded on sampler channel");  
         pEngine->Volume(dVolume);  
1893      }      }
1894      catch (LinuxSamplerException e) {      catch (Exception e) {
1895           result.Error(e);           result.Error(e);
1896      }      }
1897      return result.Produce();      return result.Produce();
1898  }  }
1899    
1900  /**  /**
1901     * Will be called by the parser to mute/unmute particular sampler channel.
1902     */
1903    String LSCPServer::SetChannelMute(bool bMute, uint uiSamplerChannel) {
1904        dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));
1905        LSCPResultSet result;
1906        try {
1907            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
1908    
1909            if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);
1910            else pEngineChannel->SetMute(1);
1911        } catch (Exception e) {
1912            result.Error(e);
1913        }
1914        return result.Produce();
1915    }
1916    
1917    /**
1918     * Will be called by the parser to solo particular sampler channel.
1919     */
1920    String LSCPServer::SetChannelSolo(bool bSolo, uint uiSamplerChannel) {
1921        dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));
1922        LSCPResultSet result;
1923        try {
1924            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
1925    
1926            bool oldSolo = pEngineChannel->GetSolo();
1927            bool hadSoloChannel = HasSoloChannel();
1928    
1929            pEngineChannel->SetSolo(bSolo);
1930    
1931            if(!oldSolo && bSolo) {
1932                if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);
1933                if(!hadSoloChannel) MuteNonSoloChannels();
1934            }
1935    
1936            if(oldSolo && !bSolo) {
1937                if(!HasSoloChannel()) UnmuteChannels();
1938                else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);
1939            }
1940        } catch (Exception e) {
1941            result.Error(e);
1942        }
1943        return result.Produce();
1944    }
1945    
1946    /**
1947     * Determines whether there is at least one solo channel in the channel list.
1948     *
1949     * @returns true if there is at least one solo channel in the channel list,
1950     * false otherwise.
1951     */
1952    bool LSCPServer::HasSoloChannel() {
1953        std::map<uint,SamplerChannel*> channels = pSampler->GetSamplerChannels();
1954        std::map<uint,SamplerChannel*>::iterator iter = channels.begin();
1955        for (; iter != channels.end(); iter++) {
1956            EngineChannel* c = iter->second->GetEngineChannel();
1957            if(c && c->GetSolo()) return true;
1958        }
1959    
1960        return false;
1961    }
1962    
1963    /**
1964     * Mutes all unmuted non-solo channels. Notice that the channels are muted
1965     * with -1 which indicates that they are muted because of the presence
1966     * of a solo channel(s). Channels muted with -1 will be automatically unmuted
1967     * when there are no solo channels left.
1968     */
1969    void LSCPServer::MuteNonSoloChannels() {
1970        dmsg(2,("LSCPServer: MuteNonSoloChannels()\n"));
1971        std::map<uint,SamplerChannel*> channels = pSampler->GetSamplerChannels();
1972        std::map<uint,SamplerChannel*>::iterator iter = channels.begin();
1973        for (; iter != channels.end(); iter++) {
1974            EngineChannel* c = iter->second->GetEngineChannel();
1975            if(c && !c->GetSolo() && !c->GetMute()) c->SetMute(-1);
1976        }
1977    }
1978    
1979    /**
1980     * Unmutes all channels that are muted because of the presence
1981     * of a solo channel(s).
1982     */
1983    void  LSCPServer::UnmuteChannels() {
1984        dmsg(2,("LSCPServer: UnmuteChannels()\n"));
1985        std::map<uint,SamplerChannel*> channels = pSampler->GetSamplerChannels();
1986        std::map<uint,SamplerChannel*>::iterator iter = channels.begin();
1987        for (; iter != channels.end(); iter++) {
1988            EngineChannel* c = iter->second->GetEngineChannel();
1989            if(c && c->GetMute() == -1) c->SetMute(0);
1990        }
1991    }
1992    
1993    String LSCPServer::AddOrReplaceMIDIInstrumentMapping(uint MidiMapID, uint MidiBank, uint MidiProg, String EngineType, String InstrumentFile, uint InstrumentIndex, float Volume, MidiInstrumentMapper::mode_t LoadMode, String Name, bool bModal) {
1994        dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));
1995    
1996        midi_prog_index_t idx;
1997        idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;
1998        idx.midi_bank_lsb = MidiBank & 0x7f;
1999        idx.midi_prog     = MidiProg;
2000    
2001        MidiInstrumentMapper::entry_t entry;
2002        entry.EngineName      = EngineType;
2003        entry.InstrumentFile  = InstrumentFile;
2004        entry.InstrumentIndex = InstrumentIndex;
2005        entry.LoadMode        = LoadMode;
2006        entry.Volume          = Volume;
2007        entry.Name            = Name;
2008    
2009        LSCPResultSet result;
2010        try {
2011            // PERSISTENT mapping commands might block for a long time, so in
2012            // that case we add/replace the mapping in another thread in case
2013            // the NON_MODAL argument was supplied, non persistent mappings
2014            // should return immediately, so we don't need to do that for them
2015            bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT && !bModal);
2016            MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);
2017        } catch (Exception e) {
2018            result.Error(e);
2019        }
2020        return result.Produce();
2021    }
2022    
2023    String LSCPServer::RemoveMIDIInstrumentMapping(uint MidiMapID, uint MidiBank, uint MidiProg) {
2024        dmsg(2,("LSCPServer: RemoveMIDIInstrumentMapping()\n"));
2025    
2026        midi_prog_index_t idx;
2027        idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;
2028        idx.midi_bank_lsb = MidiBank & 0x7f;
2029        idx.midi_prog     = MidiProg;
2030    
2031        LSCPResultSet result;
2032        try {
2033            MidiInstrumentMapper::RemoveEntry(MidiMapID, idx);
2034        } catch (Exception e) {
2035            result.Error(e);
2036        }
2037        return result.Produce();
2038    }
2039    
2040    String LSCPServer::GetMidiInstrumentMappings(uint MidiMapID) {
2041        dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));
2042        LSCPResultSet result;
2043        try {
2044            result.Add(MidiInstrumentMapper::GetInstrumentCount(MidiMapID));
2045        } catch (Exception e) {
2046            result.Error(e);
2047        }
2048        return result.Produce();
2049    }
2050    
2051    
2052    String LSCPServer::GetAllMidiInstrumentMappings() {
2053        dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));
2054        LSCPResultSet result;
2055        try {
2056            result.Add(MidiInstrumentMapper::GetInstrumentCount());
2057        } catch (Exception e) {
2058            result.Error(e);
2059        }
2060        return result.Produce();
2061    }
2062    
2063    String LSCPServer::GetMidiInstrumentMapping(uint MidiMapID, uint MidiBank, uint MidiProg) {
2064        dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));
2065        LSCPResultSet result;
2066        try {
2067            MidiInstrumentMapper::entry_t entry = MidiInstrumentMapper::GetEntry(MidiMapID, MidiBank, MidiProg);
2068            // convert the filename into the correct encoding as defined for LSCP
2069            // (especially in terms of special characters -> escape sequences)
2070    #if WIN32
2071            const String instrumentFileName = Path::fromWindows(entry.InstrumentFile).toLscp();
2072    #else
2073            // assuming POSIX
2074            const String instrumentFileName = Path::fromPosix(entry.InstrumentFile).toLscp();
2075    #endif
2076    
2077            result.Add("NAME", _escapeLscpResponse(entry.Name));
2078            result.Add("ENGINE_NAME", entry.EngineName);
2079            result.Add("INSTRUMENT_FILE", instrumentFileName);
2080            result.Add("INSTRUMENT_NR", (int) entry.InstrumentIndex);
2081            String instrumentName;
2082            Engine* pEngine = EngineFactory::Create(entry.EngineName);
2083            if (pEngine) {
2084                if (pEngine->GetInstrumentManager()) {
2085                    InstrumentManager::instrument_id_t instrID;
2086                    instrID.FileName = entry.InstrumentFile;
2087                    instrID.Index    = entry.InstrumentIndex;
2088                    instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);
2089                }
2090                EngineFactory::Destroy(pEngine);
2091            }
2092            result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
2093            switch (entry.LoadMode) {
2094                case MidiInstrumentMapper::ON_DEMAND:
2095                    result.Add("LOAD_MODE", "ON_DEMAND");
2096                    break;
2097                case MidiInstrumentMapper::ON_DEMAND_HOLD:
2098                    result.Add("LOAD_MODE", "ON_DEMAND_HOLD");
2099                    break;
2100                case MidiInstrumentMapper::PERSISTENT:
2101                    result.Add("LOAD_MODE", "PERSISTENT");
2102                    break;
2103                default:
2104                    throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");
2105            }
2106            result.Add("VOLUME", entry.Volume);
2107        } catch (Exception e) {
2108            result.Error(e);
2109        }
2110        return result.Produce();
2111    }
2112    
2113    String LSCPServer::ListMidiInstrumentMappings(uint MidiMapID) {
2114        dmsg(2,("LSCPServer: ListMidiInstrumentMappings()\n"));
2115        LSCPResultSet result;
2116        try {
2117            String s;
2118            std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(MidiMapID);
2119            std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.begin();
2120            for (; iter != mappings.end(); iter++) {
2121                if (s.size()) s += ",";
2122                s += "{" + ToString(MidiMapID) + ","
2123                         + ToString((int(iter->first.midi_bank_msb) << 7) | int(iter->first.midi_bank_lsb)) + ","
2124                         + ToString(int(iter->first.midi_prog)) + "}";
2125            }
2126            result.Add(s);
2127        } catch (Exception e) {
2128            result.Error(e);
2129        }
2130        return result.Produce();
2131    }
2132    
2133    String LSCPServer::ListAllMidiInstrumentMappings() {
2134        dmsg(2,("LSCPServer: ListAllMidiInstrumentMappings()\n"));
2135        LSCPResultSet result;
2136        try {
2137            std::vector<int> maps = MidiInstrumentMapper::Maps();
2138            String s;
2139            for (int i = 0; i < maps.size(); i++) {
2140                std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(maps[i]);
2141                std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.begin();
2142                for (; iter != mappings.end(); iter++) {
2143                    if (s.size()) s += ",";
2144                    s += "{" + ToString(maps[i]) + ","
2145                             + ToString((int(iter->first.midi_bank_msb) << 7) | int(iter->first.midi_bank_lsb)) + ","
2146                             + ToString(int(iter->first.midi_prog)) + "}";
2147                }
2148            }
2149            result.Add(s);
2150        } catch (Exception e) {
2151            result.Error(e);
2152        }
2153        return result.Produce();
2154    }
2155    
2156    String LSCPServer::ClearMidiInstrumentMappings(uint MidiMapID) {
2157        dmsg(2,("LSCPServer: ClearMidiInstrumentMappings()\n"));
2158        LSCPResultSet result;
2159        try {
2160            MidiInstrumentMapper::RemoveAllEntries(MidiMapID);
2161        } catch (Exception e) {
2162            result.Error(e);
2163        }
2164        return result.Produce();
2165    }
2166    
2167    String LSCPServer::ClearAllMidiInstrumentMappings() {
2168        dmsg(2,("LSCPServer: ClearAllMidiInstrumentMappings()\n"));
2169        LSCPResultSet result;
2170        try {
2171            std::vector<int> maps = MidiInstrumentMapper::Maps();
2172            for (int i = 0; i < maps.size(); i++)
2173                MidiInstrumentMapper::RemoveAllEntries(maps[i]);
2174        } catch (Exception e) {
2175            result.Error(e);
2176        }
2177        return result.Produce();
2178    }
2179    
2180    String LSCPServer::AddMidiInstrumentMap(String MapName) {
2181        dmsg(2,("LSCPServer: AddMidiInstrumentMap()\n"));
2182        LSCPResultSet result;
2183        try {
2184            int MapID = MidiInstrumentMapper::AddMap(MapName);
2185            result = LSCPResultSet(MapID);
2186        } catch (Exception e) {
2187            result.Error(e);
2188        }
2189        return result.Produce();
2190    }
2191    
2192    String LSCPServer::RemoveMidiInstrumentMap(uint MidiMapID) {
2193        dmsg(2,("LSCPServer: RemoveMidiInstrumentMap()\n"));
2194        LSCPResultSet result;
2195        try {
2196            MidiInstrumentMapper::RemoveMap(MidiMapID);
2197        } catch (Exception e) {
2198            result.Error(e);
2199        }
2200        return result.Produce();
2201    }
2202    
2203    String LSCPServer::RemoveAllMidiInstrumentMaps() {
2204        dmsg(2,("LSCPServer: RemoveAllMidiInstrumentMaps()\n"));
2205        LSCPResultSet result;
2206        try {
2207            MidiInstrumentMapper::RemoveAllMaps();
2208        } catch (Exception e) {
2209            result.Error(e);
2210        }
2211        return result.Produce();
2212    }
2213    
2214    String LSCPServer::GetMidiInstrumentMaps() {
2215        dmsg(2,("LSCPServer: GetMidiInstrumentMaps()\n"));
2216        LSCPResultSet result;
2217        try {
2218            result.Add(MidiInstrumentMapper::Maps().size());
2219        } catch (Exception e) {
2220            result.Error(e);
2221        }
2222        return result.Produce();
2223    }
2224    
2225    String LSCPServer::ListMidiInstrumentMaps() {
2226        dmsg(2,("LSCPServer: ListMidiInstrumentMaps()\n"));
2227        LSCPResultSet result;
2228        try {
2229            std::vector<int> maps = MidiInstrumentMapper::Maps();
2230            String sList;
2231            for (int i = 0; i < maps.size(); i++) {
2232                if (sList != "") sList += ",";
2233                sList += ToString(maps[i]);
2234            }
2235            result.Add(sList);
2236        } catch (Exception e) {
2237            result.Error(e);
2238        }
2239        return result.Produce();
2240    }
2241    
2242    String LSCPServer::GetMidiInstrumentMap(uint MidiMapID) {
2243        dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2244        LSCPResultSet result;
2245        try {
2246            result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2247            result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2248        } catch (Exception e) {
2249            result.Error(e);
2250        }
2251        return result.Produce();
2252    }
2253    
2254    String LSCPServer::SetMidiInstrumentMapName(uint MidiMapID, String NewName) {
2255        dmsg(2,("LSCPServer: SetMidiInstrumentMapName()\n"));
2256        LSCPResultSet result;
2257        try {
2258            MidiInstrumentMapper::RenameMap(MidiMapID, NewName);
2259        } catch (Exception e) {
2260            result.Error(e);
2261        }
2262        return result.Produce();
2263    }
2264    
2265    /**
2266     * Set the MIDI instrument map the given sampler channel shall use for
2267     * handling MIDI program change messages. There are the following two
2268     * special (negative) values:
2269     *
2270     *    - (-1) :  set to NONE (ignore program changes)
2271     *    - (-2) :  set to DEFAULT map
2272     */
2273    String LSCPServer::SetChannelMap(uint uiSamplerChannel, int MidiMapID) {
2274        dmsg(2,("LSCPServer: SetChannelMap()\n"));
2275        LSCPResultSet result;
2276        try {
2277            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2278    
2279            if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();
2280            else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();
2281            else                      pEngineChannel->SetMidiInstrumentMap(MidiMapID);
2282        } catch (Exception e) {
2283            result.Error(e);
2284        }
2285        return result.Produce();
2286    }
2287    
2288    String LSCPServer::CreateFxSend(uint uiSamplerChannel, uint MidiCtrl, String Name) {
2289        dmsg(2,("LSCPServer: CreateFxSend()\n"));
2290        LSCPResultSet result;
2291        try {
2292            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2293    
2294            FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2295            if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");
2296    
2297            result = LSCPResultSet(pFxSend->Id()); // success
2298        } catch (Exception e) {
2299            result.Error(e);
2300        }
2301        return result.Produce();
2302    }
2303    
2304    String LSCPServer::DestroyFxSend(uint uiSamplerChannel, uint FxSendID) {
2305        dmsg(2,("LSCPServer: DestroyFxSend()\n"));
2306        LSCPResultSet result;
2307        try {
2308            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2309    
2310            FxSend* pFxSend = NULL;
2311            for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2312                if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2313                    pFxSend = pEngineChannel->GetFxSend(i);
2314                    break;
2315                }
2316            }
2317            if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2318            pEngineChannel->RemoveFxSend(pFxSend);
2319        } catch (Exception e) {
2320            result.Error(e);
2321        }
2322        return result.Produce();
2323    }
2324    
2325    String LSCPServer::GetFxSends(uint uiSamplerChannel) {
2326        dmsg(2,("LSCPServer: GetFxSends()\n"));
2327        LSCPResultSet result;
2328        try {
2329            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2330    
2331            result.Add(pEngineChannel->GetFxSendCount());
2332        } catch (Exception e) {
2333            result.Error(e);
2334        }
2335        return result.Produce();
2336    }
2337    
2338    String LSCPServer::ListFxSends(uint uiSamplerChannel) {
2339        dmsg(2,("LSCPServer: ListFxSends()\n"));
2340        LSCPResultSet result;
2341        String list;
2342        try {
2343            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2344    
2345            for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2346                FxSend* pFxSend = pEngineChannel->GetFxSend(i);
2347                if (list != "") list += ",";
2348                list += ToString(pFxSend->Id());
2349            }
2350            result.Add(list);
2351        } catch (Exception e) {
2352            result.Error(e);
2353        }
2354        return result.Produce();
2355    }
2356    
2357    FxSend* LSCPServer::GetFxSend(uint uiSamplerChannel, uint FxSendID) {
2358        EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2359    
2360        FxSend* pFxSend = NULL;
2361        for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2362            if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2363                pFxSend = pEngineChannel->GetFxSend(i);
2364                break;
2365            }
2366        }
2367        if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2368        return pFxSend;
2369    }
2370    
2371    String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {
2372        dmsg(2,("LSCPServer: GetFxSendInfo()\n"));
2373        LSCPResultSet result;
2374        try {
2375            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2376            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2377    
2378            // gather audio routing informations
2379            String AudioRouting;
2380            for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {
2381                if (AudioRouting != "") AudioRouting += ",";
2382                AudioRouting += ToString(pFxSend->DestinationChannel(chan));
2383            }
2384    
2385            // success
2386            result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2387            result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2388            result.Add("LEVEL", ToString(pFxSend->Level()));
2389            result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
2390        } catch (Exception e) {
2391            result.Error(e);
2392        }
2393        return result.Produce();
2394    }
2395    
2396    String LSCPServer::SetFxSendName(uint uiSamplerChannel, uint FxSendID, String Name) {
2397        dmsg(2,("LSCPServer: SetFxSendName()\n"));
2398        LSCPResultSet result;
2399        try {
2400            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2401    
2402            pFxSend->SetName(Name);
2403            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2404        } catch (Exception e) {
2405            result.Error(e);
2406        }
2407        return result.Produce();
2408    }
2409    
2410    String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {
2411        dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));
2412        LSCPResultSet result;
2413        try {
2414            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2415    
2416            pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);
2417            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2418        } catch (Exception e) {
2419            result.Error(e);
2420        }
2421        return result.Produce();
2422    }
2423    
2424    String LSCPServer::SetFxSendMidiController(uint uiSamplerChannel, uint FxSendID, uint MidiController) {
2425        dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));
2426        LSCPResultSet result;
2427        try {
2428            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2429    
2430            pFxSend->SetMidiController(MidiController);
2431            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2432        } catch (Exception e) {
2433            result.Error(e);
2434        }
2435        return result.Produce();
2436    }
2437    
2438    String LSCPServer::SetFxSendLevel(uint uiSamplerChannel, uint FxSendID, double dLevel) {
2439        dmsg(2,("LSCPServer: SetFxSendLevel()\n"));
2440        LSCPResultSet result;
2441        try {
2442            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2443    
2444            pFxSend->SetLevel((float)dLevel);
2445            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2446        } catch (Exception e) {
2447            result.Error(e);
2448        }
2449        return result.Produce();
2450    }
2451    
2452    String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2453        dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2454        LSCPResultSet result;
2455        try {
2456            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2457            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2458            Engine* pEngine = pEngineChannel->GetEngine();
2459            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2460            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2461            InstrumentManager::instrument_id_t instrumentID;
2462            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2463            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2464            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2465        } catch (Exception e) {
2466            result.Error(e);
2467        }
2468        return result.Produce();
2469    }
2470    
2471    String LSCPServer::SendChannelMidiData(String MidiMsg, uint uiSamplerChannel, uint Arg1, uint Arg2) {
2472        dmsg(2,("LSCPServer: SendChannelMidiData(MidiMsg=%s,uiSamplerChannel=%d,Arg1=%d,Arg2=%d)\n", MidiMsg.c_str(), uiSamplerChannel, Arg1, Arg2));
2473        LSCPResultSet result;
2474        try {
2475            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2476    
2477            if (Arg1 > 127 || Arg2 > 127) {
2478                throw Exception("Invalid MIDI message");
2479            }
2480    
2481            VirtualMidiDevice* pMidiDevice = NULL;
2482            std::vector<EventHandler::midi_listener_entry>::iterator iter = eventHandler.channelMidiListeners.begin();
2483            for (; iter != eventHandler.channelMidiListeners.end(); ++iter) {
2484                if ((*iter).pEngineChannel == pEngineChannel) {
2485                    pMidiDevice = (*iter).pMidiListener;
2486                    break;
2487                }
2488            }
2489            
2490            if(pMidiDevice == NULL) throw Exception("Couldn't find virtual MIDI device");
2491    
2492            if (MidiMsg == "NOTE_ON") {
2493                pMidiDevice->SendNoteOnToDevice(Arg1, Arg2);
2494                bool b = pMidiDevice->SendNoteOnToSampler(Arg1, Arg2);
2495                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2496            } else if (MidiMsg == "NOTE_OFF") {
2497                pMidiDevice->SendNoteOffToDevice(Arg1, Arg2);
2498                bool b = pMidiDevice->SendNoteOffToSampler(Arg1, Arg2);
2499                if (!b) throw Exception("MIDI event failed: " + MidiMsg + " " + ToString(Arg1) + " " + ToString(Arg2));
2500            } else {
2501                throw Exception("Unknown MIDI message type: " + MidiMsg);
2502            }
2503        } catch (Exception e) {
2504            result.Error(e);
2505        }
2506        return result.Produce();
2507    }
2508    
2509    /**
2510   * Will be called by the parser to reset a particular sampler channel.   * Will be called by the parser to reset a particular sampler channel.
2511   */   */
2512  String LSCPServer::ResetChannel(uint uiSamplerChannel) {  String LSCPServer::ResetChannel(uint uiSamplerChannel) {
2513      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: ResetChannel(SamplerChannel=%d)\n", uiSamplerChannel));
2514      LSCPResultSet result;      LSCPResultSet result;
2515      try {      try {
2516          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2517          if (!pSamplerChannel) throw LinuxSamplerException("Invalid sampler channel number " + ToString(uiSamplerChannel));          pEngineChannel->Reset();
         Engine* pEngine = pSamplerChannel->GetEngine();  
         if (!pEngine) throw LinuxSamplerException("No engine loaded on sampler channel");  
         pEngine->Reset();  
2518      }      }
2519      catch (LinuxSamplerException e) {      catch (Exception e) {
2520           result.Error(e);           result.Error(e);
2521      }      }
2522      return result.Produce();      return result.Produce();
# Line 1373  String LSCPServer::ResetSampler() { Line 2533  String LSCPServer::ResetSampler() {
2533  }  }
2534    
2535  /**  /**
2536     * Will be called by the parser to return general informations about this
2537     * sampler.
2538     */
2539    String LSCPServer::GetServerInfo() {
2540        dmsg(2,("LSCPServer: GetServerInfo()\n"));
2541        const std::string description =
2542            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2543        LSCPResultSet result;
2544        result.Add("DESCRIPTION", description);
2545        result.Add("VERSION", VERSION);
2546        result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2547    #if HAVE_SQLITE3
2548        result.Add("INSTRUMENTS_DB_SUPPORT", "yes");
2549    #else
2550        result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2551    #endif
2552    
2553        return result.Produce();
2554    }
2555    
2556    /**
2557     * Will be called by the parser to return the current number of all active streams.
2558     */
2559    String LSCPServer::GetTotalStreamCount() {
2560        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2561        LSCPResultSet result;
2562        result.Add(pSampler->GetDiskStreamCount());
2563        return result.Produce();
2564    }
2565    
2566    /**
2567     * Will be called by the parser to return the current number of all active voices.
2568     */
2569    String LSCPServer::GetTotalVoiceCount() {
2570        dmsg(2,("LSCPServer: GetTotalVoiceCount()\n"));
2571        LSCPResultSet result;
2572        result.Add(pSampler->GetVoiceCount());
2573        return result.Produce();
2574    }
2575    
2576    /**
2577     * Will be called by the parser to return the maximum number of voices.
2578     */
2579    String LSCPServer::GetTotalVoiceCountMax() {
2580        dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));
2581        LSCPResultSet result;
2582        result.Add(EngineFactory::EngineInstances().size() * GLOBAL_MAX_VOICES);
2583        return result.Produce();
2584    }
2585    
2586    /**
2587     * Will be called by the parser to return the sampler global maximum
2588     * allowed number of voices.
2589     */
2590    String LSCPServer::GetGlobalMaxVoices() {
2591        dmsg(2,("LSCPServer: GetGlobalMaxVoices()\n"));
2592        LSCPResultSet result;
2593        result.Add(GLOBAL_MAX_VOICES);
2594        return result.Produce();
2595    }
2596    
2597    /**
2598     * Will be called by the parser to set the sampler global maximum number of
2599     * voices.
2600     */
2601    String LSCPServer::SetGlobalMaxVoices(int iVoices) {
2602        dmsg(2,("LSCPServer: SetGlobalMaxVoices(%d)\n", iVoices));
2603        LSCPResultSet result;
2604        try {
2605            if (iVoices < 1) throw Exception("Maximum voices may not be less than 1");
2606            GLOBAL_MAX_VOICES = iVoices; // see common/global_private.cpp
2607            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
2608            if (engines.size() > 0) {
2609                std::set<Engine*>::iterator iter = engines.begin();
2610                std::set<Engine*>::iterator end  = engines.end();
2611                for (; iter != end; ++iter) {
2612                    (*iter)->SetMaxVoices(iVoices);
2613                }
2614            }
2615            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOICES", GLOBAL_MAX_VOICES));
2616        } catch (Exception e) {
2617            result.Error(e);
2618        }
2619        return result.Produce();
2620    }
2621    
2622    /**
2623     * Will be called by the parser to return the sampler global maximum
2624     * allowed number of disk streams.
2625     */
2626    String LSCPServer::GetGlobalMaxStreams() {
2627        dmsg(2,("LSCPServer: GetGlobalMaxStreams()\n"));
2628        LSCPResultSet result;
2629        result.Add(GLOBAL_MAX_STREAMS);
2630        return result.Produce();
2631    }
2632    
2633    /**
2634     * Will be called by the parser to set the sampler global maximum number of
2635     * disk streams.
2636     */
2637    String LSCPServer::SetGlobalMaxStreams(int iStreams) {
2638        dmsg(2,("LSCPServer: SetGlobalMaxStreams(%d)\n", iStreams));
2639        LSCPResultSet result;
2640        try {
2641            if (iStreams < 0) throw Exception("Maximum disk streams may not be negative");
2642            GLOBAL_MAX_STREAMS = iStreams; // see common/global_private.cpp
2643            const std::set<Engine*>& engines = EngineFactory::EngineInstances();
2644            if (engines.size() > 0) {
2645                std::set<Engine*>::iterator iter = engines.begin();
2646                std::set<Engine*>::iterator end  = engines.end();
2647                for (; iter != end; ++iter) {
2648                    (*iter)->SetMaxDiskStreams(iStreams);
2649                }
2650            }
2651            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "STREAMS", GLOBAL_MAX_STREAMS));
2652        } catch (Exception e) {
2653            result.Error(e);
2654        }
2655        return result.Produce();
2656    }
2657    
2658    String LSCPServer::GetGlobalVolume() {
2659        LSCPResultSet result;
2660        result.Add(ToString(GLOBAL_VOLUME)); // see common/global.cpp
2661        return result.Produce();
2662    }
2663    
2664    String LSCPServer::SetGlobalVolume(double dVolume) {
2665        LSCPResultSet result;
2666        try {
2667            if (dVolume < 0) throw Exception("Volume may not be negative");
2668            GLOBAL_VOLUME = dVolume; // see common/global_private.cpp
2669            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
2670        } catch (Exception e) {
2671            result.Error(e);
2672        }
2673        return result.Produce();
2674    }
2675    
2676    String LSCPServer::GetFileInstruments(String Filename) {
2677        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2678        LSCPResultSet result;
2679        try {
2680            VerifyFile(Filename);
2681        } catch (Exception e) {
2682            result.Error(e);
2683            return result.Produce();
2684        }
2685        // try to find a sampler engine that can handle the file
2686        bool bFound = false;
2687        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2688        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2689            Engine* pEngine = NULL;
2690            try {
2691                pEngine = EngineFactory::Create(engineTypes[i]);
2692                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2693                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2694                if (pManager) {
2695                    std::vector<InstrumentManager::instrument_id_t> IDs =
2696                        pManager->GetInstrumentFileContent(Filename);
2697                    // return the amount of instruments in the file
2698                    result.Add(IDs.size());
2699                    // no more need to ask other engine types
2700                    bFound = true;
2701                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2702            } catch (Exception e) {
2703                // NOOP, as exception is thrown if engine doesn't support file
2704            }
2705            if (pEngine) EngineFactory::Destroy(pEngine);
2706        }
2707    
2708        if (!bFound) result.Error("Unknown file format");
2709        return result.Produce();
2710    }
2711    
2712    String LSCPServer::ListFileInstruments(String Filename) {
2713        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2714        LSCPResultSet result;
2715        try {
2716            VerifyFile(Filename);
2717        } catch (Exception e) {
2718            result.Error(e);
2719            return result.Produce();
2720        }
2721        // try to find a sampler engine that can handle the file
2722        bool bFound = false;
2723        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2724        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2725            Engine* pEngine = NULL;
2726            try {
2727                pEngine = EngineFactory::Create(engineTypes[i]);
2728                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2729                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2730                if (pManager) {
2731                    std::vector<InstrumentManager::instrument_id_t> IDs =
2732                        pManager->GetInstrumentFileContent(Filename);
2733                    // return a list of IDs of the instruments in the file
2734                    String s;
2735                    for (int j = 0; j < IDs.size(); j++) {
2736                        if (s.size()) s += ",";
2737                        s += ToString(IDs[j].Index);
2738                    }
2739                    result.Add(s);
2740                    // no more need to ask other engine types
2741                    bFound = true;
2742                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2743            } catch (Exception e) {
2744                // NOOP, as exception is thrown if engine doesn't support file
2745            }
2746            if (pEngine) EngineFactory::Destroy(pEngine);
2747        }
2748    
2749        if (!bFound) result.Error("Unknown file format");
2750        return result.Produce();
2751    }
2752    
2753    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2754        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2755        LSCPResultSet result;
2756        try {
2757            VerifyFile(Filename);
2758        } catch (Exception e) {
2759            result.Error(e);
2760            return result.Produce();
2761        }
2762        InstrumentManager::instrument_id_t id;
2763        id.FileName = Filename;
2764        id.Index    = InstrumentID;
2765        // try to find a sampler engine that can handle the file
2766        bool bFound = false;
2767        bool bFatalErr = false;
2768        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2769        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2770            Engine* pEngine = NULL;
2771            try {
2772                pEngine = EngineFactory::Create(engineTypes[i]);
2773                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2774                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2775                if (pManager) {
2776                    // check if the instrument index is valid
2777                    // FIXME: this won't work if an engine only supports parts of the instrument file
2778                    std::vector<InstrumentManager::instrument_id_t> IDs =
2779                        pManager->GetInstrumentFileContent(Filename);
2780                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2781                        std::stringstream ss;
2782                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2783                        bFatalErr = true;
2784                        throw Exception(ss.str());
2785                    }
2786                    // get the info of the requested instrument
2787                    InstrumentManager::instrument_info_t info =
2788                        pManager->GetInstrumentInfo(id);
2789                    // return detailed informations about the file
2790                    result.Add("NAME", info.InstrumentName);
2791                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2792                    result.Add("FORMAT_VERSION", info.FormatVersion);
2793                    result.Add("PRODUCT", info.Product);
2794                    result.Add("ARTISTS", info.Artists);
2795    
2796                    std::stringstream ss;
2797                    bool b = false;
2798                    for (int i = 0; i < 128; i++) {
2799                        if (info.KeyBindings[i]) {
2800                            if (b) ss << ',';
2801                            ss << i; b = true;
2802                        }
2803                    }
2804                    result.Add("KEY_BINDINGS", ss.str());
2805    
2806                    b = false;
2807                    std::stringstream ss2;
2808                    for (int i = 0; i < 128; i++) {
2809                        if (info.KeySwitchBindings[i]) {
2810                            if (b) ss2 << ',';
2811                            ss2 << i; b = true;
2812                        }
2813                    }
2814                    result.Add("KEYSWITCH_BINDINGS", ss2.str());
2815                    // no more need to ask other engine types
2816                    bFound = true;
2817                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2818            } catch (Exception e) {
2819                // usually NOOP, as exception is thrown if engine doesn't support file
2820                if (bFatalErr) result.Error(e);
2821            }
2822            if (pEngine) EngineFactory::Destroy(pEngine);
2823        }
2824    
2825        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2826        return result.Produce();
2827    }
2828    
2829    void LSCPServer::VerifyFile(String Filename) {
2830        #if WIN32
2831        WIN32_FIND_DATA win32FileAttributeData;
2832        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2833        if (!res) {
2834            std::stringstream ss;
2835            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2836            throw Exception(ss.str());
2837        }
2838        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2839            throw Exception("Directory is specified");
2840        }
2841        #else
2842        File f(Filename);
2843        if(!f.Exist()) throw Exception(f.GetErrorMsg());
2844        if (f.IsDirectory()) throw Exception("Directory is specified");
2845        #endif
2846    }
2847    
2848    /**
2849   * 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
2850   * server for receiving event messages.   * server for receiving event messages.
2851   */   */
# Line 1398  String LSCPServer::UnsubscribeNotificati Line 2871  String LSCPServer::UnsubscribeNotificati
2871      return result.Produce();      return result.Produce();
2872  }  }
2873    
2874  static int select_callback(void * lscpResultSet, int argc,  String LSCPServer::AddDbInstrumentDirectory(String Dir) {
2875                          char **argv, char **azColName)      dmsg(2,("LSCPServer: AddDbInstrumentDirectory(Dir=%s)\n", Dir.c_str()));
2876  {      LSCPResultSet result;
2877      LSCPResultSet* resultSet = (LSCPResultSet*) lscpResultSet;  #if HAVE_SQLITE3
2878      resultSet->Add(argc, argv);      try {
2879      return 0;          InstrumentsDb::GetInstrumentsDb()->AddDirectory(Dir);
2880        } catch (Exception e) {
2881             result.Error(e);
2882        }
2883    #else
2884        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2885    #endif
2886        return result.Produce();
2887    }
2888    
2889    String LSCPServer::RemoveDbInstrumentDirectory(String Dir, bool Force) {
2890        dmsg(2,("LSCPServer: RemoveDbInstrumentDirectory(Dir=%s,Force=%d)\n", Dir.c_str(), Force));
2891        LSCPResultSet result;
2892    #if HAVE_SQLITE3
2893        try {
2894            InstrumentsDb::GetInstrumentsDb()->RemoveDirectory(Dir, Force);
2895        } catch (Exception e) {
2896             result.Error(e);
2897        }
2898    #else
2899        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2900    #endif
2901        return result.Produce();
2902    }
2903    
2904    String LSCPServer::GetDbInstrumentDirectoryCount(String Dir, bool Recursive) {
2905        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2906        LSCPResultSet result;
2907    #if HAVE_SQLITE3
2908        try {
2909            result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir, Recursive));
2910        } catch (Exception e) {
2911             result.Error(e);
2912        }
2913    #else
2914        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2915    #endif
2916        return result.Produce();
2917    }
2918    
2919    String LSCPServer::GetDbInstrumentDirectories(String Dir, bool Recursive) {
2920        dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2921        LSCPResultSet result;
2922    #if HAVE_SQLITE3
2923        try {
2924            String list;
2925            StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir, Recursive);
2926    
2927            for (int i = 0; i < dirs->size(); i++) {
2928                if (list != "") list += ",";
2929                list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2930            }
2931    
2932            result.Add(list);
2933        } catch (Exception e) {
2934             result.Error(e);
2935        }
2936    #else
2937        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2938    #endif
2939        return result.Produce();
2940    }
2941    
2942    String LSCPServer::GetDbInstrumentDirectoryInfo(String Dir) {
2943        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryInfo(Dir=%s)\n", Dir.c_str()));
2944        LSCPResultSet result;
2945    #if HAVE_SQLITE3
2946        try {
2947            DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2948    
2949            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2950            result.Add("CREATED", info.Created);
2951            result.Add("MODIFIED", info.Modified);
2952        } catch (Exception e) {
2953             result.Error(e);
2954        }
2955    #else
2956        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2957    #endif
2958        return result.Produce();
2959    }
2960    
2961    String LSCPServer::SetDbInstrumentDirectoryName(String Dir, String Name) {
2962        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryName(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
2963        LSCPResultSet result;
2964    #if HAVE_SQLITE3
2965        try {
2966            InstrumentsDb::GetInstrumentsDb()->RenameDirectory(Dir, Name);
2967        } catch (Exception e) {
2968             result.Error(e);
2969        }
2970    #else
2971        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2972    #endif
2973        return result.Produce();
2974    }
2975    
2976    String LSCPServer::MoveDbInstrumentDirectory(String Dir, String Dst) {
2977        dmsg(2,("LSCPServer: MoveDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2978        LSCPResultSet result;
2979    #if HAVE_SQLITE3
2980        try {
2981            InstrumentsDb::GetInstrumentsDb()->MoveDirectory(Dir, Dst);
2982        } catch (Exception e) {
2983             result.Error(e);
2984        }
2985    #else
2986        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2987    #endif
2988        return result.Produce();
2989    }
2990    
2991    String LSCPServer::CopyDbInstrumentDirectory(String Dir, String Dst) {
2992        dmsg(2,("LSCPServer: CopyDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2993        LSCPResultSet result;
2994    #if HAVE_SQLITE3
2995        try {
2996            InstrumentsDb::GetInstrumentsDb()->CopyDirectory(Dir, Dst);
2997        } catch (Exception e) {
2998             result.Error(e);
2999        }
3000    #else
3001        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3002    #endif
3003        return result.Produce();
3004    }
3005    
3006    String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {
3007        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
3008        LSCPResultSet result;
3009    #if HAVE_SQLITE3
3010        try {
3011            InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);
3012        } catch (Exception e) {
3013             result.Error(e);
3014        }
3015    #else
3016        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3017    #endif
3018        return result.Produce();
3019    }
3020    
3021    String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
3022        dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
3023        LSCPResultSet result;
3024    #if HAVE_SQLITE3
3025        try {
3026            int id;
3027            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
3028            id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
3029            if (bBackground) result = id;
3030        } catch (Exception e) {
3031             result.Error(e);
3032        }
3033    #else
3034        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3035    #endif
3036        return result.Produce();
3037    }
3038    
3039    String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground, bool insDir) {
3040        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));
3041        LSCPResultSet result;
3042    #if HAVE_SQLITE3
3043        try {
3044            int id;
3045            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
3046            if (ScanMode.compare("RECURSIVE") == 0) {
3047                id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground, insDir);
3048            } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
3049                id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground, insDir);
3050            } else if (ScanMode.compare("FLAT") == 0) {
3051                id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground, insDir);
3052            } else {
3053                throw Exception("Unknown scan mode: " + ScanMode);
3054            }
3055    
3056            if (bBackground) result = id;
3057        } catch (Exception e) {
3058             result.Error(e);
3059        }
3060    #else
3061        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3062    #endif
3063        return result.Produce();
3064    }
3065    
3066    String LSCPServer::RemoveDbInstrument(String Instr) {
3067        dmsg(2,("LSCPServer: RemoveDbInstrument(Instr=%s)\n", Instr.c_str()));
3068        LSCPResultSet result;
3069    #if HAVE_SQLITE3
3070        try {
3071            InstrumentsDb::GetInstrumentsDb()->RemoveInstrument(Instr);
3072        } catch (Exception e) {
3073             result.Error(e);
3074        }
3075    #else
3076        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3077    #endif
3078        return result.Produce();
3079    }
3080    
3081    String LSCPServer::GetDbInstrumentCount(String Dir, bool Recursive) {
3082        dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
3083        LSCPResultSet result;
3084    #if HAVE_SQLITE3
3085        try {
3086            result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir, Recursive));
3087        } catch (Exception e) {
3088             result.Error(e);
3089        }
3090    #else
3091        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3092    #endif
3093        return result.Produce();
3094  }  }
3095    
3096  String LSCPServer::QueryDatabase(String query) {  String LSCPServer::GetDbInstruments(String Dir, bool Recursive) {
3097        dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
3098      LSCPResultSet result;      LSCPResultSet result;
3099  #ifdef HAVE_SQLITE3  #if HAVE_SQLITE3
3100      char* zErrMsg = NULL;      try {
3101      sqlite3 *db;          String list;
3102      String selectStr = "SELECT " + query;          StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir, Recursive);
3103    
3104      int rc = sqlite3_open("linuxsampler.db", &db);          for (int i = 0; i < instrs->size(); i++) {
3105      if (rc == SQLITE_OK)              if (list != "") list += ",";
3106      {              list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
3107              rc = sqlite3_exec(db, selectStr.c_str(), select_callback, &result, &zErrMsg);          }
3108    
3109            result.Add(list);
3110        } catch (Exception e) {
3111             result.Error(e);
3112      }      }
3113      if ( rc != SQLITE_OK )  #else
3114      {      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3115              //result.Error(String(zErrMsg), rc);  #endif
3116              result.Error(selectStr, 666);      return result.Produce();
3117    }
3118    
3119    String LSCPServer::GetDbInstrumentInfo(String Instr) {
3120        dmsg(2,("LSCPServer: GetDbInstrumentInfo(Instr=%s)\n", Instr.c_str()));
3121        LSCPResultSet result;
3122    #if HAVE_SQLITE3
3123        try {
3124            DbInstrument info = InstrumentsDb::GetInstrumentsDb()->GetInstrumentInfo(Instr);
3125    
3126            result.Add("INSTRUMENT_FILE", info.InstrFile);
3127            result.Add("INSTRUMENT_NR", info.InstrNr);
3128            result.Add("FORMAT_FAMILY", info.FormatFamily);
3129            result.Add("FORMAT_VERSION", info.FormatVersion);
3130            result.Add("SIZE", (int)info.Size);
3131            result.Add("CREATED", info.Created);
3132            result.Add("MODIFIED", info.Modified);
3133            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
3134            result.Add("IS_DRUM", info.IsDrum);
3135            result.Add("PRODUCT", _escapeLscpResponse(info.Product));
3136            result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
3137            result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
3138        } catch (Exception e) {
3139             result.Error(e);
3140      }      }
     sqlite3_close(db);  
3141  #else  #else
3142      result.Error(String("SQLITE3 was not installed when linuxsampler was built. SELECT statement is not available."), 0);      result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3143  #endif  #endif
3144      return result.Produce();      return result.Produce();
3145  }  }
3146    
3147    String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
3148        dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
3149        LSCPResultSet result;
3150    #if HAVE_SQLITE3
3151        try {
3152            ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
3153    
3154            result.Add("FILES_TOTAL", job.FilesTotal);
3155            result.Add("FILES_SCANNED", job.FilesScanned);
3156            result.Add("SCANNING", job.Scanning);
3157            result.Add("STATUS", job.Status);
3158        } catch (Exception e) {
3159             result.Error(e);
3160        }
3161    #else
3162        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3163    #endif
3164        return result.Produce();
3165    }
3166    
3167    String LSCPServer::SetDbInstrumentName(String Instr, String Name) {
3168        dmsg(2,("LSCPServer: SetDbInstrumentName(Instr=%s,Name=%s)\n", Instr.c_str(), Name.c_str()));
3169        LSCPResultSet result;
3170    #if HAVE_SQLITE3
3171        try {
3172            InstrumentsDb::GetInstrumentsDb()->RenameInstrument(Instr, Name);
3173        } catch (Exception e) {
3174             result.Error(e);
3175        }
3176    #else
3177        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3178    #endif
3179        return result.Produce();
3180    }
3181    
3182    String LSCPServer::MoveDbInstrument(String Instr, String Dst) {
3183        dmsg(2,("LSCPServer: MoveDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3184        LSCPResultSet result;
3185    #if HAVE_SQLITE3
3186        try {
3187            InstrumentsDb::GetInstrumentsDb()->MoveInstrument(Instr, Dst);
3188        } catch (Exception e) {
3189             result.Error(e);
3190        }
3191    #else
3192        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3193    #endif
3194        return result.Produce();
3195    }
3196    
3197    String LSCPServer::CopyDbInstrument(String Instr, String Dst) {
3198        dmsg(2,("LSCPServer: CopyDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3199        LSCPResultSet result;
3200    #if HAVE_SQLITE3
3201        try {
3202            InstrumentsDb::GetInstrumentsDb()->CopyInstrument(Instr, Dst);
3203        } catch (Exception e) {
3204             result.Error(e);
3205        }
3206    #else
3207        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3208    #endif
3209        return result.Produce();
3210    }
3211    
3212    String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {
3213        dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
3214        LSCPResultSet result;
3215    #if HAVE_SQLITE3
3216        try {
3217            InstrumentsDb::GetInstrumentsDb()->SetInstrumentDescription(Instr, Desc);
3218        } catch (Exception e) {
3219             result.Error(e);
3220        }
3221    #else
3222        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3223    #endif
3224        return result.Produce();
3225    }
3226    
3227    String LSCPServer::SetDbInstrumentFilePath(String OldPath, String NewPath) {
3228        dmsg(2,("LSCPServer: SetDbInstrumentFilePath(OldPath=%s,NewPath=%s)\n", OldPath.c_str(), NewPath.c_str()));
3229        LSCPResultSet result;
3230    #if HAVE_SQLITE3
3231        try {
3232            InstrumentsDb::GetInstrumentsDb()->SetInstrumentFilePath(OldPath, NewPath);
3233        } catch (Exception e) {
3234             result.Error(e);
3235        }
3236    #else
3237        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3238    #endif
3239        return result.Produce();
3240    }
3241    
3242    String LSCPServer::FindLostDbInstrumentFiles() {
3243        dmsg(2,("LSCPServer: FindLostDbInstrumentFiles()\n"));
3244        LSCPResultSet result;
3245    #if HAVE_SQLITE3
3246        try {
3247            String list;
3248            StringListPtr pLostFiles = InstrumentsDb::GetInstrumentsDb()->FindLostInstrumentFiles();
3249    
3250            for (int i = 0; i < pLostFiles->size(); i++) {
3251                if (list != "") list += ",";
3252                list += "'" + pLostFiles->at(i) + "'";
3253            }
3254    
3255            result.Add(list);
3256        } catch (Exception e) {
3257             result.Error(e);
3258        }
3259    #else
3260        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3261    #endif
3262        return result.Produce();
3263    }
3264    
3265    String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
3266        dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
3267        LSCPResultSet result;
3268    #if HAVE_SQLITE3
3269        try {
3270            SearchQuery Query;
3271            std::map<String,String>::iterator iter;
3272            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3273                if (iter->first.compare("NAME") == 0) {
3274                    Query.Name = iter->second;
3275                } else if (iter->first.compare("CREATED") == 0) {
3276                    Query.SetCreated(iter->second);
3277                } else if (iter->first.compare("MODIFIED") == 0) {
3278                    Query.SetModified(iter->second);
3279                } else if (iter->first.compare("DESCRIPTION") == 0) {
3280                    Query.Description = iter->second;
3281                } else {
3282                    throw Exception("Unknown search criteria: " + iter->first);
3283                }
3284            }
3285    
3286            String list;
3287            StringListPtr pDirectories =
3288                InstrumentsDb::GetInstrumentsDb()->FindDirectories(Dir, &Query, Recursive);
3289    
3290            for (int i = 0; i < pDirectories->size(); i++) {
3291                if (list != "") list += ",";
3292                list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
3293            }
3294    
3295            result.Add(list);
3296        } catch (Exception e) {
3297             result.Error(e);
3298        }
3299    #else
3300        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3301    #endif
3302        return result.Produce();
3303    }
3304    
3305    String LSCPServer::FindDbInstruments(String Dir, std::map<String,String> Parameters, bool Recursive) {
3306        dmsg(2,("LSCPServer: FindDbInstruments(Dir=%s)\n", Dir.c_str()));
3307        LSCPResultSet result;
3308    #if HAVE_SQLITE3
3309        try {
3310            SearchQuery Query;
3311            std::map<String,String>::iterator iter;
3312            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3313                if (iter->first.compare("NAME") == 0) {
3314                    Query.Name = iter->second;
3315                } else if (iter->first.compare("FORMAT_FAMILIES") == 0) {
3316                    Query.SetFormatFamilies(iter->second);
3317                } else if (iter->first.compare("SIZE") == 0) {
3318                    Query.SetSize(iter->second);
3319                } else if (iter->first.compare("CREATED") == 0) {
3320                    Query.SetCreated(iter->second);
3321                } else if (iter->first.compare("MODIFIED") == 0) {
3322                    Query.SetModified(iter->second);
3323                } else if (iter->first.compare("DESCRIPTION") == 0) {
3324                    Query.Description = iter->second;
3325                } else if (iter->first.compare("IS_DRUM") == 0) {
3326                    if (!strcasecmp(iter->second.c_str(), "true")) {
3327                        Query.InstrType = SearchQuery::DRUM;
3328                    } else {
3329                        Query.InstrType = SearchQuery::CHROMATIC;
3330                    }
3331                } else if (iter->first.compare("PRODUCT") == 0) {
3332                     Query.Product = iter->second;
3333                } else if (iter->first.compare("ARTISTS") == 0) {
3334                     Query.Artists = iter->second;
3335                } else if (iter->first.compare("KEYWORDS") == 0) {
3336                     Query.Keywords = iter->second;
3337                } else {
3338                    throw Exception("Unknown search criteria: " + iter->first);
3339                }
3340            }
3341    
3342            String list;
3343            StringListPtr pInstruments =
3344                InstrumentsDb::GetInstrumentsDb()->FindInstruments(Dir, &Query, Recursive);
3345    
3346            for (int i = 0; i < pInstruments->size(); i++) {
3347                if (list != "") list += ",";
3348                list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
3349            }
3350    
3351            result.Add(list);
3352        } catch (Exception e) {
3353             result.Error(e);
3354        }
3355    #else
3356        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3357    #endif
3358        return result.Produce();
3359    }
3360    
3361    String LSCPServer::FormatInstrumentsDb() {
3362        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3363        LSCPResultSet result;
3364    #if HAVE_SQLITE3
3365        try {
3366            InstrumentsDb::GetInstrumentsDb()->Format();
3367        } catch (Exception e) {
3368             result.Error(e);
3369        }
3370    #else
3371        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3372    #endif
3373        return result.Produce();
3374    }
3375    
3376    
3377  /**  /**
3378   * 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
3379   * mode is enabled, all commands from the client will (immediately) be   * mode is enabled, all commands from the client will (immediately) be
# Line 1441  String LSCPServer::SetEcho(yyparse_param Line 3385  String LSCPServer::SetEcho(yyparse_param
3385      try {      try {
3386          if      (boolean_value == 0) pSession->bVerbose = false;          if      (boolean_value == 0) pSession->bVerbose = false;
3387          else if (boolean_value == 1) pSession->bVerbose = true;          else if (boolean_value == 1) pSession->bVerbose = true;
3388          else throw LinuxSamplerException("Not a boolean value, must either be 0 or 1");          else throw Exception("Not a boolean value, must either be 0 or 1");
3389      }      }
3390      catch (LinuxSamplerException e) {      catch (Exception e) {
3391           result.Error(e);           result.Error(e);
3392      }      }
3393      return result.Produce();      return result.Produce();
3394  }  }
3395    
3396    }

Legend:
Removed from v.397  
changed lines
  Added in v.1897

  ViewVC Help
Powered by ViewVC