/[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 133 by capela, Fri Jun 18 14:29:02 2004 UTC revision 1763 by iliev, Wed Sep 3 17:18:51 2008 UTC
# Line 3  Line 3 
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6     *   Copyright (C) 2005 - 2008 Christian Schoenebeck                       *
7   *                                                                         *   *                                                                         *
8   *   This program 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  *
10   *   the Free Software Foundation; either version 2 of the License, or     *   *   the Free Software Foundation; either version 2 of the License, or     *
11   *   (at your option) any later version.                                   *   *   (at your option) any later version.                                   *
12   *                                                                         *   *                                                                         *
13   *   This program is distributed in the hope that it will be useful,       *   *   This library is distributed in the hope that it will be useful,       *
14   *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *   *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
15   *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *   *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
16   *   GNU General Public License for more details.                          *   *   GNU General Public License for more details.                          *
17   *                                                                         *   *                                                                         *
18   *   You should have received a copy of the GNU General Public License     *   *   You should have received a copy of the GNU General Public License     *
19   *   along with this program; if not, write to the Free Software           *   *   along with this library; if not, write to the Free Software           *
20   *   Foundation, Inc., 59 Temple Place, Suite 330, Boston,                 *   *   Foundation, Inc., 59 Temple Place, Suite 330, Boston,                 *
21   *   MA  02111-1307  USA                                                   *   *   MA  02111-1307  USA                                                   *
22   ***************************************************************************/   ***************************************************************************/
23    
24    #include <algorithm>
25    
26  #include "lscpserver.h"  #include "lscpserver.h"
27  #include "lscpresultset.h"  #include "lscpresultset.h"
28    #include "lscpevent.h"
29    
30    #if defined(WIN32)
31    #include <windows.h>
32    #else
33    #include <fcntl.h>
34    #endif
35    
36    #if ! HAVE_SQLITE3
37    #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."
38    #endif
39    
40    #include "../engines/EngineFactory.h"
41    #include "../engines/EngineChannelFactory.h"
42    #include "../drivers/audio/AudioOutputDeviceFactory.h"
43    #include "../drivers/midi/MidiInputDeviceFactory.h"
44    
 #include "../engines/gig/Engine.h"  
 #include "../audiodriver/AudioOutputDeviceFactory.h"  
45    
46  LSCPServer::LSCPServer(Sampler* pSampler) : Thread(false, 0, -4) {  /**
47     * Returns a copy of the given string where all special characters are
48     * replaced by LSCP escape sequences ("\xHH"). This function shall be used
49     * to escape LSCP response fields in case the respective response field is
50     * actually defined as using escape sequences in the LSCP specs.
51     *
52     * @e Caution: DO NOT use this function for escaping path based responses,
53     * use the Path class (src/common/Path.h) for this instead!
54     */
55    static String _escapeLscpResponse(String txt) {
56        for (int i = 0; i < txt.length(); i++) {
57            const char c = txt.c_str()[i];
58            if (
59                !(c >= '0' && c <= '9') &&
60                !(c >= 'a' && c <= 'z') &&
61                !(c >= 'A' && c <= 'Z') &&
62                !(c == ' ') && !(c == '!') && !(c == '#') && !(c == '$') &&
63                !(c == '%') && !(c == '&') && !(c == '(') && !(c == ')') &&
64                !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&
65                !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&
66                !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&
67                !(c == '@') && !(c == '[') && !(c == ']') &&
68                !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&
69                !(c == '|') && !(c == '}') && !(c == '~')
70            ) {
71                // convert the "special" character into a "\xHH" LSCP escape sequence
72                char buf[5];
73                snprintf(buf, sizeof(buf), "\\x%02x", static_cast<unsigned char>(c));
74                txt.replace(i, 1, buf);
75                i += 3;
76            }
77        }
78        return txt;
79    }
80    
81    /**
82     * Below are a few static members of the LSCPServer class.
83     * The big assumption here is that LSCPServer is going to remain a singleton.
84     * These members are used to support client connections.
85     * Class handles multiple connections at the same time using select() and non-blocking recv()
86     * Commands are processed by a single LSCPServer thread.
87     * Notifications are delivered either by the thread that originated them
88     * or (if the resultset is currently in progress) by the LSCPServer thread
89     * after the resultset was sent out.
90     * This makes sure that resultsets can not be interrupted by notifications.
91     * This also makes sure that the thread sending notification is not blocked
92     * by the LSCPServer thread.
93     */
94    fd_set LSCPServer::fdSet;
95    int LSCPServer::currentSocket = -1;
96    std::vector<yyparse_param_t> LSCPServer::Sessions = std::vector<yyparse_param_t>();
97    std::vector<yyparse_param_t>::iterator itCurrentSession = std::vector<yyparse_param_t>::iterator();
98    std::map<int,String> LSCPServer::bufferedNotifies = std::map<int,String>();
99    std::map<int,String> LSCPServer::bufferedCommands = std::map<int,String>();
100    std::map< LSCPEvent::event_t, std::list<int> > LSCPServer::eventSubscriptions = std::map< LSCPEvent::event_t, std::list<int> >();
101    Mutex LSCPServer::NotifyMutex = Mutex();
102    Mutex LSCPServer::NotifyBufferMutex = Mutex();
103    Mutex LSCPServer::SubscriptionMutex = Mutex();
104    Mutex LSCPServer::RTNotifyMutex = Mutex();
105    
106    LSCPServer::LSCPServer(Sampler* pSampler, long int addr, short int port) : Thread(true, false, 0, -4), eventHandler(this) {
107        SocketAddress.sin_family      = AF_INET;
108        SocketAddress.sin_addr.s_addr = addr;
109        SocketAddress.sin_port        = port;
110      this->pSampler = pSampler;      this->pSampler = pSampler;
111        LSCPEvent::RegisterEvent(LSCPEvent::event_audio_device_count, "AUDIO_OUTPUT_DEVICE_COUNT");
112        LSCPEvent::RegisterEvent(LSCPEvent::event_audio_device_info, "AUDIO_OUTPUT_DEVICE_INFO");
113        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_device_count, "MIDI_INPUT_DEVICE_COUNT");
114        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_device_info, "MIDI_INPUT_DEVICE_INFO");
115        LSCPEvent::RegisterEvent(LSCPEvent::event_channel_count, "CHANNEL_COUNT");
116        LSCPEvent::RegisterEvent(LSCPEvent::event_voice_count, "VOICE_COUNT");
117        LSCPEvent::RegisterEvent(LSCPEvent::event_stream_count, "STREAM_COUNT");
118        LSCPEvent::RegisterEvent(LSCPEvent::event_buffer_fill, "BUFFER_FILL");
119        LSCPEvent::RegisterEvent(LSCPEvent::event_channel_info, "CHANNEL_INFO");
120        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_send_count, "FX_SEND_COUNT");
121        LSCPEvent::RegisterEvent(LSCPEvent::event_fx_send_info, "FX_SEND_INFO");
122        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_count, "MIDI_INSTRUMENT_MAP_COUNT");
123        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_map_info, "MIDI_INSTRUMENT_MAP_INFO");
124        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_count, "MIDI_INSTRUMENT_COUNT");
125        LSCPEvent::RegisterEvent(LSCPEvent::event_midi_instr_info, "MIDI_INSTRUMENT_INFO");
126        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_count, "DB_INSTRUMENT_DIRECTORY_COUNT");
127        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_dir_info, "DB_INSTRUMENT_DIRECTORY_INFO");
128        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_count, "DB_INSTRUMENT_COUNT");
129        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instr_info, "DB_INSTRUMENT_INFO");
130        LSCPEvent::RegisterEvent(LSCPEvent::event_db_instrs_job_info, "DB_INSTRUMENTS_JOB_INFO");
131        LSCPEvent::RegisterEvent(LSCPEvent::event_misc, "MISCELLANEOUS");
132        LSCPEvent::RegisterEvent(LSCPEvent::event_total_stream_count, "TOTAL_STREAM_COUNT");
133        LSCPEvent::RegisterEvent(LSCPEvent::event_total_voice_count, "TOTAL_VOICE_COUNT");
134        LSCPEvent::RegisterEvent(LSCPEvent::event_global_info, "GLOBAL_INFO");
135        LSCPEvent::RegisterEvent(LSCPEvent::event_channel_midi, "CHANNEL_MIDI");
136        LSCPEvent::RegisterEvent(LSCPEvent::event_device_midi, "DEVICE_MIDI");
137        hSocket = -1;
138    }
139    
140    LSCPServer::~LSCPServer() {
141    #if defined(WIN32)
142        if (hSocket >= 0) closesocket(hSocket);
143    #else
144        if (hSocket >= 0) close(hSocket);
145    #endif
146    }
147    
148    LSCPServer::EventHandler::EventHandler(LSCPServer* pParent) {
149        this->pParent = pParent;
150    }
151    
152    LSCPServer::EventHandler::~EventHandler() {
153        std::vector<midi_listener_entry> l = channelMidiListeners;
154        channelMidiListeners.clear();
155        for (int i = 0; i < l.size(); i++)
156            delete l[i].pMidiListener;
157    }
158    
159    void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
160        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_count, NewCount));
161    }
162    
163    void LSCPServer::EventHandler::ChannelAdded(SamplerChannel* pChannel) {
164        pChannel->AddEngineChangeListener(this);
165    }
166    
167    void LSCPServer::EventHandler::ChannelToBeRemoved(SamplerChannel* pChannel) {
168        if (!pChannel->GetEngineChannel()) return;
169        EngineToBeChanged(pChannel->Index());
170    }
171    
172    void LSCPServer::EventHandler::EngineToBeChanged(int ChannelId) {
173        SamplerChannel* pSamplerChannel =
174            pParent->pSampler->GetSamplerChannel(ChannelId);
175        if (!pSamplerChannel) return;
176        EngineChannel* pEngineChannel =
177            pSamplerChannel->GetEngineChannel();
178        if (!pEngineChannel) return;
179        for (std::vector<midi_listener_entry>::iterator iter = channelMidiListeners.begin(); iter != channelMidiListeners.end(); ++iter) {
180            if ((*iter).pEngineChannel == pEngineChannel) {
181                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
182                pEngineChannel->Disconnect(pMidiListener);
183                channelMidiListeners.erase(iter);
184                delete pMidiListener;
185                return;
186            }
187        }
188    }
189    
190    void LSCPServer::EventHandler::EngineChanged(int ChannelId) {
191        SamplerChannel* pSamplerChannel =
192            pParent->pSampler->GetSamplerChannel(ChannelId);
193        if (!pSamplerChannel) return;
194        EngineChannel* pEngineChannel =
195            pSamplerChannel->GetEngineChannel();
196        if (!pEngineChannel) return;
197        VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
198        pEngineChannel->Connect(pMidiListener);
199        midi_listener_entry entry = {
200            pSamplerChannel, pEngineChannel, pMidiListener
201        };
202        channelMidiListeners.push_back(entry);
203    }
204    
205    void LSCPServer::EventHandler::AudioDeviceCountChanged(int NewCount) {
206        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_count, NewCount));
207    }
208    
209    void LSCPServer::EventHandler::MidiDeviceCountChanged(int NewCount) {
210        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_count, NewCount));
211    }
212    
213    void LSCPServer::EventHandler::MidiDeviceToBeDestroyed(MidiInputDevice* pDevice) {
214        pDevice->RemoveMidiPortCountListener(this);
215        for (int i = 0; i < pDevice->PortCount(); ++i)
216            MidiPortToBeRemoved(pDevice->GetPort(i));
217    }
218    
219    void LSCPServer::EventHandler::MidiDeviceCreated(MidiInputDevice* pDevice) {
220        pDevice->AddMidiPortCountListener(this);
221        for (int i = 0; i < pDevice->PortCount(); ++i)
222            MidiPortAdded(pDevice->GetPort(i));
223    }
224    
225    void LSCPServer::EventHandler::MidiPortCountChanged(int NewCount) {
226        // yet unused
227    }
228    
229    void LSCPServer::EventHandler::MidiPortToBeRemoved(MidiInputPort* pPort) {
230        for (std::vector<device_midi_listener_entry>::iterator iter = deviceMidiListeners.begin(); iter != deviceMidiListeners.end(); ++iter) {
231            if ((*iter).pPort == pPort) {
232                VirtualMidiDevice* pMidiListener = (*iter).pMidiListener;
233                pPort->Disconnect(pMidiListener);
234                deviceMidiListeners.erase(iter);
235                delete pMidiListener;
236                return;
237            }
238        }
239    }
240    
241    void LSCPServer::EventHandler::MidiPortAdded(MidiInputPort* pPort) {
242        // find out the device ID
243        std::map<uint, MidiInputDevice*> devices =
244            pParent->pSampler->GetMidiInputDevices();
245        for (
246            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
247            iter != devices.end(); ++iter
248        ) {
249            if (iter->second == pPort->GetDevice()) { // found
250                VirtualMidiDevice* pMidiListener = new VirtualMidiDevice;
251                pPort->Connect(pMidiListener);
252                device_midi_listener_entry entry = {
253                    pPort, pMidiListener, iter->first
254                };
255                deviceMidiListeners.push_back(entry);
256                return;
257            }
258        }
259    }
260    
261    void LSCPServer::EventHandler::MidiInstrumentCountChanged(int MapId, int NewCount) {
262        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_count, MapId, NewCount));
263    }
264    
265    void LSCPServer::EventHandler::MidiInstrumentInfoChanged(int MapId, int Bank, int Program) {
266        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_info, MapId, Bank, Program));
267    }
268    
269    void LSCPServer::EventHandler::MidiInstrumentMapCountChanged(int NewCount) {
270        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_count, NewCount));
271    }
272    
273    void LSCPServer::EventHandler::MidiInstrumentMapInfoChanged(int MapId) {
274        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_instr_map_info, MapId));
275    }
276    
277    void LSCPServer::EventHandler::FxSendCountChanged(int ChannelId, int NewCount) {
278        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_count, ChannelId, NewCount));
279    }
280    
281    void LSCPServer::EventHandler::VoiceCountChanged(int ChannelId, int NewCount) {
282        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_voice_count, ChannelId, NewCount));
283    }
284    
285    void LSCPServer::EventHandler::StreamCountChanged(int ChannelId, int NewCount) {
286        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_stream_count, ChannelId, NewCount));
287    }
288    
289    void LSCPServer::EventHandler::BufferFillChanged(int ChannelId, String FillData) {
290        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_buffer_fill, ChannelId, FillData));
291    }
292    
293    void LSCPServer::EventHandler::TotalVoiceCountChanged(int NewCount) {
294        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_voice_count, NewCount));
295    }
296    
297    void LSCPServer::EventHandler::TotalStreamCountChanged(int NewCount) {
298        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_total_stream_count, NewCount));
299    }
300    
301    #if HAVE_SQLITE3
302    void LSCPServer::DbInstrumentsEventHandler::DirectoryCountChanged(String Dir) {
303        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_count, InstrumentsDb::toEscapedPath(Dir)));
304    }
305    
306    void LSCPServer::DbInstrumentsEventHandler::DirectoryInfoChanged(String Dir) {
307        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, InstrumentsDb::toEscapedPath(Dir)));
308    }
309    
310    void LSCPServer::DbInstrumentsEventHandler::DirectoryNameChanged(String Dir, String NewName) {
311        Dir = "'" + InstrumentsDb::toEscapedPath(Dir) + "'";
312        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
313        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_dir_info, "NAME", Dir, NewName));
314    }
315    
316    void LSCPServer::DbInstrumentsEventHandler::InstrumentCountChanged(String Dir) {
317        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_count, InstrumentsDb::toEscapedPath(Dir)));
318    }
319    
320    void LSCPServer::DbInstrumentsEventHandler::InstrumentInfoChanged(String Instr) {
321        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, InstrumentsDb::toEscapedPath(Instr)));
322    }
323    
324    void LSCPServer::DbInstrumentsEventHandler::InstrumentNameChanged(String Instr, String NewName) {
325        Instr = "'" + InstrumentsDb::toEscapedPath(Instr) + "'";
326        NewName = "'" + InstrumentsDb::toEscapedPath(NewName) + "'";
327        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instr_info, "NAME", Instr, NewName));
328    }
329    
330    void LSCPServer::DbInstrumentsEventHandler::JobStatusChanged(int JobId) {
331        LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_db_instrs_job_info, JobId));
332    }
333    #endif // HAVE_SQLITE3
334    
335    
336    /**
337     * Blocks the calling thread until the LSCP Server is initialized and
338     * accepting socket connections, if the server is already initialized then
339     * this method will return immediately.
340     * @param TimeoutSeconds     - optional: max. wait time in seconds
341     *                             (default: 0s)
342     * @param TimeoutNanoSeconds - optional: max wait time in nano seconds
343     *                             (default: 0ns)
344     * @returns  0 on success, a value less than 0 if timeout exceeded
345     */
346    int LSCPServer::WaitUntilInitialized(long TimeoutSeconds, long TimeoutNanoSeconds) {
347        return Initialized.WaitAndUnlockIf(false, TimeoutSeconds, TimeoutNanoSeconds);
348  }  }
349    
350  int LSCPServer::Main() {  int LSCPServer::Main() {
351            #if defined(WIN32)
352            WSADATA wsaData;
353            int iResult;
354            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
355            if (iResult != 0) {
356                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
357                    exit(EXIT_FAILURE);
358            }
359            #endif
360      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
361      if (hSocket < 0) {      if (hSocket < 0) {
362          std::cerr << "LSCPServer: Could not create server socket." << std::endl;          std::cerr << "LSCPServer: Could not create server socket." << std::endl;
# Line 38  int LSCPServer::Main() { Line 364  int LSCPServer::Main() {
364          exit(EXIT_FAILURE);          exit(EXIT_FAILURE);
365      }      }
366    
     SocketAddress.sin_family      = AF_INET;  
     SocketAddress.sin_port        = htons(LSCP_PORT);  
     SocketAddress.sin_addr.s_addr = htonl(INADDR_ANY);  
   
367      if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {      if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
368          std::cerr << "LSCPServer: Could not bind server socket." << std::endl;          std::cerr << "LSCPServer: Could not bind server socket, retrying for " << ToString(LSCP_SERVER_BIND_TIMEOUT) << " seconds...";
369          close(hSocket);          for (int trial = 0; true; trial++) { // retry for LSCP_SERVER_BIND_TIMEOUT seconds
370          //return -1;              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
371          exit(EXIT_FAILURE);                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
372                        std::cerr << "gave up!" << std::endl;
373                        #if defined(WIN32)
374                        closesocket(hSocket);
375                        #else
376                        close(hSocket);
377                        #endif
378                        //return -1;
379                        exit(EXIT_FAILURE);
380                    }
381                    else sleep(1); // sleep 1s
382                }
383                else break; // success
384            }
385      }      }
386    
387      listen(hSocket, 1);      listen(hSocket, 1);
388      dmsg(1,("LSCPServer: Server running.\n")); // server running      Initialized.Set(true);
389    
390        // Registering event listeners
391        pSampler->AddChannelCountListener(&eventHandler);
392        pSampler->AddAudioDeviceCountListener(&eventHandler);
393        pSampler->AddMidiDeviceCountListener(&eventHandler);
394        pSampler->AddVoiceCountListener(&eventHandler);
395        pSampler->AddStreamCountListener(&eventHandler);
396        pSampler->AddBufferFillListener(&eventHandler);
397        pSampler->AddTotalStreamCountListener(&eventHandler);
398        pSampler->AddTotalVoiceCountListener(&eventHandler);
399        pSampler->AddFxSendCountListener(&eventHandler);
400        MidiInstrumentMapper::AddMidiInstrumentCountListener(&eventHandler);
401        MidiInstrumentMapper::AddMidiInstrumentInfoListener(&eventHandler);
402        MidiInstrumentMapper::AddMidiInstrumentMapCountListener(&eventHandler);
403        MidiInstrumentMapper::AddMidiInstrumentMapInfoListener(&eventHandler);
404    #if HAVE_SQLITE3
405        InstrumentsDb::GetInstrumentsDb()->AddInstrumentsDbListener(&dbInstrumentsEventHandler);
406    #endif
407      // now wait for client connections and handle their requests      // now wait for client connections and handle their requests
408      sockaddr_in client;      sockaddr_in client;
409      int length = sizeof(client);      int length = sizeof(client);
410        FD_ZERO(&fdSet);
411        FD_SET(hSocket, &fdSet);
412        int maxSessions = hSocket;
413    
414        timeval timeout;
415    
416      while (true) {      while (true) {
417          hSession = accept(hSocket, (sockaddr*) &client, (socklen_t*) &length);          #if CONFIG_PTHREAD_TESTCANCEL
418          if (hSession < 0) {                  TestCancel();
419              std::cerr << "LSCPServer: Client connection failed." << std::endl;          #endif
420              close(hSocket);          // check if some engine channel's parameter / status changed, if so notify the respective LSCP event subscribers
421              //return -1;          {
422              exit(EXIT_FAILURE);              std::set<EngineChannel*> engineChannels = EngineChannelFactory::EngineChannelInstances();
423          }              std::set<EngineChannel*>::iterator itEngineChannel = engineChannels.begin();
424                std::set<EngineChannel*>::iterator itEnd           = engineChannels.end();
425          dmsg(1,("LSCPServer: Client connection established.\n"));              for (; itEngineChannel != itEnd; ++itEngineChannel) {
426          //send(hSession, "Welcome!\r\n", 10, 0);                  if ((*itEngineChannel)->StatusChanged()) {
427                        SendLSCPNotify(LSCPEvent(LSCPEvent::event_channel_info, (*itEngineChannel)->GetSamplerChannel()->Index()));
428          // Parser invocation                  }
429          yyparse_param_t yyparse_param;  
430          yyparse_param.pServer = this;                  for (int i = 0; i < (*itEngineChannel)->GetFxSendCount(); i++) {
431          yylex_init(&yyparse_param.pScanner);                      FxSend* fxs = (*itEngineChannel)->GetFxSend(i);
432          while (yyparse(&yyparse_param) == LSCP_SYNTAX_ERROR); // recall parser in case of syntax error                      if(fxs != NULL && fxs->IsInfoChanged()) {
433          yylex_destroy(yyparse_param.pScanner);                          int chn = (*itEngineChannel)->GetSamplerChannel()->Index();
434                            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, chn, fxs->Id()));
435                            fxs->SetInfoChanged(false);
436                        }
437                    }
438                }
439            }
440    
441          close(hSession);          // check if MIDI data arrived on some engine channel
442          dmsg(1,("LSCPServer: Client connection terminated.\n"));          for (int i = 0; i < eventHandler.channelMidiListeners.size(); ++i) {
443                const EventHandler::midi_listener_entry entry =
444                    eventHandler.channelMidiListeners[i];
445                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
446                if (pMidiListener->NotesChanged()) {
447                    for (int iNote = 0; iNote < 128; iNote++) {
448                        if (pMidiListener->NoteChanged(iNote)) {
449                            const bool bActive = pMidiListener->NoteIsActive(iNote);
450                            LSCPServer::SendLSCPNotify(
451                                LSCPEvent(
452                                    LSCPEvent::event_channel_midi,
453                                    entry.pSamplerChannel->Index(),
454                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
455                                    iNote,
456                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
457                                            : pMidiListener->NoteOffVelocity(iNote)
458                                )
459                            );
460                        }
461                    }
462                }
463            }
464    
465            // check if MIDI data arrived on some MIDI device
466            for (int i = 0; i < eventHandler.deviceMidiListeners.size(); ++i) {
467                const EventHandler::device_midi_listener_entry entry =
468                    eventHandler.deviceMidiListeners[i];
469                VirtualMidiDevice* pMidiListener = entry.pMidiListener;
470                if (pMidiListener->NotesChanged()) {
471                    for (int iNote = 0; iNote < 128; iNote++) {
472                        if (pMidiListener->NoteChanged(iNote)) {
473                            const bool bActive = pMidiListener->NoteIsActive(iNote);
474                            LSCPServer::SendLSCPNotify(
475                                LSCPEvent(
476                                    LSCPEvent::event_device_midi,
477                                    entry.uiDeviceID,
478                                    entry.pPort->GetPortNumber(),
479                                    std::string(bActive ? "NOTE_ON" : "NOTE_OFF"),
480                                    iNote,
481                                    bActive ? pMidiListener->NoteOnVelocity(iNote)
482                                            : pMidiListener->NoteOffVelocity(iNote)
483                                )
484                            );
485                        }
486                    }
487                }
488            }
489    
490            //Now let's deliver late notifies (if any)
491            NotifyBufferMutex.Lock();
492            for (std::map<int,String>::iterator iterNotify = bufferedNotifies.begin(); iterNotify != bufferedNotifies.end(); iterNotify++) {
493    #ifdef MSG_NOSIGNAL
494                    send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), MSG_NOSIGNAL);
495    #else
496                    send(iterNotify->first, iterNotify->second.c_str(), iterNotify->second.size(), 0);
497    #endif
498            }
499            bufferedNotifies.clear();
500            NotifyBufferMutex.Unlock();
501    
502            fd_set selectSet = fdSet;
503            timeout.tv_sec  = 0;
504            timeout.tv_usec = 100000;
505    
506            int retval = select(maxSessions+1, &selectSet, NULL, NULL, &timeout);
507    
508            if (retval == 0)
509                    continue; //Nothing try again
510            if (retval == -1) {
511                    std::cerr << "LSCPServer: Socket select error." << std::endl;
512                    #if defined(WIN32)
513                    closesocket(hSocket);
514                    #else
515                    close(hSocket);
516                    #endif
517                    exit(EXIT_FAILURE);
518            }
519    
520            //Accept new connections now (if any)
521            if (FD_ISSET(hSocket, &selectSet)) {
522                    int socket = accept(hSocket, (sockaddr*) &client, (socklen_t*) &length);
523                    if (socket < 0) {
524                            std::cerr << "LSCPServer: Client connection failed." << std::endl;
525                            exit(EXIT_FAILURE);
526                    }
527    
528                    #if defined(WIN32)
529                    u_long nonblock_io = 1;
530                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
531                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
532                      exit(EXIT_FAILURE);
533                    }
534            #else
535                    if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
536                            std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
537                            exit(EXIT_FAILURE);
538                    }
539                    #endif
540    
541                    // Parser initialization
542                    yyparse_param_t yyparse_param;
543                    yyparse_param.pServer  = this;
544                    yyparse_param.hSession = socket;
545    
546                    Sessions.push_back(yyparse_param);
547                    FD_SET(socket, &fdSet);
548                    if (socket > maxSessions)
549                            maxSessions = socket;
550                    dmsg(1,("LSCPServer: Client connection established on socket:%d.\n", socket));
551                    LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection established on socket", socket));
552                    continue; //Maybe this was the only selected socket, better select again
553            }
554    
555            //Something was selected and it was not the hSocket, so it must be some command(s) coming.
556            for (std::vector<yyparse_param_t>::iterator iter = Sessions.begin(); iter != Sessions.end(); iter++) {
557                    if (FD_ISSET((*iter).hSession, &selectSet)) {   //Was it this socket?
558                            if (GetLSCPCommand(iter)) {     //Have we read the entire command?
559                                    dmsg(3,("LSCPServer: Got command on socket %d, calling parser.\n", currentSocket));
560                                    int dummy; // just a temporary hack to fulfill the restart() function prototype
561                                    restart(NULL, dummy); // restart the 'scanner'
562                                    currentSocket = (*iter).hSession;  //a hack
563                                    itCurrentSession = iter; // another hack
564                                    dmsg(2,("LSCPServer: [%s]\n",bufferedCommands[currentSocket].c_str()));
565                                    if ((*iter).bVerbose) { // if echo mode enabled
566                                        AnswerClient(bufferedCommands[currentSocket]);
567                                    }
568                                    int result = yyparse(&(*iter));
569                                    currentSocket = -1;     //continuation of a hack
570                                    itCurrentSession = Sessions.end(); // hack as well
571                                    dmsg(3,("LSCPServer: Done parsing on socket %d.\n", currentSocket));
572                                    if (result == LSCP_QUIT) { //Was it a quit command by any chance?
573                                            CloseConnection(iter);
574                                    }
575                            }
576                            //socket may have been closed, iter may be invalid, get out of the loop for now.
577                            //we'll be back if there is data.
578                            break;
579                    }
580            }
581      }      }
582  }  }
583    
584    void LSCPServer::CloseConnection( std::vector<yyparse_param_t>::iterator iter ) {
585            int socket = (*iter).hSession;
586            dmsg(1,("LSCPServer: Client connection terminated on socket:%d.\n",socket));
587            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Client connection terminated on socket", socket));
588            Sessions.erase(iter);
589            FD_CLR(socket,  &fdSet);
590            SubscriptionMutex.Lock(); //Must unsubscribe this socket from all events (if any)
591            for (std::map< LSCPEvent::event_t, std::list<int> >::iterator iter = eventSubscriptions.begin(); iter != eventSubscriptions.end(); iter++) {
592                    iter->second.remove(socket);
593            }
594            SubscriptionMutex.Unlock();
595            NotifyMutex.Lock();
596            bufferedCommands.erase(socket);
597            bufferedNotifies.erase(socket);
598            #if defined(WIN32)
599            closesocket(socket);
600            #else
601            close(socket);
602            #endif
603            NotifyMutex.Unlock();
604    }
605    
606    void LSCPServer::LockRTNotify() {
607        RTNotifyMutex.Lock();
608    }
609    
610    void LSCPServer::UnlockRTNotify() {
611        RTNotifyMutex.Unlock();
612    }
613    
614    int LSCPServer::EventSubscribers( std::list<LSCPEvent::event_t> events ) {
615            int subs = 0;
616            SubscriptionMutex.Lock();
617            for( std::list<LSCPEvent::event_t>::iterator iter = events.begin();
618                            iter != events.end(); iter++)
619            {
620                    subs += eventSubscriptions.count(*iter);
621            }
622            SubscriptionMutex.Unlock();
623            return subs;
624    }
625    
626    void LSCPServer::SendLSCPNotify( LSCPEvent event ) {
627            SubscriptionMutex.Lock();
628            if (eventSubscriptions.count(event.GetType()) == 0) {
629                    SubscriptionMutex.Unlock();     //Nobody is subscribed to this event
630                    return;
631            }
632            std::list<int>::iterator iter = eventSubscriptions[event.GetType()].begin();
633            std::list<int>::iterator end = eventSubscriptions[event.GetType()].end();
634            String notify = event.Produce();
635    
636            while (true) {
637                    if (NotifyMutex.Trylock()) {
638                            for(;iter != end; iter++)
639    #ifdef MSG_NOSIGNAL
640                                    send(*iter, notify.c_str(), notify.size(), MSG_NOSIGNAL);
641    #else
642                                    send(*iter, notify.c_str(), notify.size(), 0);
643    #endif
644                            NotifyMutex.Unlock();
645                            break;
646                    } else {
647                            if (NotifyBufferMutex.Trylock()) {
648                                    for(;iter != end; iter++)
649                                            bufferedNotifies[*iter] += notify;
650                                    NotifyBufferMutex.Unlock();
651                                    break;
652                            }
653                    }
654            }
655            SubscriptionMutex.Unlock();
656    }
657    
658    extern int GetLSCPCommand( void *buf, int max_size ) {
659            String command = LSCPServer::bufferedCommands[LSCPServer::currentSocket];
660            if (command.size() == 0) {              //Parser wants input but we have nothing.
661                    strcpy((char*) buf, "\n");      //So give it an empty command
662                    return 1;                       //to keep it happy.
663            }
664    
665            if (max_size < command.size()) {
666                    std::cerr << "getLSCPCommand: Flex buffer too small, ignoring the command." << std::endl;
667                    return 0;       //This will never happen
668            }
669    
670            strcpy((char*) buf, command.c_str());
671            LSCPServer::bufferedCommands.erase(LSCPServer::currentSocket);
672            return command.size();
673    }
674    
675    extern yyparse_param_t* GetCurrentYaccSession() {
676        return &(*itCurrentSession);
677    }
678    
679    /**
680     * Will be called to try to read the command from the socket
681     * If command is read, it will return true. Otherwise false is returned.
682     * In any case the received portion (complete or incomplete) is saved into bufferedCommand map.
683     */
684    bool LSCPServer::GetLSCPCommand( std::vector<yyparse_param_t>::iterator iter ) {
685            int socket = (*iter).hSession;
686            char c;
687            int i = 0;
688            while (true) {
689                    #if defined(WIN32)
690                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
691                    #else
692                    int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now
693                    #endif
694                    if (result == 0) { //socket was selected, so 0 here means client has closed the connection
695                            CloseConnection(iter);
696                            break;
697                    }
698                    if (result == 1) {
699                            if (c == '\r')
700                                    continue; //Ignore CR
701                            if (c == '\n') {
702                                    LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_misc, "Received \'" + bufferedCommands[socket] + "\' on socket", socket));
703                                    bufferedCommands[socket] += "\r\n";
704                                    return true; //Complete command was read
705                            }
706                            bufferedCommands[socket] += c;
707                    }
708                    #if defined(WIN32)
709                    if (result == SOCKET_ERROR) {
710                        int wsa_lasterror = WSAGetLastError();
711                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
712                                    return false;
713                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
714                            CloseConnection(iter);
715                            break;
716                    }
717                    #else
718                    if (result == -1) {
719                            if (errno == EAGAIN) //Would block, try again later.
720                                    return false;
721                            switch(errno) {
722                                    case EBADF:
723                                            dmsg(2,("LSCPScanner: The argument s is an invalid descriptor.\n"));
724                                            break;
725                                    case ECONNREFUSED:
726                                            dmsg(2,("LSCPScanner: A remote host refused to allow the network connection (typically because it is not running the requested service).\n"));
727                                            break;
728                                    case ENOTCONN:
729                                            dmsg(2,("LSCPScanner: The socket is associated with a connection-oriented protocol and has not been connected (see connect(2) and accept(2)).\n"));
730                                            break;
731                                    case ENOTSOCK:
732                                            dmsg(2,("LSCPScanner: The argument s does not refer to a socket.\n"));
733                                            break;
734                                    case EAGAIN:
735                                            dmsg(2,("LSCPScanner: The socket is marked non-blocking and the receive operation would block, or a receive timeout had been set and the timeout expired before data was received.\n"));
736                                            break;
737                                    case EINTR:
738                                            dmsg(2,("LSCPScanner: The receive was interrupted by delivery of a signal before any data were available.\n"));
739                                            break;
740                                    case EFAULT:
741                                            dmsg(2,("LSCPScanner: The receive buffer pointer(s) point outside the process's address space.\n"));
742                                            break;
743                                    case EINVAL:
744                                            dmsg(2,("LSCPScanner: Invalid argument passed.\n"));
745                                            break;
746                                    case ENOMEM:
747                                            dmsg(2,("LSCPScanner: Could not allocate memory for recvmsg.\n"));
748                                            break;
749                                    default:
750                                            dmsg(2,("LSCPScanner: Unknown recv() error.\n"));
751                                            break;
752                            }
753                            CloseConnection(iter);
754                            break;
755                    }
756                    #endif
757            }
758            return false;
759    }
760    
761  /**  /**
762   * Will be called by the parser whenever it wants to send an answer to the   * Will be called by the parser whenever it wants to send an answer to the
763   * client / frontend.   * client / frontend.
# Line 87  int LSCPServer::Main() { Line 766  int LSCPServer::Main() {
766   */   */
767  void LSCPServer::AnswerClient(String ReturnMessage) {  void LSCPServer::AnswerClient(String ReturnMessage) {
768      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str()));      dmsg(2,("LSCPServer::AnswerClient(ReturnMessage=%s)", ReturnMessage.c_str()));
769      send(hSession, ReturnMessage.c_str(), ReturnMessage.size(), 0);      if (currentSocket != -1) {
770                NotifyMutex.Lock();
771    #ifdef MSG_NOSIGNAL
772                send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), MSG_NOSIGNAL);
773    #else
774                send(currentSocket, ReturnMessage.c_str(), ReturnMessage.size(), 0);
775    #endif
776                NotifyMutex.Unlock();
777        }
778    }
779    
780    /**
781     * Find a created audio output device index.
782     */
783    int LSCPServer::GetAudioOutputDeviceIndex ( AudioOutputDevice *pDevice )
784    {
785        // Search for the created device to get its index
786        std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
787        std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();
788        for (; iter != devices.end(); iter++) {
789            if (iter->second == pDevice)
790                return iter->first;
791        }
792        // Not found.
793        return -1;
794    }
795    
796    /**
797     * Find a created midi input device index.
798     */
799    int LSCPServer::GetMidiInputDeviceIndex ( MidiInputDevice *pDevice )
800    {
801        // Search for the created device to get its index
802        std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
803        std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
804        for (; iter != devices.end(); iter++) {
805            if (iter->second == pDevice)
806                return iter->first;
807        }
808        // Not found.
809        return -1;
810  }  }
811    
812  String LSCPServer::CreateAudioOutputDevice(String Driver, std::map<String,String> Parameters) {  String LSCPServer::CreateAudioOutputDevice(String Driver, std::map<String,String> Parameters) {
# Line 95  String LSCPServer::CreateAudioOutputDevi Line 814  String LSCPServer::CreateAudioOutputDevi
814      LSCPResultSet result;      LSCPResultSet result;
815      try {      try {
816          AudioOutputDevice* pDevice = pSampler->CreateAudioOutputDevice(Driver, Parameters);          AudioOutputDevice* pDevice = pSampler->CreateAudioOutputDevice(Driver, Parameters);
         std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();  
817          // search for the created device to get its index          // search for the created device to get its index
818          int index = -1;          int index = GetAudioOutputDeviceIndex(pDevice);
819          std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();          if (index == -1) throw Exception("Internal error: could not find created audio output device.");
         for (; iter != devices.end(); iter++) {  
             if (iter->second == pDevice) {  
                 index = iter->first;  
                 break;  
             }  
         }  
         if (index == -1) throw LinuxSamplerException("Internal error: could not find created audio output device.");  
820          result = index; // success          result = index; // success
821      }      }
822      catch (LinuxSamplerException e) {      catch (Exception e) {
823            result.Error(e);
824        }
825        return result.Produce();
826    }
827    
828    String LSCPServer::CreateMidiInputDevice(String Driver, std::map<String,String> Parameters) {
829        dmsg(2,("LSCPServer: CreateMidiInputDevice(Driver=%s)\n", Driver.c_str()));
830        LSCPResultSet result;
831        try {
832            MidiInputDevice* pDevice = pSampler->CreateMidiInputDevice(Driver, Parameters);
833            // search for the created device to get its index
834            int index = GetMidiInputDeviceIndex(pDevice);
835            if (index == -1) throw Exception("Internal error: could not find created midi input device.");
836            result = index; // success
837        }
838        catch (Exception e) {
839          result.Error(e);          result.Error(e);
840      }      }
841      return result.Produce();      return result.Produce();
# Line 119  String LSCPServer::DestroyAudioOutputDev Line 846  String LSCPServer::DestroyAudioOutputDev
846      LSCPResultSet result;      LSCPResultSet result;
847      try {      try {
848          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
849          if (!devices[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) + ".");
850          AudioOutputDevice* pDevice = devices[DeviceIndex];          AudioOutputDevice* pDevice = devices[DeviceIndex];
851          pSampler->DestroyAudioOutputDevice(pDevice);          pSampler->DestroyAudioOutputDevice(pDevice);
852      }      }
853      catch (LinuxSamplerException e) {      catch (Exception e) {
854          result.Error(e);          result.Error(e);
855      }      }
856      return result.Produce();      return result.Produce();
857  }  }
858    
859    String LSCPServer::DestroyMidiInputDevice(uint DeviceIndex) {
860        dmsg(2,("LSCPServer: DestroyMidiInputDevice(DeviceIndex=%d)\n", DeviceIndex));
861        LSCPResultSet result;
862        try {
863            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
864            if (!devices.count(DeviceIndex)) throw Exception("There is no audio output device with index " + ToString(DeviceIndex) + ".");
865            MidiInputDevice* pDevice = devices[DeviceIndex];
866            pSampler->DestroyMidiInputDevice(pDevice);
867        }
868        catch (Exception e) {
869            result.Error(e);
870        }
871        return result.Produce();
872    }
873    
874    EngineChannel* LSCPServer::GetEngineChannel(uint uiSamplerChannel) {
875        SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
876        if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
877    
878        EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
879        if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
880    
881        return pEngineChannel;
882    }
883    
884  /**  /**
885   * Will be called by the parser to load an instrument.   * Will be called by the parser to load an instrument.
886   */   */
887  String LSCPServer::LoadInstrument(String Filename, uint uiInstrument, uint uiSamplerChannel) {  String LSCPServer::LoadInstrument(String Filename, uint uiInstrument, uint uiSamplerChannel, bool bBackground) {
888      dmsg(2,("LSCPServer: LoadInstrument(Filename=%s,Instrument=%d,SamplerChannel=%d)\n", Filename.c_str(), uiInstrument, uiSamplerChannel));      dmsg(2,("LSCPServer: LoadInstrument(Filename=%s,Instrument=%d,SamplerChannel=%d)\n", Filename.c_str(), uiInstrument, uiSamplerChannel));
889      LSCPResultSet result;      LSCPResultSet result;
890      try {      try {
891          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
892          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
893          Engine* pEngine = pSamplerChannel->GetEngine();          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
894          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");          if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel yet");
895          LSCPLoadInstrument *pLoadInstrument = new LSCPLoadInstrument(pEngine, Filename.c_str(), uiInstrument);          if (!pSamplerChannel->GetAudioOutputDevice())
896          pLoadInstrument->StartThread();              throw Exception("No audio output device connected to sampler channel");
897            if (bBackground) {
898                InstrumentManager::instrument_id_t id;
899                id.FileName = Filename;
900                id.Index    = uiInstrument;
901                InstrumentManager::LoadInstrumentInBackground(id, pEngineChannel);
902            }
903            else {
904                // tell the engine channel which instrument to load
905                pEngineChannel->PrepareLoadInstrument(Filename.c_str(), uiInstrument);
906                // actually start to load the instrument (blocks until completed)
907                pEngineChannel->LoadInstrument();
908            }
909      }      }
910      catch (LinuxSamplerException e) {      catch (Exception e) {
911           result.Error(e);           result.Error(e);
912      }      }
913      return result.Produce();      return result.Produce();
914  }  }
915    
916  /**  /**
917   * 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
918     * sampler channel.
919   */   */
920  String LSCPServer::LoadEngine(String EngineName, uint uiSamplerChannel) {  String LSCPServer::SetEngineType(String EngineName, uint uiSamplerChannel) {
921      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));
922      LSCPResultSet result;      LSCPResultSet result;
923      try {      try {
         Engine::type_t type;  
         if ((EngineName == "GigEngine") || (EngineName == "gig")) type = Engine::type_gig;  
         else throw LinuxSamplerException("Unknown engine type");  
924          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
925          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
926          pSamplerChannel->LoadEngine(type);          LockRTNotify();
927            pSamplerChannel->SetEngineType(EngineName);
928            if(HasSoloChannel()) pSamplerChannel->GetEngineChannel()->SetMute(-1);
929            UnlockRTNotify();
930      }      }
931      catch (LinuxSamplerException e) {      catch (Exception e) {
932           result.Error(e);           result.Error(e);
933      }      }
934      return result.Produce();      return result.Produce();
# Line 180  String LSCPServer::GetChannels() { Line 945  String LSCPServer::GetChannels() {
945  }  }
946    
947  /**  /**
948     * Will be called by the parser to get the list of sampler channels.
949     */
950    String LSCPServer::ListChannels() {
951        dmsg(2,("LSCPServer: ListChannels()\n"));
952        String list;
953        std::map<uint,SamplerChannel*> channels = pSampler->GetSamplerChannels();
954        std::map<uint,SamplerChannel*>::iterator iter = channels.begin();
955        for (; iter != channels.end(); iter++) {
956            if (list != "") list += ",";
957            list += ToString(iter->first);
958        }
959        LSCPResultSet result;
960        result.Add(list);
961        return result.Produce();
962    }
963    
964    /**
965   * Will be called by the parser to add a sampler channel.   * Will be called by the parser to add a sampler channel.
966   */   */
967  String LSCPServer::AddChannel() {  String LSCPServer::AddChannel() {
968      dmsg(2,("LSCPServer: AddChannel()\n"));      dmsg(2,("LSCPServer: AddChannel()\n"));
969        LockRTNotify();
970      SamplerChannel* pSamplerChannel = pSampler->AddSamplerChannel();      SamplerChannel* pSamplerChannel = pSampler->AddSamplerChannel();
971        UnlockRTNotify();
972      LSCPResultSet result(pSamplerChannel->Index());      LSCPResultSet result(pSamplerChannel->Index());
973      return result.Produce();      return result.Produce();
974  }  }
# Line 195  String LSCPServer::AddChannel() { Line 979  String LSCPServer::AddChannel() {
979  String LSCPServer::RemoveChannel(uint uiSamplerChannel) {  String LSCPServer::RemoveChannel(uint uiSamplerChannel) {
980      dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel));      dmsg(2,("LSCPServer: RemoveChannel(SamplerChannel=%d)\n", uiSamplerChannel));
981      LSCPResultSet result;      LSCPResultSet result;
982        LockRTNotify();
983      pSampler->RemoveSamplerChannel(uiSamplerChannel);      pSampler->RemoveSamplerChannel(uiSamplerChannel);
984        UnlockRTNotify();
985      return result.Produce();      return result.Produce();
986  }  }
987    
988  /**  /**
989   * 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.
990   */   */
991  String LSCPServer::GetAvailableEngines() {  String LSCPServer::GetAvailableEngines() {
992      dmsg(2,("LSCPServer: GetAvailableEngines()\n"));      dmsg(2,("LSCPServer: GetAvailableEngines()\n"));
993      LSCPResultSet result("GigEngine");      LSCPResultSet result;
994        try {
995            int n = EngineFactory::AvailableEngineTypes().size();
996            result.Add(n);
997        }
998        catch (Exception e) {
999            result.Error(e);
1000        }
1001        return result.Produce();
1002    }
1003    
1004    /**
1005     * Will be called by the parser to get a list of all available engines.
1006     */
1007    String LSCPServer::ListAvailableEngines() {
1008        dmsg(2,("LSCPServer: ListAvailableEngines()\n"));
1009        LSCPResultSet result;
1010        try {
1011            String s = EngineFactory::AvailableEngineTypesAsString();
1012            result.Add(s);
1013        }
1014        catch (Exception e) {
1015            result.Error(e);
1016        }
1017      return result.Produce();      return result.Produce();
1018  }  }
1019    
1020  /**  /**
1021   * 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
1022     * sampler engine.
1023   */   */
1024  String LSCPServer::GetEngineInfo(String EngineName) {  String LSCPServer::GetEngineInfo(String EngineName) {
1025      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));      dmsg(2,("LSCPServer: GetEngineInfo(EngineName=%s)\n", EngineName.c_str()));
1026      LSCPResultSet result;      LSCPResultSet result;
1027        LockRTNotify();
1028      try {      try {
1029          if ((EngineName == "GigEngine") || (EngineName == "gig")) {          Engine* pEngine = EngineFactory::Create(EngineName);
1030              Engine* pEngine = new LinuxSampler::gig::Engine;          result.Add("DESCRIPTION", _escapeLscpResponse(pEngine->Description()));
1031              result.Add(pEngine->Description());          result.Add("VERSION",     pEngine->Version());
1032              result.Add(pEngine->Version());          EngineFactory::Destroy(pEngine);
             delete pEngine;  
         }  
         else throw LinuxSamplerException("Unknown engine type");  
1033      }      }
1034      catch (LinuxSamplerException e) {      catch (Exception e) {
1035           result.Error(e);           result.Error(e);
1036      }      }
1037        UnlockRTNotify();
1038      return result.Produce();      return result.Produce();
1039  }  }
1040    
# Line 238  String LSCPServer::GetChannelInfo(uint u Line 1047  String LSCPServer::GetChannelInfo(uint u
1047      LSCPResultSet result;      LSCPResultSet result;
1048      try {      try {
1049          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1050          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1051          Engine* pEngine = pSamplerChannel->GetEngine();          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1052    
1053          //Defaults values          //Defaults values
1054          String EngineName = "NONE";          String EngineName = "NONE";
1055          float Volume = 0;          float Volume = 0.0f;
1056          String InstrumentFileName = "NONE";          String InstrumentFileName = "NONE";
1057            String InstrumentName = "NONE";
1058          int InstrumentIndex = -1;          int InstrumentIndex = -1;
1059          int InstrumentStatus = -1;          int InstrumentStatus = -1;
1060            int AudioOutputChannels = 0;
1061          if (pEngine) {          String AudioRouting;
1062              EngineName =  pEngine->EngineName();          int Mute = 0;
1063              Volume = pEngine->Volume();          bool Solo = false;
1064              InstrumentStatus = pEngine->InstrumentStatus();          String MidiInstrumentMap = "NONE";
1065              InstrumentIndex = pEngine->InstrumentIndex();  
1066              if (InstrumentIndex != -1)          if (pEngineChannel) {
1067                  InstrumentFileName = pEngine->InstrumentFileName();              EngineName          = pEngineChannel->EngineName();
1068                AudioOutputChannels = pEngineChannel->Channels();
1069                Volume              = pEngineChannel->Volume();
1070                InstrumentStatus    = pEngineChannel->InstrumentStatus();
1071                InstrumentIndex     = pEngineChannel->InstrumentIndex();
1072                if (InstrumentIndex != -1) {
1073                    InstrumentFileName = pEngineChannel->InstrumentFileName();
1074                    InstrumentName     = pEngineChannel->InstrumentName();
1075                }
1076                for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {
1077                    if (AudioRouting != "") AudioRouting += ",";
1078                    AudioRouting += ToString(pEngineChannel->OutputChannel(chan));
1079                }
1080                Mute = pEngineChannel->GetMute();
1081                Solo = pEngineChannel->GetSolo();
1082                if (pEngineChannel->UsesNoMidiInstrumentMap())
1083                    MidiInstrumentMap = "NONE";
1084                else if (pEngineChannel->UsesDefaultMidiInstrumentMap())
1085                    MidiInstrumentMap = "DEFAULT";
1086                else
1087                    MidiInstrumentMap = ToString(pEngineChannel->GetMidiInstrumentMap());
1088          }          }
1089    
1090          result.Add("ENGINE_NAME", EngineName);          result.Add("ENGINE_NAME", EngineName);
1091          result.Add("VOLUME", Volume);          result.Add("VOLUME", Volume);
1092    
1093          //Some hardcoded stuff for now to make GUI look good          //Some not-so-hardcoded stuff to make GUI look good
1094          result.Add("AUDIO_OUTPUT_DEVICE", "0");          result.Add("AUDIO_OUTPUT_DEVICE", GetAudioOutputDeviceIndex(pSamplerChannel->GetAudioOutputDevice()));
1095          result.Add("AUDIO_OUTPUT_CHANNELS", "2");          result.Add("AUDIO_OUTPUT_CHANNELS", AudioOutputChannels);
1096          result.Add("AUDIO_OUTPUT_ROUTING", "0,1");          result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
1097    
1098            result.Add("MIDI_INPUT_DEVICE", GetMidiInputDeviceIndex(pSamplerChannel->GetMidiInputDevice()));
1099            result.Add("MIDI_INPUT_PORT", pSamplerChannel->GetMidiInputPort());
1100            if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
1101            else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
1102    
1103            // convert the filename into the correct encoding as defined for LSCP
1104            // (especially in terms of special characters -> escape sequences)
1105            if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
1106    #if WIN32
1107                InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
1108    #else
1109                // assuming POSIX
1110                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
1111    #endif
1112            }
1113    
1114          result.Add("INSTRUMENT_FILE", InstrumentFileName);          result.Add("INSTRUMENT_FILE", InstrumentFileName);
1115          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
1116            result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
1117          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
1118            result.Add("MUTE", Mute == -1 ? "MUTED_BY_SOLO" : (Mute ? "true" : "false"));
1119          //Some more hardcoded stuff for now to make GUI look good          result.Add("SOLO", Solo);
1120          result.Add("MIDI_INPUT_DEVICE", "0");          result.Add("MIDI_INSTRUMENT_MAP", MidiInstrumentMap);
         result.Add("MIDI_INPUT_PORT", "0");  
         result.Add("MIDI_INPUT_CHANNEL", "1");  
1121      }      }
1122      catch (LinuxSamplerException e) {      catch (Exception e) {
1123           result.Error(e);           result.Error(e);
1124      }      }
1125      return result.Produce();      return result.Produce();
# Line 289  String LSCPServer::GetVoiceCount(uint ui Line 1134  String LSCPServer::GetVoiceCount(uint ui
1134      LSCPResultSet result;      LSCPResultSet result;
1135      try {      try {
1136          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1137          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1138          Engine* pEngine = pSamplerChannel->GetEngine();          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1139          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");          if (!pEngineChannel) throw Exception("No engine loaded on sampler channel");
1140          result.Add(pEngine->VoiceCount());          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1141            result.Add(pEngineChannel->GetEngine()->VoiceCount());
1142      }      }
1143      catch (LinuxSamplerException e) {      catch (Exception e) {
1144           result.Error(e);           result.Error(e);
1145      }      }
1146      return result.Produce();      return result.Produce();
# Line 309  String LSCPServer::GetStreamCount(uint u Line 1155  String LSCPServer::GetStreamCount(uint u
1155      LSCPResultSet result;      LSCPResultSet result;
1156      try {      try {
1157          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1158          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1159          Engine* pEngine = pSamplerChannel->GetEngine();          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1160          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");          if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
1161          result.Add(pEngine->DiskStreamCount());          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1162            result.Add(pEngineChannel->GetEngine()->DiskStreamCount());
1163      }      }
1164      catch (LinuxSamplerException e) {      catch (Exception e) {
1165           result.Error(e);           result.Error(e);
1166      }      }
1167      return result.Produce();      return result.Produce();
# Line 329  String LSCPServer::GetBufferFill(fill_re Line 1176  String LSCPServer::GetBufferFill(fill_re
1176      LSCPResultSet result;      LSCPResultSet result;
1177      try {      try {
1178          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1179          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1180          Engine* pEngine = pSamplerChannel->GetEngine();          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1181          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");          if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
1182          if (!pEngine->DiskStreamSupported())          if (!pEngineChannel->GetEngine()) throw Exception("No audio output device connected to sampler channel");
1183              result.Add("NA");          if (!pEngineChannel->GetEngine()->DiskStreamSupported()) result.Add("NA");
1184          else {          else {
1185              switch (ResponseType) {              switch (ResponseType) {
1186                  case fill_response_bytes:                  case fill_response_bytes:
1187                      result.Add(pEngine->DiskStreamBufferFillBytes());                      result.Add(pEngineChannel->GetEngine()->DiskStreamBufferFillBytes());
1188                      break;                      break;
1189                  case fill_response_percentage:                  case fill_response_percentage:
1190                      result.Add(pEngine->DiskStreamBufferFillPercentage());                      result.Add(pEngineChannel->GetEngine()->DiskStreamBufferFillPercentage());
1191                      break;                      break;
1192                  default:                  default:
1193                      throw LinuxSamplerException("Unknown fill response type");                      throw Exception("Unknown fill response type");
1194              }              }
1195          }          }
1196      }      }
1197      catch (LinuxSamplerException e) {      catch (Exception e) {
1198           result.Error(e);           result.Error(e);
1199      }      }
1200      return result.Produce();      return result.Produce();
# Line 357  String LSCPServer::GetAvailableAudioOutp Line 1204  String LSCPServer::GetAvailableAudioOutp
1204      dmsg(2,("LSCPServer: GetAvailableAudioOutputDrivers()\n"));      dmsg(2,("LSCPServer: GetAvailableAudioOutputDrivers()\n"));
1205      LSCPResultSet result;      LSCPResultSet result;
1206      try {      try {
1207            int n = AudioOutputDeviceFactory::AvailableDrivers().size();
1208            result.Add(n);
1209        }
1210        catch (Exception e) {
1211            result.Error(e);
1212        }
1213        return result.Produce();
1214    }
1215    
1216    String LSCPServer::ListAvailableAudioOutputDrivers() {
1217        dmsg(2,("LSCPServer: ListAvailableAudioOutputDrivers()\n"));
1218        LSCPResultSet result;
1219        try {
1220          String s = AudioOutputDeviceFactory::AvailableDriversAsString();          String s = AudioOutputDeviceFactory::AvailableDriversAsString();
1221          result.Add(s);          result.Add(s);
1222      }      }
1223      catch (LinuxSamplerException e) {      catch (Exception e) {
1224            result.Error(e);
1225        }
1226        return result.Produce();
1227    }
1228    
1229    String LSCPServer::GetAvailableMidiInputDrivers() {
1230        dmsg(2,("LSCPServer: GetAvailableMidiInputDrivers()\n"));
1231        LSCPResultSet result;
1232        try {
1233            int n = MidiInputDeviceFactory::AvailableDrivers().size();
1234            result.Add(n);
1235        }
1236        catch (Exception e) {
1237            result.Error(e);
1238        }
1239        return result.Produce();
1240    }
1241    
1242    String LSCPServer::ListAvailableMidiInputDrivers() {
1243        dmsg(2,("LSCPServer: ListAvailableMidiInputDrivers()\n"));
1244        LSCPResultSet result;
1245        try {
1246            String s = MidiInputDeviceFactory::AvailableDriversAsString();
1247            result.Add(s);
1248        }
1249        catch (Exception e) {
1250            result.Error(e);
1251        }
1252        return result.Produce();
1253    }
1254    
1255    String LSCPServer::GetMidiInputDriverInfo(String Driver) {
1256        dmsg(2,("LSCPServer: GetMidiInputDriverInfo(Driver=%s)\n",Driver.c_str()));
1257        LSCPResultSet result;
1258        try {
1259            result.Add("DESCRIPTION", MidiInputDeviceFactory::GetDriverDescription(Driver));
1260            result.Add("VERSION",     MidiInputDeviceFactory::GetDriverVersion(Driver));
1261    
1262            std::map<String,DeviceCreationParameter*> parameters = MidiInputDeviceFactory::GetAvailableDriverParameters(Driver);
1263            if (parameters.size()) { // if there are parameters defined for this driver
1264                String s;
1265                std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();
1266                for (;iter != parameters.end(); iter++) {
1267                    if (s != "") s += ",";
1268                    s += iter->first;
1269                }
1270                result.Add("PARAMETERS", s);
1271            }
1272        }
1273        catch (Exception e) {
1274          result.Error(e);          result.Error(e);
1275      }      }
1276      return result.Produce();      return result.Produce();
# Line 384  String LSCPServer::GetAudioOutputDriverI Line 1294  String LSCPServer::GetAudioOutputDriverI
1294              result.Add("PARAMETERS", s);              result.Add("PARAMETERS", s);
1295          }          }
1296      }      }
1297      catch (LinuxSamplerException e) {      catch (Exception e) {
1298            result.Error(e);
1299        }
1300        return result.Produce();
1301    }
1302    
1303    String LSCPServer::GetMidiInputDriverParameterInfo(String Driver, String Parameter, std::map<String,String> DependencyList) {
1304        dmsg(2,("LSCPServer: GetMidiInputDriverParameterInfo(Driver=%s,Parameter=%s,DependencyListSize=%d)\n",Driver.c_str(),Parameter.c_str(),DependencyList.size()));
1305        LSCPResultSet result;
1306        try {
1307            DeviceCreationParameter* pParameter = MidiInputDeviceFactory::GetDriverParameter(Driver, Parameter);
1308            result.Add("TYPE",         pParameter->Type());
1309            result.Add("DESCRIPTION",  pParameter->Description());
1310            result.Add("MANDATORY",    pParameter->Mandatory());
1311            result.Add("FIX",          pParameter->Fix());
1312            result.Add("MULTIPLICITY", pParameter->Multiplicity());
1313            optional<String> oDepends       = pParameter->Depends();
1314            optional<String> oDefault       = pParameter->Default(DependencyList);
1315            optional<String> oRangeMin      = pParameter->RangeMin(DependencyList);
1316            optional<String> oRangeMax      = pParameter->RangeMax(DependencyList);
1317            optional<String> oPossibilities = pParameter->Possibilities(DependencyList);
1318            if (oDepends)       result.Add("DEPENDS",       *oDepends);
1319            if (oDefault)       result.Add("DEFAULT",       *oDefault);
1320            if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1321            if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1322            if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1323        }
1324        catch (Exception e) {
1325          result.Error(e);          result.Error(e);
1326      }      }
1327      return result.Produce();      return result.Produce();
1328  }  }
1329    
1330  String LSCPServer::GetAudioOutputDriverParameterInfo(String Driver, String Parameter, std::map<String,String> DependencyList) {  String LSCPServer::GetAudioOutputDriverParameterInfo(String Driver, String Parameter, std::map<String,String> DependencyList) {
1331      dmsg(2,("LSCPServer: GetAudioOutputDriverParameterInfo(Driver=%s,Parameter=%s)\n",Driver.c_str(),Parameter.c_str()));      dmsg(2,("LSCPServer: GetAudioOutputDriverParameterInfo(Driver=%s,Parameter=%s,DependencyListSize=%d)\n",Driver.c_str(),Parameter.c_str(),DependencyList.size()));
1332      LSCPResultSet result;      LSCPResultSet result;
1333      try {      try {
1334          DeviceCreationParameter* pParameter = AudioOutputDeviceFactory::GetDriverParameter(Driver, Parameter);          DeviceCreationParameter* pParameter = AudioOutputDeviceFactory::GetDriverParameter(Driver, Parameter);
# Line 400  String LSCPServer::GetAudioOutputDriverP Line 1337  String LSCPServer::GetAudioOutputDriverP
1337          result.Add("MANDATORY",    pParameter->Mandatory());          result.Add("MANDATORY",    pParameter->Mandatory());
1338          result.Add("FIX",          pParameter->Fix());          result.Add("FIX",          pParameter->Fix());
1339          result.Add("MULTIPLICITY", pParameter->Multiplicity());          result.Add("MULTIPLICITY", pParameter->Multiplicity());
1340          if (pParameter->Depends())       result.Add("DEPENDS",       pParameter->Depends());          optional<String> oDepends       = pParameter->Depends();
1341          if (pParameter->Default())       result.Add("DEFAULT",       pParameter->Default());          optional<String> oDefault       = pParameter->Default(DependencyList);
1342          if (pParameter->RangeMin())      result.Add("RANGE_MIN",     pParameter->RangeMin());          optional<String> oRangeMin      = pParameter->RangeMin(DependencyList);
1343          if (pParameter->RangeMax())      result.Add("RANGE_MAX",     pParameter->RangeMax());          optional<String> oRangeMax      = pParameter->RangeMax(DependencyList);
1344          if (pParameter->Possibilities()) result.Add("POSSIBILITIES", pParameter->Possibilities());          optional<String> oPossibilities = pParameter->Possibilities(DependencyList);
1345            if (oDepends)       result.Add("DEPENDS",       *oDepends);
1346            if (oDefault)       result.Add("DEFAULT",       *oDefault);
1347            if (oRangeMin)      result.Add("RANGE_MIN",     *oRangeMin);
1348            if (oRangeMax)      result.Add("RANGE_MAX",     *oRangeMax);
1349            if (oPossibilities) result.Add("POSSIBILITIES", *oPossibilities);
1350      }      }
1351      catch (LinuxSamplerException e) {      catch (Exception e) {
1352          result.Error(e);          result.Error(e);
1353      }      }
1354      return result.Produce();      return result.Produce();
# Line 417  String LSCPServer::GetAudioOutputDeviceC Line 1359  String LSCPServer::GetAudioOutputDeviceC
1359      LSCPResultSet result;      LSCPResultSet result;
1360      try {      try {
1361          uint count = pSampler->AudioOutputDevices();          uint count = pSampler->AudioOutputDevices();
1362          result = count; // success          result.Add(count); // success
1363        }
1364        catch (Exception e) {
1365            result.Error(e);
1366      }      }
1367      catch (LinuxSamplerException e) {      return result.Produce();
1368    }
1369    
1370    String LSCPServer::GetMidiInputDeviceCount() {
1371        dmsg(2,("LSCPServer: GetMidiInputDeviceCount()\n"));
1372        LSCPResultSet result;
1373        try {
1374            uint count = pSampler->MidiInputDevices();
1375            result.Add(count); // success
1376        }
1377        catch (Exception e) {
1378          result.Error(e);          result.Error(e);
1379      }      }
1380      return result.Produce();      return result.Produce();
# Line 438  String LSCPServer::GetAudioOutputDevices Line 1393  String LSCPServer::GetAudioOutputDevices
1393          }          }
1394          result.Add(s);          result.Add(s);
1395      }      }
1396      catch (LinuxSamplerException e) {      catch (Exception e) {
1397            result.Error(e);
1398        }
1399        return result.Produce();
1400    }
1401    
1402    String LSCPServer::GetMidiInputDevices() {
1403        dmsg(2,("LSCPServer: GetMidiInputDevices()\n"));
1404        LSCPResultSet result;
1405        try {
1406            String s;
1407            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1408            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
1409            for (; iter != devices.end(); iter++) {
1410                if (s != "") s += ",";
1411                s += ToString(iter->first);
1412            }
1413            result.Add(s);
1414        }
1415        catch (Exception e) {
1416          result.Error(e);          result.Error(e);
1417      }      }
1418      return result.Produce();      return result.Produce();
# Line 449  String LSCPServer::GetAudioOutputDeviceI Line 1423  String LSCPServer::GetAudioOutputDeviceI
1423      LSCPResultSet result;      LSCPResultSet result;
1424      try {      try {
1425          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1426          if (!devices[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) + ".");
1427          AudioOutputDevice* pDevice = devices[DeviceIndex];          AudioOutputDevice* pDevice = devices[DeviceIndex];
1428            result.Add("DRIVER", pDevice->Driver());
1429          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1430          std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();          std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();
1431          for (; iter != parameters.end(); iter++) {          for (; iter != parameters.end(); iter++) {
1432              result.Add(iter->first, iter->second->Value());              result.Add(iter->first, iter->second->Value());
1433          }          }
1434      }      }
1435      catch (LinuxSamplerException e) {      catch (Exception e) {
1436            result.Error(e);
1437        }
1438        return result.Produce();
1439    }
1440    
1441    String LSCPServer::GetMidiInputDeviceInfo(uint DeviceIndex) {
1442        dmsg(2,("LSCPServer: GetMidiInputDeviceInfo(DeviceIndex=%d)\n",DeviceIndex));
1443        LSCPResultSet result;
1444        try {
1445            std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1446            if (!devices.count(DeviceIndex)) throw Exception("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1447            MidiInputDevice* pDevice = devices[DeviceIndex];
1448            result.Add("DRIVER", pDevice->Driver());
1449            std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1450            std::map<String,DeviceCreationParameter*>::iterator iter = parameters.begin();
1451            for (; iter != parameters.end(); iter++) {
1452                result.Add(iter->first, iter->second->Value());
1453            }
1454        }
1455        catch (Exception e) {
1456            result.Error(e);
1457        }
1458        return result.Produce();
1459    }
1460    String LSCPServer::GetMidiInputPortInfo(uint DeviceIndex, uint PortIndex) {
1461        dmsg(2,("LSCPServer: GetMidiInputPortInfo(DeviceIndex=%d, PortIndex=%d)\n",DeviceIndex, PortIndex));
1462        LSCPResultSet result;
1463        try {
1464            // get MIDI input device
1465            std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1466            if (!devices.count(DeviceIndex)) throw Exception("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1467            MidiInputDevice* pDevice = devices[DeviceIndex];
1468    
1469            // get MIDI port
1470            MidiInputPort* pMidiInputPort = pDevice->GetPort(PortIndex);
1471            if (!pMidiInputPort) throw Exception("There is no MIDI input port with index " + ToString(PortIndex) + ".");
1472    
1473            // return the values of all MIDI port parameters
1474            std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();
1475            std::map<String,DeviceRuntimeParameter*>::iterator iter = parameters.begin();
1476            for (; iter != parameters.end(); iter++) {
1477                result.Add(iter->first, iter->second->Value());
1478            }
1479        }
1480        catch (Exception e) {
1481          result.Error(e);          result.Error(e);
1482      }      }
1483      return result.Produce();      return result.Produce();
# Line 469  String LSCPServer::GetAudioOutputChannel Line 1489  String LSCPServer::GetAudioOutputChannel
1489      try {      try {
1490          // get audio output device          // get audio output device
1491          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1492          if (!devices[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) + ".");
1493          AudioOutputDevice* pDevice = devices[DeviceId];          AudioOutputDevice* pDevice = devices[DeviceId];
1494    
1495          // get audio channel          // get audio channel
1496          AudioChannel* pChannel = pDevice->Channel(ChannelId);          AudioChannel* pChannel = pDevice->Channel(ChannelId);
1497          if (!pChannel) throw LinuxSamplerException("Audio ouotput device does not have channel " + ToString(ChannelId) + ".");          if (!pChannel) throw Exception("Audio output device does not have audio channel " + ToString(ChannelId) + ".");
1498    
1499          // return the values of all audio channel parameters          // return the values of all audio channel parameters
1500          std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();          std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();
# Line 483  String LSCPServer::GetAudioOutputChannel Line 1503  String LSCPServer::GetAudioOutputChannel
1503              result.Add(iter->first, iter->second->Value());              result.Add(iter->first, iter->second->Value());
1504          }          }
1505      }      }
1506      catch (LinuxSamplerException e) {      catch (Exception e) {
1507            result.Error(e);
1508        }
1509        return result.Produce();
1510    }
1511    
1512    String LSCPServer::GetMidiInputPortParameterInfo(uint DeviceId, uint PortId, String ParameterName) {
1513        dmsg(2,("LSCPServer: GetMidiInputPortParameterInfo(DeviceId=%d,PortId=%d,ParameterName=%s)\n",DeviceId,PortId,ParameterName.c_str()));
1514        LSCPResultSet result;
1515        try {
1516            // get MIDI input device
1517            std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1518            if (!devices.count(DeviceId)) throw Exception("There is no midi input device with index " + ToString(DeviceId) + ".");
1519            MidiInputDevice* pDevice = devices[DeviceId];
1520    
1521            // get midi port
1522            MidiInputPort* pPort = pDevice->GetPort(PortId);
1523            if (!pPort) throw Exception("Midi input device does not have port " + ToString(PortId) + ".");
1524    
1525            // get desired port parameter
1526            std::map<String,DeviceRuntimeParameter*> parameters = pPort->PortParameters();
1527            if (!parameters.count(ParameterName)) throw Exception("Midi port does not provide a parameter '" + ParameterName + "'.");
1528            DeviceRuntimeParameter* pParameter = parameters[ParameterName];
1529    
1530            // return all fields of this audio channel parameter
1531            result.Add("TYPE",         pParameter->Type());
1532            result.Add("DESCRIPTION",  pParameter->Description());
1533            result.Add("FIX",          pParameter->Fix());
1534            result.Add("MULTIPLICITY", pParameter->Multiplicity());
1535            if (pParameter->RangeMin())      result.Add("RANGE_MIN",     *pParameter->RangeMin());
1536            if (pParameter->RangeMax())      result.Add("RANGE_MAX",     *pParameter->RangeMax());
1537            if (pParameter->Possibilities()) result.Add("POSSIBILITIES", *pParameter->Possibilities());
1538        }
1539        catch (Exception e) {
1540          result.Error(e);          result.Error(e);
1541      }      }
1542      return result.Produce();      return result.Produce();
# Line 495  String LSCPServer::GetAudioOutputChannel Line 1548  String LSCPServer::GetAudioOutputChannel
1548      try {      try {
1549          // get audio output device          // get audio output device
1550          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1551          if (!devices[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) + ".");
1552          AudioOutputDevice* pDevice = devices[DeviceId];          AudioOutputDevice* pDevice = devices[DeviceId];
1553    
1554          // get audio channel          // get audio channel
1555          AudioChannel* pChannel = pDevice->Channel(ChannelId);          AudioChannel* pChannel = pDevice->Channel(ChannelId);
1556          if (!pChannel) throw LinuxSamplerException("Audio output device does not have channel " + ToString(ChannelId) + ".");          if (!pChannel) throw Exception("Audio output device does not have audio channel " + ToString(ChannelId) + ".");
1557    
1558          // get desired audio channel parameter          // get desired audio channel parameter
1559          std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();          std::map<String,DeviceRuntimeParameter*> parameters = pChannel->ChannelParameters();
1560          if (!parameters[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 + "'.");
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 512  String LSCPServer::GetAudioOutputChannel Line 1565  String LSCPServer::GetAudioOutputChannel
1565          result.Add("DESCRIPTION",  pParameter->Description());          result.Add("DESCRIPTION",  pParameter->Description());
1566          result.Add("FIX",          pParameter->Fix());          result.Add("FIX",          pParameter->Fix());
1567          result.Add("MULTIPLICITY", pParameter->Multiplicity());          result.Add("MULTIPLICITY", pParameter->Multiplicity());
1568          if (pParameter->RangeMin())      result.Add("RANGE_MIN",     pParameter->RangeMin());          if (pParameter->RangeMin())      result.Add("RANGE_MIN",     *pParameter->RangeMin());
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 528  String LSCPServer::SetAudioOutputChannel Line 1581  String LSCPServer::SetAudioOutputChannel
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[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 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[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 + "'.");
1594          DeviceRuntimeParameter* pParameter = parameters[ParamKey];          DeviceRuntimeParameter* pParameter = parameters[ParamKey];
1595    
1596          // set new channel parameter value          // set new channel parameter value
1597          pParameter->SetValue(ParamVal);          pParameter->SetValue(ParamVal);
1598            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_info, DeviceId));
1599      }      }
1600      catch (LinuxSamplerException e) {      catch (Exception e) {
1601          result.Error(e);          result.Error(e);
1602      }      }
1603      return result.Produce();      return result.Produce();
# Line 554  String LSCPServer::SetAudioOutputDeviceP Line 1608  String LSCPServer::SetAudioOutputDeviceP
1608      LSCPResultSet result;      LSCPResultSet result;
1609      try {      try {
1610          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();          std::map<uint,AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1611          if (!devices[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) + ".");
1612          AudioOutputDevice* pDevice = devices[DeviceIndex];          AudioOutputDevice* pDevice = devices[DeviceIndex];
1613          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();          std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1614          if (!parameters[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 + "'");
1615          parameters[ParamKey]->SetValue(ParamVal);          parameters[ParamKey]->SetValue(ParamVal);
1616            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_audio_device_info, DeviceIndex));
1617      }      }
1618      catch (LinuxSamplerException e) {      catch (Exception e) {
1619            result.Error(e);
1620        }
1621        return result.Produce();
1622    }
1623    
1624    String LSCPServer::SetMidiInputDeviceParameter(uint DeviceIndex, String ParamKey, String ParamVal) {
1625        dmsg(2,("LSCPServer: SetMidiOutputDeviceParameter(DeviceIndex=%d,ParamKey=%s,ParamVal=%s)\n",DeviceIndex,ParamKey.c_str(),ParamVal.c_str()));
1626        LSCPResultSet result;
1627        try {
1628            std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1629            if (!devices.count(DeviceIndex)) throw Exception("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1630            MidiInputDevice* pDevice = devices[DeviceIndex];
1631            std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1632            if (!parameters.count(ParamKey)) throw Exception("MIDI input device " + ToString(DeviceIndex) + " does not have a device parameter '" + ParamKey + "'");
1633            parameters[ParamKey]->SetValue(ParamVal);
1634            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_info, DeviceIndex));
1635        }
1636        catch (Exception e) {
1637            result.Error(e);
1638        }
1639        return result.Produce();
1640    }
1641    
1642    String LSCPServer::SetMidiInputPortParameter(uint DeviceIndex, uint PortIndex, String ParamKey, String ParamVal) {
1643        dmsg(2,("LSCPServer: SetMidiOutputDeviceParameter(DeviceIndex=%d,ParamKey=%s,ParamVal=%s)\n",DeviceIndex,ParamKey.c_str(),ParamVal.c_str()));
1644        LSCPResultSet result;
1645        try {
1646            // get MIDI input device
1647            std::map<uint,MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1648            if (!devices.count(DeviceIndex)) throw Exception("There is no MIDI input device with index " + ToString(DeviceIndex) + ".");
1649            MidiInputDevice* pDevice = devices[DeviceIndex];
1650    
1651            // get MIDI port
1652            MidiInputPort* pMidiInputPort = pDevice->GetPort(PortIndex);
1653            if (!pMidiInputPort) throw Exception("There is no MIDI input port with index " + ToString(PortIndex) + ".");
1654    
1655            // set port parameter value
1656            std::map<String,DeviceRuntimeParameter*> parameters = pMidiInputPort->PortParameters();
1657            if (!parameters.count(ParamKey)) throw Exception("MIDI input device " + ToString(PortIndex) + " does not have a parameter '" + ParamKey + "'");
1658            parameters[ParamKey]->SetValue(ParamVal);
1659            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_midi_device_info, DeviceIndex));
1660        }
1661        catch (Exception e) {
1662          result.Error(e);          result.Error(e);
1663      }      }
1664      return result.Produce();      return result.Produce();
# Line 572  String LSCPServer::SetAudioOutputDeviceP Line 1670  String LSCPServer::SetAudioOutputDeviceP
1670   */   */
1671  String LSCPServer::SetAudioOutputChannel(uint ChannelAudioOutputChannel, uint AudioOutputDeviceInputChannel, uint uiSamplerChannel) {  String LSCPServer::SetAudioOutputChannel(uint ChannelAudioOutputChannel, uint AudioOutputDeviceInputChannel, uint uiSamplerChannel) {
1672      dmsg(2,("LSCPServer: SetAudioOutputChannel(ChannelAudioOutputChannel=%d, AudioOutputDeviceInputChannel=%d, SamplerChannel=%d)\n",ChannelAudioOutputChannel,AudioOutputDeviceInputChannel,uiSamplerChannel));      dmsg(2,("LSCPServer: SetAudioOutputChannel(ChannelAudioOutputChannel=%d, AudioOutputDeviceInputChannel=%d, SamplerChannel=%d)\n",ChannelAudioOutputChannel,AudioOutputDeviceInputChannel,uiSamplerChannel));
1673      return "ERR:0:Not implemented yet.\r\n"; //FIXME: Add support for this in resultset class?      LSCPResultSet result;
1674        try {
1675            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1676            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1677            EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1678            if (!pEngineChannel) throw Exception("No engine type yet assigned to sampler channel " + ToString(uiSamplerChannel));
1679            if (!pSamplerChannel->GetAudioOutputDevice()) throw Exception("No audio output device connected to sampler channel " + ToString(uiSamplerChannel));
1680            pEngineChannel->SetOutputChannel(ChannelAudioOutputChannel, AudioOutputDeviceInputChannel);
1681        }
1682        catch (Exception e) {
1683             result.Error(e);
1684        }
1685        return result.Produce();
1686    }
1687    
1688    String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint uiSamplerChannel) {
1689        dmsg(2,("LSCPServer: SetAudiotOutputDevice(AudioDeviceId=%d, SamplerChannel=%d)\n",AudioDeviceId,uiSamplerChannel));
1690        LSCPResultSet result;
1691        LockRTNotify();
1692        try {
1693            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1694            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1695            std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1696            if (!devices.count(AudioDeviceId)) throw Exception("There is no audio output device with index " + ToString(AudioDeviceId));
1697            AudioOutputDevice* pDevice = devices[AudioDeviceId];
1698            pSamplerChannel->SetAudioOutputDevice(pDevice);
1699        }
1700        catch (Exception e) {
1701             result.Error(e);
1702        }
1703        UnlockRTNotify();
1704        return result.Produce();
1705    }
1706    
1707    String LSCPServer::SetAudioOutputType(String AudioOutputDriver, uint uiSamplerChannel) {
1708        dmsg(2,("LSCPServer: SetAudioOutputType(String AudioOutputDriver=%s, SamplerChannel=%d)\n",AudioOutputDriver.c_str(),uiSamplerChannel));
1709        LSCPResultSet result;
1710        LockRTNotify();
1711        try {
1712            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1713            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1714            // Driver type name aliasing...
1715            if (AudioOutputDriver == "Alsa") AudioOutputDriver = "ALSA";
1716            if (AudioOutputDriver == "Jack") AudioOutputDriver = "JACK";
1717            // Check if there's one audio output device already created
1718            // for the intended audio driver type (AudioOutputDriver)...
1719            AudioOutputDevice *pDevice = NULL;
1720            std::map<uint, AudioOutputDevice*> devices = pSampler->GetAudioOutputDevices();
1721            std::map<uint, AudioOutputDevice*>::iterator iter = devices.begin();
1722            for (; iter != devices.end(); iter++) {
1723                if ((iter->second)->Driver() == AudioOutputDriver) {
1724                    pDevice = iter->second;
1725                    break;
1726                }
1727            }
1728            // If it doesn't exist, create a new one with default parameters...
1729            if (pDevice == NULL) {
1730                std::map<String,String> params;
1731                pDevice = pSampler->CreateAudioOutputDevice(AudioOutputDriver, params);
1732            }
1733            // Must have a device...
1734            if (pDevice == NULL)
1735                throw Exception("Internal error: could not create audio output device.");
1736            // Set it as the current channel device...
1737            pSamplerChannel->SetAudioOutputDevice(pDevice);
1738        }
1739        catch (Exception e) {
1740             result.Error(e);
1741        }
1742        UnlockRTNotify();
1743        return result.Produce();
1744    }
1745    
1746    String LSCPServer::SetMIDIInputPort(uint MIDIPort, uint uiSamplerChannel) {
1747        dmsg(2,("LSCPServer: SetMIDIInputPort(MIDIPort=%d, SamplerChannel=%d)\n",MIDIPort,uiSamplerChannel));
1748        LSCPResultSet result;
1749        try {
1750            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1751            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1752            pSamplerChannel->SetMidiInputPort(MIDIPort);
1753        }
1754        catch (Exception e) {
1755             result.Error(e);
1756        }
1757        return result.Produce();
1758    }
1759    
1760    String LSCPServer::SetMIDIInputChannel(uint MIDIChannel, uint uiSamplerChannel) {
1761        dmsg(2,("LSCPServer: SetMIDIInputChannel(MIDIChannel=%d, SamplerChannel=%d)\n",MIDIChannel,uiSamplerChannel));
1762        LSCPResultSet result;
1763        try {
1764            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1765            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1766            pSamplerChannel->SetMidiInputChannel((midi_chan_t) MIDIChannel);
1767        }
1768        catch (Exception e) {
1769             result.Error(e);
1770        }
1771        return result.Produce();
1772    }
1773    
1774    String LSCPServer::SetMIDIInputDevice(uint MIDIDeviceId, uint uiSamplerChannel) {
1775        dmsg(2,("LSCPServer: SetMIDIInputDevice(MIDIDeviceId=%d, SamplerChannel=%d)\n",MIDIDeviceId,uiSamplerChannel));
1776        LSCPResultSet result;
1777        try {
1778            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1779            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1780            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1781            if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1782            MidiInputDevice* pDevice = devices[MIDIDeviceId];
1783            pSamplerChannel->SetMidiInputDevice(pDevice);
1784        }
1785        catch (Exception e) {
1786             result.Error(e);
1787        }
1788        return result.Produce();
1789  }  }
1790    
1791  String LSCPServer::SetMIDIInputType(String MidiInputDriver, uint uiSamplerChannel) {  String LSCPServer::SetMIDIInputType(String MidiInputDriver, uint uiSamplerChannel) {
# Line 580  String LSCPServer::SetMIDIInputType(Stri Line 1793  String LSCPServer::SetMIDIInputType(Stri
1793      LSCPResultSet result;      LSCPResultSet result;
1794      try {      try {
1795          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1796          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1797          // FIXME: workaround until MIDI driver configuration is implemented (using a Factory class for the MIDI input drivers then, like its already done for audio output drivers)          // Driver type name aliasing...
1798          if (MidiInputDriver != "ALSA") throw LinuxSamplerException("Unknown MIDI input driver '" + MidiInputDriver + "'.");          if (MidiInputDriver == "Alsa") MidiInputDriver = "ALSA";
1799          MidiInputDevice::type_t MidiInputType = MidiInputDevice::type_alsa;          // Check if there's one MIDI input device already created
1800          pSamplerChannel->SetMidiInputDevice(MidiInputType);          // for the intended MIDI driver type (MidiInputDriver)...
1801            MidiInputDevice *pDevice = NULL;
1802            std::map<uint, MidiInputDevice*> devices = pSampler->GetMidiInputDevices();
1803            std::map<uint, MidiInputDevice*>::iterator iter = devices.begin();
1804            for (; iter != devices.end(); iter++) {
1805                if ((iter->second)->Driver() == MidiInputDriver) {
1806                    pDevice = iter->second;
1807                    break;
1808                }
1809            }
1810            // If it doesn't exist, create a new one with default parameters...
1811            if (pDevice == NULL) {
1812                std::map<String,String> params;
1813                pDevice = pSampler->CreateMidiInputDevice(MidiInputDriver, params);
1814                // Make it with at least one initial port.
1815                std::map<String,DeviceCreationParameter*> parameters = pDevice->DeviceParameters();
1816                parameters["PORTS"]->SetValue("1");
1817            }
1818            // Must have a device...
1819            if (pDevice == NULL)
1820                throw Exception("Internal error: could not create MIDI input device.");
1821            // Set it as the current channel device...
1822            pSamplerChannel->SetMidiInputDevice(pDevice);
1823      }      }
1824      catch (LinuxSamplerException e) {      catch (Exception e) {
1825           result.Error(e);           result.Error(e);
1826      }      }
1827      return result.Produce();      return result.Produce();
1828  }  }
1829    
1830  /**  /**
1831   * Will be called by the parser to change the MIDI input port on which the   * Will be called by the parser to change the MIDI input device, port and channel on which
1832   * engine of a particular sampler channel should listen to.   * engine of a particular sampler channel should listen to.
1833   */   */
1834  String LSCPServer::SetMIDIInputPort(String MIDIInputPort, uint uiSamplerChannel) {  String LSCPServer::SetMIDIInput(uint MIDIDeviceId, uint MIDIPort, uint MIDIChannel, uint uiSamplerChannel) {
1835      dmsg(2,("LSCPServer: SetMIDIInputPort(MIDIInputPort=%s, Samplerchannel=%d)\n", MIDIInputPort.c_str(), uiSamplerChannel));      dmsg(2,("LSCPServer: SetMIDIInput(MIDIDeviceId=%d, MIDIPort=%d, MIDIChannel=%d, SamplerChannel=%d)\n", MIDIDeviceId, MIDIPort, MIDIChannel, uiSamplerChannel));
1836      LSCPResultSet result;      LSCPResultSet result;
1837      try {      try {
1838          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1839          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1840          if (!pSamplerChannel->GetMidiInputDevice()) throw LinuxSamplerException("No MIDI input device connected yet");          std::map<uint, MidiInputDevice*> devices =  pSampler->GetMidiInputDevices();
1841          pSamplerChannel->GetMidiInputDevice()->SetInputPort(MIDIInputPort.c_str());          if (!devices.count(MIDIDeviceId)) throw Exception("There is no MIDI input device with index " + ToString(MIDIDeviceId));
1842            MidiInputDevice* pDevice = devices[MIDIDeviceId];
1843            pSamplerChannel->SetMidiInput(pDevice, MIDIPort, (midi_chan_t) MIDIChannel);
1844      }      }
1845      catch (LinuxSamplerException e) {      catch (Exception e) {
1846           result.Error(e);           result.Error(e);
1847      }      }
1848      return result.Produce();      return result.Produce();
1849  }  }
1850    
1851  /**  /**
1852   * Will be called by the parser to change the MIDI input channel on which the   * Will be called by the parser to change the global volume factor on a
1853   * engine of a particular sampler channel should listen to.   * particular sampler channel.
1854   */   */
1855  String LSCPServer::SetMIDIInputChannel(uint MIDIChannel, uint uiSamplerChannel) {  String LSCPServer::SetVolume(double dVolume, uint uiSamplerChannel) {
1856      dmsg(2,("LSCPServer: SetMIDIInputChannel(MIDIChannel=%d, SamplerChannel=%d)\n", MIDIChannel, uiSamplerChannel));      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", dVolume, uiSamplerChannel));
1857      LSCPResultSet result;      LSCPResultSet result;
1858      try {      try {
1859          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1860          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1861          if (!pSamplerChannel->GetMidiInputDevice()) throw LinuxSamplerException("No MIDI input device connected yet");          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1862          MidiInputDevice::type_t oldtype = pSamplerChannel->GetMidiInputDevice()->Type();          if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
1863          pSamplerChannel->SetMidiInputDevice(oldtype, (MidiInputDevice::midi_chan_t) MIDIChannel);          pEngineChannel->Volume(dVolume);
1864      }      }
1865      catch (LinuxSamplerException e) {      catch (Exception e) {
1866           result.Error(e);           result.Error(e);
1867      }      }
1868      return result.Produce();      return result.Produce();
1869  }  }
1870    
1871  String LSCPServer::SetAudioOutputDevice(uint AudioDeviceId, uint SamplerChannel) {  /**
1872     * Will be called by the parser to mute/unmute particular sampler channel.
1873     */
1874    String LSCPServer::SetChannelMute(bool bMute, uint uiSamplerChannel) {
1875        dmsg(2,("LSCPServer: SetChannelMute(bMute=%d,uiSamplerChannel=%d)\n",bMute,uiSamplerChannel));
1876      LSCPResultSet result;      LSCPResultSet result;
1877      try {      try {
1878          throw LinuxSamplerException("Command not yet implemented");          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1879            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1880    
1881            EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1882            if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
1883    
1884            if(!bMute) pEngineChannel->SetMute((HasSoloChannel() && !pEngineChannel->GetSolo()) ? -1 : 0);
1885            else pEngineChannel->SetMute(1);
1886        } catch (Exception e) {
1887            result.Error(e);
1888      }      }
1889      catch (LinuxSamplerException e) {      return result.Produce();
1890           result.Error(e);  }
1891    
1892    /**
1893     * Will be called by the parser to solo particular sampler channel.
1894     */
1895    String LSCPServer::SetChannelSolo(bool bSolo, uint uiSamplerChannel) {
1896        dmsg(2,("LSCPServer: SetChannelSolo(bSolo=%d,uiSamplerChannel=%d)\n",bSolo,uiSamplerChannel));
1897        LSCPResultSet result;
1898        try {
1899            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
1900            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
1901    
1902            EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
1903            if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
1904    
1905            bool oldSolo = pEngineChannel->GetSolo();
1906            bool hadSoloChannel = HasSoloChannel();
1907    
1908            pEngineChannel->SetSolo(bSolo);
1909    
1910            if(!oldSolo && bSolo) {
1911                if(pEngineChannel->GetMute() == -1) pEngineChannel->SetMute(0);
1912                if(!hadSoloChannel) MuteNonSoloChannels();
1913            }
1914    
1915            if(oldSolo && !bSolo) {
1916                if(!HasSoloChannel()) UnmuteChannels();
1917                else if(!pEngineChannel->GetMute()) pEngineChannel->SetMute(-1);
1918            }
1919        } catch (Exception e) {
1920            result.Error(e);
1921      }      }
1922      return result.Produce();      return result.Produce();
1923  }  }
1924    
1925  /**  /**
1926   * Will be called by the parser to change the global volume factor on a   * Determines whether there is at least one solo channel in the channel list.
1927   * particular sampler channel.   *
1928     * @returns true if there is at least one solo channel in the channel list,
1929     * false otherwise.
1930     */
1931    bool LSCPServer::HasSoloChannel() {
1932        std::map<uint,SamplerChannel*> channels = pSampler->GetSamplerChannels();
1933        std::map<uint,SamplerChannel*>::iterator iter = channels.begin();
1934        for (; iter != channels.end(); iter++) {
1935            EngineChannel* c = iter->second->GetEngineChannel();
1936            if(c && c->GetSolo()) return true;
1937        }
1938    
1939        return false;
1940    }
1941    
1942    /**
1943     * Mutes all unmuted non-solo channels. Notice that the channels are muted
1944     * with -1 which indicates that they are muted because of the presence
1945     * of a solo channel(s). Channels muted with -1 will be automatically unmuted
1946     * when there are no solo channels left.
1947   */   */
1948  String LSCPServer::SetVolume(double Volume, uint uiSamplerChannel) {  void LSCPServer::MuteNonSoloChannels() {
1949      dmsg(2,("LSCPServer: SetVolume(Volume=%f, SamplerChannel=%d)\n", Volume, uiSamplerChannel));      dmsg(2,("LSCPServer: MuteNonSoloChannels()\n"));
1950        std::map<uint,SamplerChannel*> channels = pSampler->GetSamplerChannels();
1951        std::map<uint,SamplerChannel*>::iterator iter = channels.begin();
1952        for (; iter != channels.end(); iter++) {
1953            EngineChannel* c = iter->second->GetEngineChannel();
1954            if(c && !c->GetSolo() && !c->GetMute()) c->SetMute(-1);
1955        }
1956    }
1957    
1958    /**
1959     * Unmutes all channels that are muted because of the presence
1960     * of a solo channel(s).
1961     */
1962    void  LSCPServer::UnmuteChannels() {
1963        dmsg(2,("LSCPServer: UnmuteChannels()\n"));
1964        std::map<uint,SamplerChannel*> channels = pSampler->GetSamplerChannels();
1965        std::map<uint,SamplerChannel*>::iterator iter = channels.begin();
1966        for (; iter != channels.end(); iter++) {
1967            EngineChannel* c = iter->second->GetEngineChannel();
1968            if(c && c->GetMute() == -1) c->SetMute(0);
1969        }
1970    }
1971    
1972    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) {
1973        dmsg(2,("LSCPServer: AddOrReplaceMIDIInstrumentMapping()\n"));
1974    
1975        midi_prog_index_t idx;
1976        idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;
1977        idx.midi_bank_lsb = MidiBank & 0x7f;
1978        idx.midi_prog     = MidiProg;
1979    
1980        MidiInstrumentMapper::entry_t entry;
1981        entry.EngineName      = EngineType;
1982        entry.InstrumentFile  = InstrumentFile;
1983        entry.InstrumentIndex = InstrumentIndex;
1984        entry.LoadMode        = LoadMode;
1985        entry.Volume          = Volume;
1986        entry.Name            = Name;
1987    
1988        LSCPResultSet result;
1989        try {
1990            // PERSISTENT mapping commands might block for a long time, so in
1991            // that case we add/replace the mapping in another thread in case
1992            // the NON_MODAL argument was supplied, non persistent mappings
1993            // should return immediately, so we don't need to do that for them
1994            bool bInBackground = (entry.LoadMode == MidiInstrumentMapper::PERSISTENT && !bModal);
1995            MidiInstrumentMapper::AddOrReplaceEntry(MidiMapID, idx, entry, bInBackground);
1996        } catch (Exception e) {
1997            result.Error(e);
1998        }
1999        return result.Produce();
2000    }
2001    
2002    String LSCPServer::RemoveMIDIInstrumentMapping(uint MidiMapID, uint MidiBank, uint MidiProg) {
2003        dmsg(2,("LSCPServer: RemoveMIDIInstrumentMapping()\n"));
2004    
2005        midi_prog_index_t idx;
2006        idx.midi_bank_msb = (MidiBank >> 7) & 0x7f;
2007        idx.midi_bank_lsb = MidiBank & 0x7f;
2008        idx.midi_prog     = MidiProg;
2009    
2010        LSCPResultSet result;
2011        try {
2012            MidiInstrumentMapper::RemoveEntry(MidiMapID, idx);
2013        } catch (Exception e) {
2014            result.Error(e);
2015        }
2016        return result.Produce();
2017    }
2018    
2019    String LSCPServer::GetMidiInstrumentMappings(uint MidiMapID) {
2020        dmsg(2,("LSCPServer: GetMidiInstrumentMappings()\n"));
2021        LSCPResultSet result;
2022        try {
2023            result.Add(MidiInstrumentMapper::GetInstrumentCount(MidiMapID));
2024        } catch (Exception e) {
2025            result.Error(e);
2026        }
2027        return result.Produce();
2028    }
2029    
2030    
2031    String LSCPServer::GetAllMidiInstrumentMappings() {
2032        dmsg(2,("LSCPServer: GetAllMidiInstrumentMappings()\n"));
2033        LSCPResultSet result;
2034        try {
2035            result.Add(MidiInstrumentMapper::GetInstrumentCount());
2036        } catch (Exception e) {
2037            result.Error(e);
2038        }
2039        return result.Produce();
2040    }
2041    
2042    String LSCPServer::GetMidiInstrumentMapping(uint MidiMapID, uint MidiBank, uint MidiProg) {
2043        dmsg(2,("LSCPServer: GetMidiIstrumentMapping()\n"));
2044        LSCPResultSet result;
2045        try {
2046            MidiInstrumentMapper::entry_t entry = MidiInstrumentMapper::GetEntry(MidiMapID, MidiBank, MidiProg);
2047            // convert the filename into the correct encoding as defined for LSCP
2048            // (especially in terms of special characters -> escape sequences)
2049    #if WIN32
2050            const String instrumentFileName = Path::fromWindows(entry.InstrumentFile).toLscp();
2051    #else
2052            // assuming POSIX
2053            const String instrumentFileName = Path::fromPosix(entry.InstrumentFile).toLscp();
2054    #endif
2055    
2056            result.Add("NAME", _escapeLscpResponse(entry.Name));
2057            result.Add("ENGINE_NAME", entry.EngineName);
2058            result.Add("INSTRUMENT_FILE", instrumentFileName);
2059            result.Add("INSTRUMENT_NR", (int) entry.InstrumentIndex);
2060            String instrumentName;
2061            Engine* pEngine = EngineFactory::Create(entry.EngineName);
2062            if (pEngine) {
2063                if (pEngine->GetInstrumentManager()) {
2064                    InstrumentManager::instrument_id_t instrID;
2065                    instrID.FileName = entry.InstrumentFile;
2066                    instrID.Index    = entry.InstrumentIndex;
2067                    instrumentName = pEngine->GetInstrumentManager()->GetInstrumentName(instrID);
2068                }
2069                EngineFactory::Destroy(pEngine);
2070            }
2071            result.Add("INSTRUMENT_NAME", _escapeLscpResponse(instrumentName));
2072            switch (entry.LoadMode) {
2073                case MidiInstrumentMapper::ON_DEMAND:
2074                    result.Add("LOAD_MODE", "ON_DEMAND");
2075                    break;
2076                case MidiInstrumentMapper::ON_DEMAND_HOLD:
2077                    result.Add("LOAD_MODE", "ON_DEMAND_HOLD");
2078                    break;
2079                case MidiInstrumentMapper::PERSISTENT:
2080                    result.Add("LOAD_MODE", "PERSISTENT");
2081                    break;
2082                default:
2083                    throw Exception("entry reflects invalid LOAD_MODE, consider this as a bug!");
2084            }
2085            result.Add("VOLUME", entry.Volume);
2086        } catch (Exception e) {
2087            result.Error(e);
2088        }
2089        return result.Produce();
2090    }
2091    
2092    String LSCPServer::ListMidiInstrumentMappings(uint MidiMapID) {
2093        dmsg(2,("LSCPServer: ListMidiInstrumentMappings()\n"));
2094        LSCPResultSet result;
2095        try {
2096            String s;
2097            std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(MidiMapID);
2098            std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.begin();
2099            for (; iter != mappings.end(); iter++) {
2100                if (s.size()) s += ",";
2101                s += "{" + ToString(MidiMapID) + ","
2102                         + ToString((int(iter->first.midi_bank_msb) << 7) | int(iter->first.midi_bank_lsb)) + ","
2103                         + ToString(int(iter->first.midi_prog)) + "}";
2104            }
2105            result.Add(s);
2106        } catch (Exception e) {
2107            result.Error(e);
2108        }
2109        return result.Produce();
2110    }
2111    
2112    String LSCPServer::ListAllMidiInstrumentMappings() {
2113        dmsg(2,("LSCPServer: ListAllMidiInstrumentMappings()\n"));
2114        LSCPResultSet result;
2115        try {
2116            std::vector<int> maps = MidiInstrumentMapper::Maps();
2117            String s;
2118            for (int i = 0; i < maps.size(); i++) {
2119                std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t> mappings = MidiInstrumentMapper::Entries(maps[i]);
2120                std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.begin();
2121                for (; iter != mappings.end(); iter++) {
2122                    if (s.size()) s += ",";
2123                    s += "{" + ToString(maps[i]) + ","
2124                             + ToString((int(iter->first.midi_bank_msb) << 7) | int(iter->first.midi_bank_lsb)) + ","
2125                             + ToString(int(iter->first.midi_prog)) + "}";
2126                }
2127            }
2128            result.Add(s);
2129        } catch (Exception e) {
2130            result.Error(e);
2131        }
2132        return result.Produce();
2133    }
2134    
2135    String LSCPServer::ClearMidiInstrumentMappings(uint MidiMapID) {
2136        dmsg(2,("LSCPServer: ClearMidiInstrumentMappings()\n"));
2137        LSCPResultSet result;
2138        try {
2139            MidiInstrumentMapper::RemoveAllEntries(MidiMapID);
2140        } catch (Exception e) {
2141            result.Error(e);
2142        }
2143        return result.Produce();
2144    }
2145    
2146    String LSCPServer::ClearAllMidiInstrumentMappings() {
2147        dmsg(2,("LSCPServer: ClearAllMidiInstrumentMappings()\n"));
2148        LSCPResultSet result;
2149        try {
2150            std::vector<int> maps = MidiInstrumentMapper::Maps();
2151            for (int i = 0; i < maps.size(); i++)
2152                MidiInstrumentMapper::RemoveAllEntries(maps[i]);
2153        } catch (Exception e) {
2154            result.Error(e);
2155        }
2156        return result.Produce();
2157    }
2158    
2159    String LSCPServer::AddMidiInstrumentMap(String MapName) {
2160        dmsg(2,("LSCPServer: AddMidiInstrumentMap()\n"));
2161        LSCPResultSet result;
2162        try {
2163            int MapID = MidiInstrumentMapper::AddMap(MapName);
2164            result = LSCPResultSet(MapID);
2165        } catch (Exception e) {
2166            result.Error(e);
2167        }
2168        return result.Produce();
2169    }
2170    
2171    String LSCPServer::RemoveMidiInstrumentMap(uint MidiMapID) {
2172        dmsg(2,("LSCPServer: RemoveMidiInstrumentMap()\n"));
2173        LSCPResultSet result;
2174        try {
2175            MidiInstrumentMapper::RemoveMap(MidiMapID);
2176        } catch (Exception e) {
2177            result.Error(e);
2178        }
2179        return result.Produce();
2180    }
2181    
2182    String LSCPServer::RemoveAllMidiInstrumentMaps() {
2183        dmsg(2,("LSCPServer: RemoveAllMidiInstrumentMaps()\n"));
2184        LSCPResultSet result;
2185        try {
2186            MidiInstrumentMapper::RemoveAllMaps();
2187        } catch (Exception e) {
2188            result.Error(e);
2189        }
2190        return result.Produce();
2191    }
2192    
2193    String LSCPServer::GetMidiInstrumentMaps() {
2194        dmsg(2,("LSCPServer: GetMidiInstrumentMaps()\n"));
2195        LSCPResultSet result;
2196        try {
2197            result.Add(MidiInstrumentMapper::Maps().size());
2198        } catch (Exception e) {
2199            result.Error(e);
2200        }
2201        return result.Produce();
2202    }
2203    
2204    String LSCPServer::ListMidiInstrumentMaps() {
2205        dmsg(2,("LSCPServer: ListMidiInstrumentMaps()\n"));
2206        LSCPResultSet result;
2207        try {
2208            std::vector<int> maps = MidiInstrumentMapper::Maps();
2209            String sList;
2210            for (int i = 0; i < maps.size(); i++) {
2211                if (sList != "") sList += ",";
2212                sList += ToString(maps[i]);
2213            }
2214            result.Add(sList);
2215        } catch (Exception e) {
2216            result.Error(e);
2217        }
2218        return result.Produce();
2219    }
2220    
2221    String LSCPServer::GetMidiInstrumentMap(uint MidiMapID) {
2222        dmsg(2,("LSCPServer: GetMidiInstrumentMap()\n"));
2223        LSCPResultSet result;
2224        try {
2225            result.Add("NAME", _escapeLscpResponse(MidiInstrumentMapper::MapName(MidiMapID)));
2226            result.Add("DEFAULT", MidiInstrumentMapper::GetDefaultMap() == MidiMapID);
2227        } catch (Exception e) {
2228            result.Error(e);
2229        }
2230        return result.Produce();
2231    }
2232    
2233    String LSCPServer::SetMidiInstrumentMapName(uint MidiMapID, String NewName) {
2234        dmsg(2,("LSCPServer: SetMidiInstrumentMapName()\n"));
2235        LSCPResultSet result;
2236        try {
2237            MidiInstrumentMapper::RenameMap(MidiMapID, NewName);
2238        } catch (Exception e) {
2239            result.Error(e);
2240        }
2241        return result.Produce();
2242    }
2243    
2244    /**
2245     * Set the MIDI instrument map the given sampler channel shall use for
2246     * handling MIDI program change messages. There are the following two
2247     * special (negative) values:
2248     *
2249     *    - (-1) :  set to NONE (ignore program changes)
2250     *    - (-2) :  set to DEFAULT map
2251     */
2252    String LSCPServer::SetChannelMap(uint uiSamplerChannel, int MidiMapID) {
2253        dmsg(2,("LSCPServer: SetChannelMap()\n"));
2254      LSCPResultSet result;      LSCPResultSet result;
2255      try {      try {
2256          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
2257          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
2258          Engine* pEngine = pSamplerChannel->GetEngine();  
2259          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
2260          pEngine->Volume(Volume);          if (!pEngineChannel) throw Exception("There is no engine deployed on this sampler channel yet");
2261    
2262            if      (MidiMapID == -1) pEngineChannel->SetMidiInstrumentMapToNone();
2263            else if (MidiMapID == -2) pEngineChannel->SetMidiInstrumentMapToDefault();
2264            else                      pEngineChannel->SetMidiInstrumentMap(MidiMapID);
2265        } catch (Exception e) {
2266            result.Error(e);
2267      }      }
2268      catch (LinuxSamplerException e) {      return result.Produce();
2269           result.Error(e);  }
2270    
2271    String LSCPServer::CreateFxSend(uint uiSamplerChannel, uint MidiCtrl, String Name) {
2272        dmsg(2,("LSCPServer: CreateFxSend()\n"));
2273        LSCPResultSet result;
2274        try {
2275            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2276    
2277            FxSend* pFxSend = pEngineChannel->AddFxSend(MidiCtrl, Name);
2278            if (!pFxSend) throw Exception("Could not add FxSend, don't ask, I don't know why (probably a bug)");
2279    
2280            result = LSCPResultSet(pFxSend->Id()); // success
2281        } catch (Exception e) {
2282            result.Error(e);
2283        }
2284        return result.Produce();
2285    }
2286    
2287    String LSCPServer::DestroyFxSend(uint uiSamplerChannel, uint FxSendID) {
2288        dmsg(2,("LSCPServer: DestroyFxSend()\n"));
2289        LSCPResultSet result;
2290        try {
2291            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2292    
2293            FxSend* pFxSend = NULL;
2294            for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2295                if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2296                    pFxSend = pEngineChannel->GetFxSend(i);
2297                    break;
2298                }
2299            }
2300            if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2301            pEngineChannel->RemoveFxSend(pFxSend);
2302        } catch (Exception e) {
2303            result.Error(e);
2304        }
2305        return result.Produce();
2306    }
2307    
2308    String LSCPServer::GetFxSends(uint uiSamplerChannel) {
2309        dmsg(2,("LSCPServer: GetFxSends()\n"));
2310        LSCPResultSet result;
2311        try {
2312            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2313    
2314            result.Add(pEngineChannel->GetFxSendCount());
2315        } catch (Exception e) {
2316            result.Error(e);
2317        }
2318        return result.Produce();
2319    }
2320    
2321    String LSCPServer::ListFxSends(uint uiSamplerChannel) {
2322        dmsg(2,("LSCPServer: ListFxSends()\n"));
2323        LSCPResultSet result;
2324        String list;
2325        try {
2326            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2327    
2328            for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2329                FxSend* pFxSend = pEngineChannel->GetFxSend(i);
2330                if (list != "") list += ",";
2331                list += ToString(pFxSend->Id());
2332            }
2333            result.Add(list);
2334        } catch (Exception e) {
2335            result.Error(e);
2336        }
2337        return result.Produce();
2338    }
2339    
2340    FxSend* LSCPServer::GetFxSend(uint uiSamplerChannel, uint FxSendID) {
2341        EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2342    
2343        FxSend* pFxSend = NULL;
2344        for (int i = 0; i < pEngineChannel->GetFxSendCount(); i++) {
2345            if (pEngineChannel->GetFxSend(i)->Id() == FxSendID) {
2346                pFxSend = pEngineChannel->GetFxSend(i);
2347                break;
2348            }
2349        }
2350        if (!pFxSend) throw Exception("There is no FxSend with that ID on the given sampler channel");
2351        return pFxSend;
2352    }
2353    
2354    String LSCPServer::GetFxSendInfo(uint uiSamplerChannel, uint FxSendID) {
2355        dmsg(2,("LSCPServer: GetFxSendInfo()\n"));
2356        LSCPResultSet result;
2357        try {
2358            EngineChannel* pEngineChannel = GetEngineChannel(uiSamplerChannel);
2359            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2360    
2361            // gather audio routing informations
2362            String AudioRouting;
2363            for (int chan = 0; chan < pEngineChannel->Channels(); chan++) {
2364                if (AudioRouting != "") AudioRouting += ",";
2365                AudioRouting += ToString(pFxSend->DestinationChannel(chan));
2366            }
2367    
2368            // success
2369            result.Add("NAME", _escapeLscpResponse(pFxSend->Name()));
2370            result.Add("MIDI_CONTROLLER", pFxSend->MidiController());
2371            result.Add("LEVEL", ToString(pFxSend->Level()));
2372            result.Add("AUDIO_OUTPUT_ROUTING", AudioRouting);
2373        } catch (Exception e) {
2374            result.Error(e);
2375        }
2376        return result.Produce();
2377    }
2378    
2379    String LSCPServer::SetFxSendName(uint uiSamplerChannel, uint FxSendID, String Name) {
2380        dmsg(2,("LSCPServer: SetFxSendName()\n"));
2381        LSCPResultSet result;
2382        try {
2383            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2384    
2385            pFxSend->SetName(Name);
2386            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2387        } catch (Exception e) {
2388            result.Error(e);
2389        }
2390        return result.Produce();
2391    }
2392    
2393    String LSCPServer::SetFxSendAudioOutputChannel(uint uiSamplerChannel, uint FxSendID, uint FxSendChannel, uint DeviceChannel) {
2394        dmsg(2,("LSCPServer: SetFxSendAudioOutputChannel()\n"));
2395        LSCPResultSet result;
2396        try {
2397            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2398    
2399            pFxSend->SetDestinationChannel(FxSendChannel, DeviceChannel);
2400            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2401        } catch (Exception e) {
2402            result.Error(e);
2403        }
2404        return result.Produce();
2405    }
2406    
2407    String LSCPServer::SetFxSendMidiController(uint uiSamplerChannel, uint FxSendID, uint MidiController) {
2408        dmsg(2,("LSCPServer: SetFxSendMidiController()\n"));
2409        LSCPResultSet result;
2410        try {
2411            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2412    
2413            pFxSend->SetMidiController(MidiController);
2414            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2415        } catch (Exception e) {
2416            result.Error(e);
2417        }
2418        return result.Produce();
2419    }
2420    
2421    String LSCPServer::SetFxSendLevel(uint uiSamplerChannel, uint FxSendID, double dLevel) {
2422        dmsg(2,("LSCPServer: SetFxSendLevel()\n"));
2423        LSCPResultSet result;
2424        try {
2425            FxSend* pFxSend = GetFxSend(uiSamplerChannel, FxSendID);
2426    
2427            pFxSend->SetLevel((float)dLevel);
2428            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_fx_send_info, uiSamplerChannel, FxSendID));
2429        } catch (Exception e) {
2430            result.Error(e);
2431        }
2432        return result.Produce();
2433    }
2434    
2435    String LSCPServer::EditSamplerChannelInstrument(uint uiSamplerChannel) {
2436        dmsg(2,("LSCPServer: EditSamplerChannelInstrument(SamplerChannel=%d)\n", uiSamplerChannel));
2437        LSCPResultSet result;
2438        try {
2439            SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
2440            if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
2441            EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
2442            if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
2443            if (pEngineChannel->InstrumentStatus() < 0) throw Exception("No instrument loaded to sampler channel");
2444            Engine* pEngine = pEngineChannel->GetEngine();
2445            InstrumentManager* pInstrumentManager = pEngine->GetInstrumentManager();
2446            if (!pInstrumentManager) throw Exception("Engine does not provide an instrument manager");
2447            InstrumentManager::instrument_id_t instrumentID;
2448            instrumentID.FileName = pEngineChannel->InstrumentFileName();
2449            instrumentID.Index    = pEngineChannel->InstrumentIndex();
2450            pInstrumentManager->LaunchInstrumentEditor(instrumentID);
2451        } catch (Exception e) {
2452            result.Error(e);
2453      }      }
2454      return result.Produce();      return result.Produce();
2455  }  }
# Line 670  String LSCPServer::ResetChannel(uint uiS Line 2462  String LSCPServer::ResetChannel(uint uiS
2462      LSCPResultSet result;      LSCPResultSet result;
2463      try {      try {
2464          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);          SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(uiSamplerChannel);
2465          if (!pSamplerChannel) throw LinuxSamplerException("Index out of bounds");          if (!pSamplerChannel) throw Exception("Invalid sampler channel number " + ToString(uiSamplerChannel));
2466          Engine* pEngine = pSamplerChannel->GetEngine();          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
2467          if (!pEngine) throw LinuxSamplerException("No engine loaded on channel");          if (!pEngineChannel) throw Exception("No engine type assigned to sampler channel");
2468          pEngine->Reset();          pEngineChannel->Reset();
2469      }      }
2470      catch (LinuxSamplerException e) {      catch (Exception e) {
2471           result.Error(e);           result.Error(e);
2472      }      }
2473      return result.Produce();      return result.Produce();
2474  }  }
2475    
2476  /**  /**
2477     * Will be called by the parser to reset the whole sampler.
2478     */
2479    String LSCPServer::ResetSampler() {
2480        dmsg(2,("LSCPServer: ResetSampler()\n"));
2481        pSampler->Reset();
2482        LSCPResultSet result;
2483        return result.Produce();
2484    }
2485    
2486    /**
2487     * Will be called by the parser to return general informations about this
2488     * sampler.
2489     */
2490    String LSCPServer::GetServerInfo() {
2491        dmsg(2,("LSCPServer: GetServerInfo()\n"));
2492        const std::string description =
2493            _escapeLscpResponse("LinuxSampler - modular, streaming capable sampler");
2494        LSCPResultSet result;
2495        result.Add("DESCRIPTION", description);
2496        result.Add("VERSION", VERSION);
2497        result.Add("PROTOCOL_VERSION", ToString(LSCP_RELEASE_MAJOR) + "." + ToString(LSCP_RELEASE_MINOR));
2498    #if HAVE_SQLITE3
2499        result.Add("INSTRUMENTS_DB_SUPPORT", "yes");
2500    #else
2501        result.Add("INSTRUMENTS_DB_SUPPORT", "no");
2502    #endif
2503    
2504        return result.Produce();
2505    }
2506    
2507    /**
2508     * Will be called by the parser to return the current number of all active streams.
2509     */
2510    String LSCPServer::GetTotalStreamCount() {
2511        dmsg(2,("LSCPServer: GetTotalStreamCount()\n"));
2512        LSCPResultSet result;
2513        result.Add(pSampler->GetDiskStreamCount());
2514        return result.Produce();
2515    }
2516    
2517    /**
2518     * Will be called by the parser to return the current number of all active voices.
2519     */
2520    String LSCPServer::GetTotalVoiceCount() {
2521        dmsg(2,("LSCPServer: GetTotalVoiceCount()\n"));
2522        LSCPResultSet result;
2523        result.Add(pSampler->GetVoiceCount());
2524        return result.Produce();
2525    }
2526    
2527    /**
2528     * Will be called by the parser to return the maximum number of voices.
2529     */
2530    String LSCPServer::GetTotalVoiceCountMax() {
2531        dmsg(2,("LSCPServer: GetTotalVoiceCountMax()\n"));
2532        LSCPResultSet result;
2533        result.Add(EngineFactory::EngineInstances().size() * CONFIG_MAX_VOICES);
2534        return result.Produce();
2535    }
2536    
2537    String LSCPServer::GetGlobalVolume() {
2538        LSCPResultSet result;
2539        result.Add(ToString(GLOBAL_VOLUME)); // see common/global.cpp
2540        return result.Produce();
2541    }
2542    
2543    String LSCPServer::SetGlobalVolume(double dVolume) {
2544        LSCPResultSet result;
2545        try {
2546            if (dVolume < 0) throw Exception("Volume may not be negative");
2547            GLOBAL_VOLUME = dVolume; // see common/global_private.cpp
2548            LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_global_info, "VOLUME", GLOBAL_VOLUME));
2549        } catch (Exception e) {
2550            result.Error(e);
2551        }
2552        return result.Produce();
2553    }
2554    
2555    String LSCPServer::GetFileInstruments(String Filename) {
2556        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2557        LSCPResultSet result;
2558        try {
2559            VerifyFile(Filename);
2560        } catch (Exception e) {
2561            result.Error(e);
2562            return result.Produce();
2563        }
2564        // try to find a sampler engine that can handle the file
2565        bool bFound = false;
2566        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2567        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2568            Engine* pEngine = NULL;
2569            try {
2570                pEngine = EngineFactory::Create(engineTypes[i]);
2571                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2572                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2573                if (pManager) {
2574                    std::vector<InstrumentManager::instrument_id_t> IDs =
2575                        pManager->GetInstrumentFileContent(Filename);
2576                    // return the amount of instruments in the file
2577                    result.Add(IDs.size());
2578                    // no more need to ask other engine types
2579                    bFound = true;
2580                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2581            } catch (Exception e) {
2582                // NOOP, as exception is thrown if engine doesn't support file
2583            }
2584            if (pEngine) EngineFactory::Destroy(pEngine);
2585        }
2586    
2587        if (!bFound) result.Error("Unknown file format");
2588        return result.Produce();
2589    }
2590    
2591    String LSCPServer::ListFileInstruments(String Filename) {
2592        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2593        LSCPResultSet result;
2594        try {
2595            VerifyFile(Filename);
2596        } catch (Exception e) {
2597            result.Error(e);
2598            return result.Produce();
2599        }
2600        // try to find a sampler engine that can handle the file
2601        bool bFound = false;
2602        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2603        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2604            Engine* pEngine = NULL;
2605            try {
2606                pEngine = EngineFactory::Create(engineTypes[i]);
2607                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2608                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2609                if (pManager) {
2610                    std::vector<InstrumentManager::instrument_id_t> IDs =
2611                        pManager->GetInstrumentFileContent(Filename);
2612                    // return a list of IDs of the instruments in the file
2613                    String s;
2614                    for (int j = 0; j < IDs.size(); j++) {
2615                        if (s.size()) s += ",";
2616                        s += ToString(IDs[j].Index);
2617                    }
2618                    result.Add(s);
2619                    // no more need to ask other engine types
2620                    bFound = true;
2621                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2622            } catch (Exception e) {
2623                // NOOP, as exception is thrown if engine doesn't support file
2624            }
2625            if (pEngine) EngineFactory::Destroy(pEngine);
2626        }
2627    
2628        if (!bFound) result.Error("Unknown file format");
2629        return result.Produce();
2630    }
2631    
2632    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2633        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2634        LSCPResultSet result;
2635        try {
2636            VerifyFile(Filename);
2637        } catch (Exception e) {
2638            result.Error(e);
2639            return result.Produce();
2640        }
2641        InstrumentManager::instrument_id_t id;
2642        id.FileName = Filename;
2643        id.Index    = InstrumentID;
2644        // try to find a sampler engine that can handle the file
2645        bool bFound = false;
2646        bool bFatalErr = false;
2647        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2648        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2649            Engine* pEngine = NULL;
2650            try {
2651                pEngine = EngineFactory::Create(engineTypes[i]);
2652                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2653                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2654                if (pManager) {
2655                    // check if the instrument index is valid
2656                    // FIXME: this won't work if an engine only supports parts of the instrument file
2657                    std::vector<InstrumentManager::instrument_id_t> IDs =
2658                        pManager->GetInstrumentFileContent(Filename);
2659                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2660                        std::stringstream ss;
2661                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2662                        bFatalErr = true;
2663                        throw Exception(ss.str());
2664                    }
2665                    // get the info of the requested instrument
2666                    InstrumentManager::instrument_info_t info =
2667                        pManager->GetInstrumentInfo(id);
2668                    // return detailed informations about the file
2669                    result.Add("NAME", info.InstrumentName);
2670                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2671                    result.Add("FORMAT_VERSION", info.FormatVersion);
2672                    result.Add("PRODUCT", info.Product);
2673                    result.Add("ARTISTS", info.Artists);
2674                    // no more need to ask other engine types
2675                    bFound = true;
2676                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2677            } catch (Exception e) {
2678                // usually NOOP, as exception is thrown if engine doesn't support file
2679                if (bFatalErr) result.Error(e);
2680            }
2681            if (pEngine) EngineFactory::Destroy(pEngine);
2682        }
2683    
2684        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2685        return result.Produce();
2686    }
2687    
2688    void LSCPServer::VerifyFile(String Filename) {
2689        #if WIN32
2690        WIN32_FIND_DATA win32FileAttributeData;
2691        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2692        if (!res) {
2693            std::stringstream ss;
2694            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2695            throw Exception(ss.str());
2696        }
2697        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2698            throw Exception("Directory is specified");
2699        }
2700        #else
2701        struct stat statBuf;
2702        int res = stat(Filename.c_str(), &statBuf);
2703        if (res) {
2704            std::stringstream ss;
2705            ss << "Fail to stat `" << Filename << "`: " << strerror(errno);
2706            throw Exception(ss.str());
2707        }
2708    
2709        if (S_ISDIR(statBuf.st_mode)) {
2710            throw Exception("Directory is specified");
2711        }
2712        #endif
2713    }
2714    
2715    /**
2716   * 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
2717   * server for receiving event messages.   * server for receiving event messages.
2718   */   */
2719  String LSCPServer::SubscribeNotification(uint UDPPort) {  String LSCPServer::SubscribeNotification(LSCPEvent::event_t type) {
2720      dmsg(2,("LSCPServer: SubscribeNotification(UDPPort=%d)\n", UDPPort));      dmsg(2,("LSCPServer: SubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
2721      return "ERR:0:Not implemented yet.\r\n";      LSCPResultSet result;
2722        SubscriptionMutex.Lock();
2723        eventSubscriptions[type].push_back(currentSocket);
2724        SubscriptionMutex.Unlock();
2725        return result.Produce();
2726  }  }
2727    
2728  /**  /**
2729   * Will be called by the parser to unsubscribe a client on the server   * Will be called by the parser to unsubscribe a client on the server
2730   * for not receiving further event messages.   * for not receiving further event messages.
2731   */   */
2732  String LSCPServer::UnsubscribeNotification(String SessionID) {  String LSCPServer::UnsubscribeNotification(LSCPEvent::event_t type) {
2733      dmsg(2,("LSCPServer: UnsubscribeNotification(SessionID=%s)\n", SessionID.c_str()));      dmsg(2,("LSCPServer: UnsubscribeNotification(Event=%s)\n", LSCPEvent::Name(type).c_str()));
2734      return "ERR:0:Not implemented yet.\r\n";      LSCPResultSet result;
2735        SubscriptionMutex.Lock();
2736        eventSubscriptions[type].remove(currentSocket);
2737        SubscriptionMutex.Unlock();
2738        return result.Produce();
2739  }  }
2740    
2741    String LSCPServer::AddDbInstrumentDirectory(String Dir) {
2742        dmsg(2,("LSCPServer: AddDbInstrumentDirectory(Dir=%s)\n", Dir.c_str()));
2743        LSCPResultSet result;
2744    #if HAVE_SQLITE3
2745        try {
2746            InstrumentsDb::GetInstrumentsDb()->AddDirectory(Dir);
2747        } catch (Exception e) {
2748             result.Error(e);
2749        }
2750    #else
2751        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2752    #endif
2753        return result.Produce();
2754    }
2755    
2756  // Instrument loader constructor.  String LSCPServer::RemoveDbInstrumentDirectory(String Dir, bool Force) {
2757  LSCPLoadInstrument::LSCPLoadInstrument(Engine* pEngine, String Filename, uint uiInstrument)      dmsg(2,("LSCPServer: RemoveDbInstrumentDirectory(Dir=%s,Force=%d)\n", Dir.c_str(), Force));
2758      : Thread(false, 0, -4)      LSCPResultSet result;
2759  {  #if HAVE_SQLITE3
2760      this->pEngine = pEngine;      try {
2761      this->Filename = Filename;          InstrumentsDb::GetInstrumentsDb()->RemoveDirectory(Dir, Force);
2762      this->uiInstrument = uiInstrument;      } catch (Exception e) {
2763             result.Error(e);
2764        }
2765    #else
2766        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2767    #endif
2768        return result.Produce();
2769  }  }
2770    
2771  // Instrument loader process.  String LSCPServer::GetDbInstrumentDirectoryCount(String Dir, bool Recursive) {
2772  int LSCPLoadInstrument::Main()      dmsg(2,("LSCPServer: GetDbInstrumentDirectoryCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2773  {      LSCPResultSet result;
2774    #if HAVE_SQLITE3
2775        try {
2776            result.Add(InstrumentsDb::GetInstrumentsDb()->GetDirectoryCount(Dir, Recursive));
2777        } catch (Exception e) {
2778             result.Error(e);
2779        }
2780    #else
2781        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2782    #endif
2783        return result.Produce();
2784    }
2785    
2786    String LSCPServer::GetDbInstrumentDirectories(String Dir, bool Recursive) {
2787        dmsg(2,("LSCPServer: GetDbInstrumentDirectories(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2788        LSCPResultSet result;
2789    #if HAVE_SQLITE3
2790        try {
2791            String list;
2792            StringListPtr dirs = InstrumentsDb::GetInstrumentsDb()->GetDirectories(Dir, Recursive);
2793    
2794            for (int i = 0; i < dirs->size(); i++) {
2795                if (list != "") list += ",";
2796                list += "'" + InstrumentsDb::toEscapedPath(dirs->at(i)) + "'";
2797            }
2798    
2799            result.Add(list);
2800        } catch (Exception e) {
2801             result.Error(e);
2802        }
2803    #else
2804        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2805    #endif
2806        return result.Produce();
2807    }
2808    
2809    String LSCPServer::GetDbInstrumentDirectoryInfo(String Dir) {
2810        dmsg(2,("LSCPServer: GetDbInstrumentDirectoryInfo(Dir=%s)\n", Dir.c_str()));
2811        LSCPResultSet result;
2812    #if HAVE_SQLITE3
2813        try {
2814            DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2815    
2816            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2817            result.Add("CREATED", info.Created);
2818            result.Add("MODIFIED", info.Modified);
2819        } catch (Exception e) {
2820             result.Error(e);
2821        }
2822    #else
2823        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2824    #endif
2825        return result.Produce();
2826    }
2827    
2828    String LSCPServer::SetDbInstrumentDirectoryName(String Dir, String Name) {
2829        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryName(Dir=%s,Name=%s)\n", Dir.c_str(), Name.c_str()));
2830        LSCPResultSet result;
2831    #if HAVE_SQLITE3
2832        try {
2833            InstrumentsDb::GetInstrumentsDb()->RenameDirectory(Dir, Name);
2834        } catch (Exception e) {
2835             result.Error(e);
2836        }
2837    #else
2838        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2839    #endif
2840        return result.Produce();
2841    }
2842    
2843    String LSCPServer::MoveDbInstrumentDirectory(String Dir, String Dst) {
2844        dmsg(2,("LSCPServer: MoveDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2845        LSCPResultSet result;
2846    #if HAVE_SQLITE3
2847        try {
2848            InstrumentsDb::GetInstrumentsDb()->MoveDirectory(Dir, Dst);
2849        } catch (Exception e) {
2850             result.Error(e);
2851        }
2852    #else
2853        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2854    #endif
2855        return result.Produce();
2856    }
2857    
2858    String LSCPServer::CopyDbInstrumentDirectory(String Dir, String Dst) {
2859        dmsg(2,("LSCPServer: CopyDbInstrumentDirectory(Dir=%s,Dst=%s)\n", Dir.c_str(), Dst.c_str()));
2860        LSCPResultSet result;
2861    #if HAVE_SQLITE3
2862        try {
2863            InstrumentsDb::GetInstrumentsDb()->CopyDirectory(Dir, Dst);
2864        } catch (Exception e) {
2865             result.Error(e);
2866        }
2867    #else
2868        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2869    #endif
2870        return result.Produce();
2871    }
2872    
2873    String LSCPServer::SetDbInstrumentDirectoryDescription(String Dir, String Desc) {
2874        dmsg(2,("LSCPServer: SetDbInstrumentDirectoryDescription(Dir=%s,Desc=%s)\n", Dir.c_str(), Desc.c_str()));
2875        LSCPResultSet result;
2876    #if HAVE_SQLITE3
2877        try {
2878            InstrumentsDb::GetInstrumentsDb()->SetDirectoryDescription(Dir, Desc);
2879        } catch (Exception e) {
2880             result.Error(e);
2881        }
2882    #else
2883        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2884    #endif
2885        return result.Produce();
2886    }
2887    
2888    String LSCPServer::AddDbInstruments(String DbDir, String FilePath, int Index, bool bBackground) {
2889        dmsg(2,("LSCPServer: AddDbInstruments(DbDir=%s,FilePath=%s,Index=%d,bBackground=%d)\n", DbDir.c_str(), FilePath.c_str(), Index, bBackground));
2890        LSCPResultSet result;
2891    #if HAVE_SQLITE3
2892        try {
2893            int id;
2894            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2895            id = db->AddInstruments(DbDir, FilePath, Index, bBackground);
2896            if (bBackground) result = id;
2897        } catch (Exception e) {
2898             result.Error(e);
2899        }
2900    #else
2901        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2902    #endif
2903        return result.Produce();
2904    }
2905    
2906    String LSCPServer::AddDbInstruments(String ScanMode, String DbDir, String FsDir, bool bBackground) {
2907        dmsg(2,("LSCPServer: AddDbInstruments(ScanMode=%s,DbDir=%s,FsDir=%s,bBackground=%d)\n", ScanMode.c_str(), DbDir.c_str(), FsDir.c_str(), bBackground));
2908        LSCPResultSet result;
2909    #if HAVE_SQLITE3
2910        try {
2911            int id;
2912            InstrumentsDb* db = InstrumentsDb::GetInstrumentsDb();
2913            if (ScanMode.compare("RECURSIVE") == 0) {
2914               id = db->AddInstruments(RECURSIVE, DbDir, FsDir, bBackground);
2915            } else if (ScanMode.compare("NON_RECURSIVE") == 0) {
2916               id = db->AddInstruments(NON_RECURSIVE, DbDir, FsDir, bBackground);
2917            } else if (ScanMode.compare("FLAT") == 0) {
2918               id = db->AddInstruments(FLAT, DbDir, FsDir, bBackground);
2919            } else {
2920                throw Exception("Unknown scan mode: " + ScanMode);
2921            }
2922    
2923            if (bBackground) result = id;
2924        } catch (Exception e) {
2925             result.Error(e);
2926        }
2927    #else
2928        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2929    #endif
2930        return result.Produce();
2931    }
2932    
2933    String LSCPServer::RemoveDbInstrument(String Instr) {
2934        dmsg(2,("LSCPServer: RemoveDbInstrument(Instr=%s)\n", Instr.c_str()));
2935        LSCPResultSet result;
2936    #if HAVE_SQLITE3
2937        try {
2938            InstrumentsDb::GetInstrumentsDb()->RemoveInstrument(Instr);
2939        } catch (Exception e) {
2940             result.Error(e);
2941        }
2942    #else
2943        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2944    #endif
2945        return result.Produce();
2946    }
2947    
2948    String LSCPServer::GetDbInstrumentCount(String Dir, bool Recursive) {
2949        dmsg(2,("LSCPServer: GetDbInstrumentCount(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2950        LSCPResultSet result;
2951    #if HAVE_SQLITE3
2952        try {
2953            result.Add(InstrumentsDb::GetInstrumentsDb()->GetInstrumentCount(Dir, Recursive));
2954        } catch (Exception e) {
2955             result.Error(e);
2956        }
2957    #else
2958        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2959    #endif
2960        return result.Produce();
2961    }
2962    
2963    String LSCPServer::GetDbInstruments(String Dir, bool Recursive) {
2964        dmsg(2,("LSCPServer: GetDbInstruments(Dir=%s,Recursive=%d)\n", Dir.c_str(), Recursive));
2965        LSCPResultSet result;
2966    #if HAVE_SQLITE3
2967        try {
2968            String list;
2969            StringListPtr instrs = InstrumentsDb::GetInstrumentsDb()->GetInstruments(Dir, Recursive);
2970    
2971            for (int i = 0; i < instrs->size(); i++) {
2972                if (list != "") list += ",";
2973                list += "'" + InstrumentsDb::toEscapedPath(instrs->at(i)) + "'";
2974            }
2975    
2976            result.Add(list);
2977        } catch (Exception e) {
2978             result.Error(e);
2979        }
2980    #else
2981        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
2982    #endif
2983        return result.Produce();
2984    }
2985    
2986    String LSCPServer::GetDbInstrumentInfo(String Instr) {
2987        dmsg(2,("LSCPServer: GetDbInstrumentInfo(Instr=%s)\n", Instr.c_str()));
2988        LSCPResultSet result;
2989    #if HAVE_SQLITE3
2990        try {
2991            DbInstrument info = InstrumentsDb::GetInstrumentsDb()->GetInstrumentInfo(Instr);
2992    
2993            result.Add("INSTRUMENT_FILE", info.InstrFile);
2994            result.Add("INSTRUMENT_NR", info.InstrNr);
2995            result.Add("FORMAT_FAMILY", info.FormatFamily);
2996            result.Add("FORMAT_VERSION", info.FormatVersion);
2997            result.Add("SIZE", (int)info.Size);
2998            result.Add("CREATED", info.Created);
2999            result.Add("MODIFIED", info.Modified);
3000            result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
3001            result.Add("IS_DRUM", info.IsDrum);
3002            result.Add("PRODUCT", _escapeLscpResponse(info.Product));
3003            result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
3004            result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
3005        } catch (Exception e) {
3006             result.Error(e);
3007        }
3008    #else
3009        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3010    #endif
3011        return result.Produce();
3012    }
3013    
3014    String LSCPServer::GetDbInstrumentsJobInfo(int JobId) {
3015        dmsg(2,("LSCPServer: GetDbInstrumentsJobInfo(JobId=%d)\n", JobId));
3016        LSCPResultSet result;
3017    #if HAVE_SQLITE3
3018        try {
3019            ScanJob job = InstrumentsDb::GetInstrumentsDb()->Jobs.GetJobById(JobId);
3020    
3021            result.Add("FILES_TOTAL", job.FilesTotal);
3022            result.Add("FILES_SCANNED", job.FilesScanned);
3023            result.Add("SCANNING", job.Scanning);
3024            result.Add("STATUS", job.Status);
3025        } catch (Exception e) {
3026             result.Error(e);
3027        }
3028    #else
3029        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3030    #endif
3031        return result.Produce();
3032    }
3033    
3034    String LSCPServer::SetDbInstrumentName(String Instr, String Name) {
3035        dmsg(2,("LSCPServer: SetDbInstrumentName(Instr=%s,Name=%s)\n", Instr.c_str(), Name.c_str()));
3036        LSCPResultSet result;
3037    #if HAVE_SQLITE3
3038        try {
3039            InstrumentsDb::GetInstrumentsDb()->RenameInstrument(Instr, Name);
3040        } catch (Exception e) {
3041             result.Error(e);
3042        }
3043    #else
3044        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3045    #endif
3046        return result.Produce();
3047    }
3048    
3049    String LSCPServer::MoveDbInstrument(String Instr, String Dst) {
3050        dmsg(2,("LSCPServer: MoveDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3051        LSCPResultSet result;
3052    #if HAVE_SQLITE3
3053        try {
3054            InstrumentsDb::GetInstrumentsDb()->MoveInstrument(Instr, Dst);
3055        } catch (Exception e) {
3056             result.Error(e);
3057        }
3058    #else
3059        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3060    #endif
3061        return result.Produce();
3062    }
3063    
3064    String LSCPServer::CopyDbInstrument(String Instr, String Dst) {
3065        dmsg(2,("LSCPServer: CopyDbInstrument(Instr=%s,Dst=%s)\n", Instr.c_str(), Dst.c_str()));
3066        LSCPResultSet result;
3067    #if HAVE_SQLITE3
3068        try {
3069            InstrumentsDb::GetInstrumentsDb()->CopyInstrument(Instr, Dst);
3070        } catch (Exception e) {
3071             result.Error(e);
3072        }
3073    #else
3074        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3075    #endif
3076        return result.Produce();
3077    }
3078    
3079    String LSCPServer::SetDbInstrumentDescription(String Instr, String Desc) {
3080        dmsg(2,("LSCPServer: SetDbInstrumentDescription(Instr=%s,Desc=%s)\n", Instr.c_str(), Desc.c_str()));
3081        LSCPResultSet result;
3082    #if HAVE_SQLITE3
3083      try {      try {
3084          pEngine->LoadInstrument(Filename.c_str(), uiInstrument);          InstrumentsDb::GetInstrumentsDb()->SetInstrumentDescription(Instr, Desc);
3085        } catch (Exception e) {
3086             result.Error(e);
3087      }      }
3088    #else
3089        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3090    #endif
3091        return result.Produce();
3092    }
3093    
3094    String LSCPServer::SetDbInstrumentFilePath(String OldPath, String NewPath) {
3095        dmsg(2,("LSCPServer: SetDbInstrumentFilePath(OldPath=%s,NewPath=%s)\n", OldPath.c_str(), NewPath.c_str()));
3096        LSCPResultSet result;
3097    #if HAVE_SQLITE3
3098        try {
3099            InstrumentsDb::GetInstrumentsDb()->SetInstrumentFilePath(OldPath, NewPath);
3100        } catch (Exception e) {
3101             result.Error(e);
3102        }
3103    #else
3104        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3105    #endif
3106        return result.Produce();
3107    }
3108    
3109    String LSCPServer::FindLostDbInstrumentFiles() {
3110        dmsg(2,("LSCPServer: FindLostDbInstrumentFiles()\n"));
3111        LSCPResultSet result;
3112    #if HAVE_SQLITE3
3113        try {
3114            String list;
3115            StringListPtr pLostFiles = InstrumentsDb::GetInstrumentsDb()->FindLostInstrumentFiles();
3116    
3117      catch (LinuxSamplerException e) {          for (int i = 0; i < pLostFiles->size(); i++) {
3118          e.PrintMessage();              if (list != "") list += ",";
3119                list += "'" + pLostFiles->at(i) + "'";
3120            }
3121    
3122            result.Add(list);
3123        } catch (Exception e) {
3124             result.Error(e);
3125      }      }
3126    #else
3127        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3128    #endif
3129        return result.Produce();
3130    }
3131    
3132      // Always re-enable the engine.  String LSCPServer::FindDbInstrumentDirectories(String Dir, std::map<String,String> Parameters, bool Recursive) {
3133      pEngine->Enable();      dmsg(2,("LSCPServer: FindDbInstrumentDirectories(Dir=%s)\n", Dir.c_str()));
3134        LSCPResultSet result;
3135    #if HAVE_SQLITE3
3136        try {
3137            SearchQuery Query;
3138            std::map<String,String>::iterator iter;
3139            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3140                if (iter->first.compare("NAME") == 0) {
3141                    Query.Name = iter->second;
3142                } else if (iter->first.compare("CREATED") == 0) {
3143                    Query.SetCreated(iter->second);
3144                } else if (iter->first.compare("MODIFIED") == 0) {
3145                    Query.SetModified(iter->second);
3146                } else if (iter->first.compare("DESCRIPTION") == 0) {
3147                    Query.Description = iter->second;
3148                } else {
3149                    throw Exception("Unknown search criteria: " + iter->first);
3150                }
3151            }
3152    
3153      // FIXME: Shoot ourselves on the foot?          String list;
3154      delete this;          StringListPtr pDirectories =
3155                InstrumentsDb::GetInstrumentsDb()->FindDirectories(Dir, &Query, Recursive);
3156    
3157            for (int i = 0; i < pDirectories->size(); i++) {
3158                if (list != "") list += ",";
3159                list += "'" + InstrumentsDb::toEscapedPath(pDirectories->at(i)) + "'";
3160            }
3161    
3162            result.Add(list);
3163        } catch (Exception e) {
3164             result.Error(e);
3165        }
3166    #else
3167        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3168    #endif
3169        return result.Produce();
3170    }
3171    
3172    String LSCPServer::FindDbInstruments(String Dir, std::map<String,String> Parameters, bool Recursive) {
3173        dmsg(2,("LSCPServer: FindDbInstruments(Dir=%s)\n", Dir.c_str()));
3174        LSCPResultSet result;
3175    #if HAVE_SQLITE3
3176        try {
3177            SearchQuery Query;
3178            std::map<String,String>::iterator iter;
3179            for (iter = Parameters.begin(); iter != Parameters.end(); iter++) {
3180                if (iter->first.compare("NAME") == 0) {
3181                    Query.Name = iter->second;
3182                } else if (iter->first.compare("FORMAT_FAMILIES") == 0) {
3183                    Query.SetFormatFamilies(iter->second);
3184                } else if (iter->first.compare("SIZE") == 0) {
3185                    Query.SetSize(iter->second);
3186                } else if (iter->first.compare("CREATED") == 0) {
3187                    Query.SetCreated(iter->second);
3188                } else if (iter->first.compare("MODIFIED") == 0) {
3189                    Query.SetModified(iter->second);
3190                } else if (iter->first.compare("DESCRIPTION") == 0) {
3191                    Query.Description = iter->second;
3192                } else if (iter->first.compare("IS_DRUM") == 0) {
3193                    if (!strcasecmp(iter->second.c_str(), "true")) {
3194                        Query.InstrType = SearchQuery::DRUM;
3195                    } else {
3196                        Query.InstrType = SearchQuery::CHROMATIC;
3197                    }
3198                } else if (iter->first.compare("PRODUCT") == 0) {
3199                     Query.Product = iter->second;
3200                } else if (iter->first.compare("ARTISTS") == 0) {
3201                     Query.Artists = iter->second;
3202                } else if (iter->first.compare("KEYWORDS") == 0) {
3203                     Query.Keywords = iter->second;
3204                } else {
3205                    throw Exception("Unknown search criteria: " + iter->first);
3206                }
3207            }
3208    
3209            String list;
3210            StringListPtr pInstruments =
3211                InstrumentsDb::GetInstrumentsDb()->FindInstruments(Dir, &Query, Recursive);
3212    
3213            for (int i = 0; i < pInstruments->size(); i++) {
3214                if (list != "") list += ",";
3215                list += "'" + InstrumentsDb::toEscapedPath(pInstruments->at(i)) + "'";
3216            }
3217    
3218            result.Add(list);
3219        } catch (Exception e) {
3220             result.Error(e);
3221        }
3222    #else
3223        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3224    #endif
3225        return result.Produce();
3226    }
3227    
3228    String LSCPServer::FormatInstrumentsDb() {
3229        dmsg(2,("LSCPServer: FormatInstrumentsDb()\n"));
3230        LSCPResultSet result;
3231    #if HAVE_SQLITE3
3232        try {
3233            InstrumentsDb::GetInstrumentsDb()->Format();
3234        } catch (Exception e) {
3235             result.Error(e);
3236        }
3237    #else
3238        result.Error(String(DOESNT_HAVE_SQLITE3), 0);
3239    #endif
3240        return result.Produce();
3241    }
3242    
3243    
3244    /**
3245     * Will be called by the parser to enable or disable echo mode; if echo
3246     * mode is enabled, all commands from the client will (immediately) be
3247     * echoed back to the client.
3248     */
3249    String LSCPServer::SetEcho(yyparse_param_t* pSession, double boolean_value) {
3250        dmsg(2,("LSCPServer: SetEcho(val=%f)\n", boolean_value));
3251        LSCPResultSet result;
3252        try {
3253            if      (boolean_value == 0) pSession->bVerbose = false;
3254            else if (boolean_value == 1) pSession->bVerbose = true;
3255            else throw Exception("Not a boolean value, must either be 0 or 1");
3256        }
3257        catch (Exception e) {
3258             result.Error(e);
3259        }
3260        return result.Produce();
3261  }  }

Legend:
Removed from v.133  
changed lines
  Added in v.1763

  ViewVC Help
Powered by ViewVC